@vkontakte/videoplayer-core 2.0.124-dev.b149ab67.0 → 2.0.124-dev.c7e94945.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 +25 -25
- package/es2015.esm.js +26 -26
- package/es2018.cjs.js +24 -24
- package/es2018.esm.js +24 -24
- package/esnext.cjs.js +26 -26
- package/esnext.esm.js +28 -28
- package/evergreen.esm.js +23 -23
- package/package.json +2 -2
- package/types/providers/DashProvider/lib/player.d.ts +1 -0
- package/types/providers/utils/StallsManager.d.ts +2 -1
- package/types/utils/tuningConfig.d.ts +1 -0
package/esnext.esm.js
CHANGED
|
@@ -1,52 +1,52 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.124-dev.
|
|
3
|
-
* Mon,
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.124-dev.c7e94945.0
|
|
3
|
+
* Mon, 17 Feb 2025 07:30:12 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-124/doc/
|
|
5
5
|
*/
|
|
6
|
-
var my=Object.create;var Ol=Object.defineProperty;var fy=Object.getOwnPropertyDescriptor;var by=Object.getOwnPropertyNames;var gy=Object.getPrototypeOf,vy=Object.prototype.hasOwnProperty;var h=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var Sy=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of by(e))!vy.call(a,i)&&i!==t&&Ol(a,i,{get:()=>e[i],enumerable:!(r=fy(e,i))||r.enumerable});return a};var D=(a,e,t)=>(t=a!=null?my(gy(a)):{},Sy(e||!a||!a.__esModule?Ol(t,"default",{value:a,enumerable:!0}):t,a));var Y=h((yn,Nl)=>{"use strict";var Zr=function(a){return a&&a.Math===Math&&a};Nl.exports=Zr(typeof globalThis=="object"&&globalThis)||Zr(typeof window=="object"&&window)||Zr(typeof self=="object"&&self)||Zr(typeof global=="object"&&global)||Zr(typeof yn=="object"&&yn)||function(){return this}()||Function("return this")()});var ie=h((YD,Fl)=>{"use strict";Fl.exports=function(a){try{return!!a()}catch{return!0}}});var ei=h((zD,ql)=>{"use strict";var yy=ie();ql.exports=!yy(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Tn=h((KD,Gl)=>{"use strict";var Ty=ei(),jl=Function.prototype,Ul=jl.apply,Hl=jl.call;Gl.exports=typeof Reflect=="object"&&Reflect.apply||(Ty?Hl.bind(Ul):function(){return Hl.apply(Ul,arguments)})});var J=h((XD,Yl)=>{"use strict";var Ql=ei(),Wl=Function.prototype,In=Wl.call,Iy=Ql&&Wl.bind.bind(In,In);Yl.exports=Ql?Iy:function(a){return function(){return In.apply(a,arguments)}}});var Ut=h((JD,Kl)=>{"use strict";var zl=J(),Ey=zl({}.toString),xy=zl("".slice);Kl.exports=function(a){return xy(Ey(a),8,-1)}});var En=h((ZD,Xl)=>{"use strict";var Py=Ut(),wy=J();Xl.exports=function(a){if(Py(a)==="Function")return wy(a)}});var W=h((eC,Jl)=>{"use strict";var xn=typeof document=="object"&&document.all;Jl.exports=typeof xn>"u"&&xn!==void 0?function(a){return typeof a=="function"||a===xn}:function(a){return typeof a=="function"}});var Pe=h((tC,Zl)=>{"use strict";var ky=ie();Zl.exports=!ky(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var we=h((rC,ec)=>{"use strict";var Ay=ei(),Ha=Function.prototype.call;ec.exports=Ay?Ha.bind(Ha):function(){return Ha.apply(Ha,arguments)}});var Pn=h(ic=>{"use strict";var tc={}.propertyIsEnumerable,rc=Object.getOwnPropertyDescriptor,Ry=rc&&!tc.call({1:2},1);ic.f=Ry?function(e){var t=rc(this,e);return!!t&&t.enumerable}:tc});var ti=h((aC,ac)=>{"use strict";ac.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var nc=h((sC,sc)=>{"use strict";var Ly=J(),$y=ie(),My=Ut(),wn=Object,Dy=Ly("".split);sc.exports=$y(function(){return!wn("z").propertyIsEnumerable(0)})?function(a){return My(a)==="String"?Dy(a,""):wn(a)}:wn});var fr=h((nC,oc)=>{"use strict";oc.exports=function(a){return a==null}});var Tt=h((oC,uc)=>{"use strict";var Cy=fr(),Vy=TypeError;uc.exports=function(a){if(Cy(a))throw new Vy("Can't call method on "+a);return a}});var Ht=h((uC,lc)=>{"use strict";var By=nc(),Oy=Tt();lc.exports=function(a){return By(Oy(a))}});var ke=h((lC,cc)=>{"use strict";var _y=W();cc.exports=function(a){return typeof a=="object"?a!==null:_y(a)}});var br=h((cC,dc)=>{"use strict";dc.exports={}});var ut=h((dC,hc)=>{"use strict";var kn=br(),An=Y(),Ny=W(),pc=function(a){return Ny(a)?a:void 0};hc.exports=function(a,e){return arguments.length<2?pc(kn[a])||pc(An[a]):kn[a]&&kn[a][e]||An[a]&&An[a][e]}});var ri=h((pC,mc)=>{"use strict";var Fy=J();mc.exports=Fy({}.isPrototypeOf)});var jt=h((hC,gc)=>{"use strict";var qy=Y(),fc=qy.navigator,bc=fc&&fc.userAgent;gc.exports=bc?String(bc):""});var Ln=h((mC,Ec)=>{"use strict";var Ic=Y(),Rn=jt(),vc=Ic.process,Sc=Ic.Deno,yc=vc&&vc.versions||Sc&&Sc.version,Tc=yc&&yc.v8,Fe,ja;Tc&&(Fe=Tc.split("."),ja=Fe[0]>0&&Fe[0]<4?1:+(Fe[0]+Fe[1]));!ja&&Rn&&(Fe=Rn.match(/Edge\/(\d+)/),(!Fe||Fe[1]>=74)&&(Fe=Rn.match(/Chrome\/(\d+)/),Fe&&(ja=+Fe[1])));Ec.exports=ja});var $n=h((fC,Pc)=>{"use strict";var xc=Ln(),Uy=ie(),Hy=Y(),jy=Hy.String;Pc.exports=!!Object.getOwnPropertySymbols&&!Uy(function(){var a=Symbol("symbol detection");return!jy(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&xc&&xc<41})});var Mn=h((bC,wc)=>{"use strict";var Gy=$n();wc.exports=Gy&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Dn=h((gC,kc)=>{"use strict";var Qy=ut(),Wy=W(),Yy=ri(),zy=Mn(),Ky=Object;kc.exports=zy?function(a){return typeof a=="symbol"}:function(a){var e=Qy("Symbol");return Wy(e)&&Yy(e.prototype,Ky(a))}});var ii=h((vC,Ac)=>{"use strict";var Xy=String;Ac.exports=function(a){try{return Xy(a)}catch{return"Object"}}});var Je=h((SC,Rc)=>{"use strict";var Jy=W(),Zy=ii(),eT=TypeError;Rc.exports=function(a){if(Jy(a))return a;throw new eT(Zy(a)+" is not a function")}});var ai=h((yC,Lc)=>{"use strict";var tT=Je(),rT=fr();Lc.exports=function(a,e){var t=a[e];return rT(t)?void 0:tT(t)}});var Mc=h((TC,$c)=>{"use strict";var Cn=we(),Vn=W(),Bn=ke(),iT=TypeError;$c.exports=function(a,e){var t,r;if(e==="string"&&Vn(t=a.toString)&&!Bn(r=Cn(t,a))||Vn(t=a.valueOf)&&!Bn(r=Cn(t,a))||e!=="string"&&Vn(t=a.toString)&&!Bn(r=Cn(t,a)))return r;throw new iT("Can't convert object to primitive value")}});var qe=h((IC,Dc)=>{"use strict";Dc.exports=!0});var Bc=h((EC,Vc)=>{"use strict";var Cc=Y(),aT=Object.defineProperty;Vc.exports=function(a,e){try{aT(Cc,a,{value:e,configurable:!0,writable:!0})}catch{Cc[a]=e}return e}});var si=h((xC,Nc)=>{"use strict";var sT=qe(),nT=Y(),oT=Bc(),Oc="__core-js_shared__",_c=Nc.exports=nT[Oc]||oT(Oc,{});(_c.versions||(_c.versions=[])).push({version:"3.38.0",mode:sT?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var On=h((PC,qc)=>{"use strict";var Fc=si();qc.exports=function(a,e){return Fc[a]||(Fc[a]=e||{})}});var gr=h((wC,Uc)=>{"use strict";var uT=Tt(),lT=Object;Uc.exports=function(a){return lT(uT(a))}});var Ue=h((kC,Hc)=>{"use strict";var cT=J(),dT=gr(),pT=cT({}.hasOwnProperty);Hc.exports=Object.hasOwn||function(e,t){return pT(dT(e),t)}});var _n=h((AC,jc)=>{"use strict";var hT=J(),mT=0,fT=Math.random(),bT=hT(1 .toString);jc.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+bT(++mT+fT,36)}});var ae=h((RC,Qc)=>{"use strict";var gT=Y(),vT=On(),Gc=Ue(),ST=_n(),yT=$n(),TT=Mn(),vr=gT.Symbol,Nn=vT("wks"),IT=TT?vr.for||vr:vr&&vr.withoutSetter||ST;Qc.exports=function(a){return Gc(Nn,a)||(Nn[a]=yT&&Gc(vr,a)?vr[a]:IT("Symbol."+a)),Nn[a]}});var Kc=h((LC,zc)=>{"use strict";var ET=we(),Wc=ke(),Yc=Dn(),xT=ai(),PT=Mc(),wT=ae(),kT=TypeError,AT=wT("toPrimitive");zc.exports=function(a,e){if(!Wc(a)||Yc(a))return a;var t=xT(a,AT),r;if(t){if(e===void 0&&(e="default"),r=ET(t,a,e),!Wc(r)||Yc(r))return r;throw new kT("Can't convert object to primitive value")}return e===void 0&&(e="number"),PT(a,e)}});var Fn=h(($C,Xc)=>{"use strict";var RT=Kc(),LT=Dn();Xc.exports=function(a){var e=RT(a,"string");return LT(e)?e:e+""}});var Ga=h((MC,Zc)=>{"use strict";var $T=Y(),Jc=ke(),qn=$T.document,MT=Jc(qn)&&Jc(qn.createElement);Zc.exports=function(a){return MT?qn.createElement(a):{}}});var Un=h((DC,ed)=>{"use strict";var DT=Pe(),CT=ie(),VT=Ga();ed.exports=!DT&&!CT(function(){return Object.defineProperty(VT("div"),"a",{get:function(){return 7}}).a!==7})});var id=h(rd=>{"use strict";var BT=Pe(),OT=we(),_T=Pn(),NT=ti(),FT=Ht(),qT=Fn(),UT=Ue(),HT=Un(),td=Object.getOwnPropertyDescriptor;rd.f=BT?td:function(e,t){if(e=FT(e),t=qT(t),HT)try{return td(e,t)}catch{}if(UT(e,t))return NT(!OT(_T.f,e,t),e[t])}});var Hn=h((VC,ad)=>{"use strict";var jT=ie(),GT=W(),QT=/#|\.prototype\./,ni=function(a,e){var t=YT[WT(a)];return t===KT?!0:t===zT?!1:GT(e)?jT(e):!!e},WT=ni.normalize=function(a){return String(a).replace(QT,".").toLowerCase()},YT=ni.data={},zT=ni.NATIVE="N",KT=ni.POLYFILL="P";ad.exports=ni});var Sr=h((BC,nd)=>{"use strict";var sd=En(),XT=Je(),JT=ei(),ZT=sd(sd.bind);nd.exports=function(a,e){return XT(a),e===void 0?a:JT?ZT(a,e):function(){return a.apply(e,arguments)}}});var jn=h((OC,od)=>{"use strict";var eI=Pe(),tI=ie();od.exports=eI&&tI(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Ze=h((_C,ud)=>{"use strict";var rI=ke(),iI=String,aI=TypeError;ud.exports=function(a){if(rI(a))return a;throw new aI(iI(a)+" is not an object")}});var Gt=h(cd=>{"use strict";var sI=Pe(),nI=Un(),oI=jn(),Qa=Ze(),ld=Fn(),uI=TypeError,Gn=Object.defineProperty,lI=Object.getOwnPropertyDescriptor,Qn="enumerable",Wn="configurable",Yn="writable";cd.f=sI?oI?function(e,t,r){if(Qa(e),t=ld(t),Qa(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Yn in r&&!r[Yn]){var i=lI(e,t);i&&i[Yn]&&(e[t]=r.value,r={configurable:Wn in r?r[Wn]:i[Wn],enumerable:Qn in r?r[Qn]:i[Qn],writable:!1})}return Gn(e,t,r)}:Gn:function(e,t,r){if(Qa(e),t=ld(t),Qa(r),nI)try{return Gn(e,t,r)}catch{}if("get"in r||"set"in r)throw new uI("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var yr=h((FC,dd)=>{"use strict";var cI=Pe(),dI=Gt(),pI=ti();dd.exports=cI?function(a,e,t){return dI.f(a,e,pI(1,t))}:function(a,e,t){return a[e]=t,a}});var K=h((qC,hd)=>{"use strict";var oi=Y(),hI=Tn(),mI=En(),fI=W(),bI=id().f,gI=Hn(),Tr=br(),vI=Sr(),Ir=yr(),pd=Ue();si();var SI=function(a){var e=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,r)}return new a(t,r,i)}return hI(a,this,arguments)};return e.prototype=a.prototype,e};hd.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?oi:i?oi[t]:oi[t]&&oi[t].prototype,o=r?Tr:Tr[t]||Ir(Tr,t,{})[t],u=o.prototype,l,d,c,p,m,f,b,g,v;for(p in e)l=gI(r?p:t+(i?".":"#")+p,a.forced),d=!l&&n&&pd(n,p),f=o[p],d&&(a.dontCallGetSet?(v=bI(n,p),b=v&&v.value):b=n[p]),m=d&&b?b:e[p],!(!l&&!s&&typeof f==typeof m)&&(a.bind&&d?g=vI(m,oi):a.wrap&&d?g=SI(m):s&&fI(m)?g=mI(m):g=m,(a.sham||m&&m.sham||f&&f.sham)&&Ir(g,"sham",!0),Ir(o,p,g),s&&(c=t+"Prototype",pd(Tr,c)||Ir(Tr,c,{}),Ir(Tr[c],p,m),a.real&&u&&(l||!u[p])&&Ir(u,p,m)))}});var fd=h((UC,md)=>{"use strict";var yI=Math.ceil,TI=Math.floor;md.exports=Math.trunc||function(e){var t=+e;return(t>0?TI:yI)(t)}});var ui=h((HC,bd)=>{"use strict";var II=fd();bd.exports=function(a){var e=+a;return e!==e||e===0?0:II(e)}});var vd=h((jC,gd)=>{"use strict";var EI=ui(),xI=Math.max,PI=Math.min;gd.exports=function(a,e){var t=EI(a);return t<0?xI(t+e,0):PI(t,e)}});var zn=h((GC,Sd)=>{"use strict";var wI=ui(),kI=Math.min;Sd.exports=function(a){var e=wI(a);return e>0?kI(e,9007199254740991):0}});var Er=h((QC,yd)=>{"use strict";var AI=zn();yd.exports=function(a){return AI(a.length)}});var Kn=h((WC,Id)=>{"use strict";var RI=Ht(),LI=vd(),$I=Er(),Td=function(a){return function(e,t,r){var i=RI(e),s=$I(i);if(s===0)return!a&&-1;var n=LI(r,s),o;if(a&&t!==t){for(;s>n;)if(o=i[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in i)&&i[n]===t)return a||n||0;return!a&&-1}};Id.exports={includes:Td(!0),indexOf:Td(!1)}});var li=h((YC,Ed)=>{"use strict";Ed.exports=function(){}});var xd=h(()=>{"use strict";var MI=K(),DI=Kn().includes,CI=ie(),VI=li(),BI=CI(function(){return!Array(1).includes()});MI({target:"Array",proto:!0,forced:BI},{includes:function(e){return DI(this,e,arguments.length>1?arguments[1]:void 0)}});VI("includes")});var It=h((XC,Pd)=>{"use strict";var OI=ut();Pd.exports=OI});var kd=h((JC,wd)=>{"use strict";xd();var _I=It();wd.exports=_I("Array","includes")});var Rd=h((ZC,Ad)=>{"use strict";var NI=kd();Ad.exports=NI});var He=h((e0,Ld)=>{"use strict";var FI=Rd();Ld.exports=FI});var za=h((p0,_d)=>{"use strict";var YI=On(),zI=_n(),Od=YI("keys");_d.exports=function(a){return Od[a]||(Od[a]=zI(a))}});var Fd=h((h0,Nd)=>{"use strict";var KI=ie();Nd.exports=!KI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Ka=h((m0,Ud)=>{"use strict";var XI=Ue(),JI=W(),ZI=gr(),eE=za(),tE=Fd(),qd=eE("IE_PROTO"),Zn=Object,rE=Zn.prototype;Ud.exports=tE?Zn.getPrototypeOf:function(a){var e=ZI(a);if(XI(e,qd))return e[qd];var t=e.constructor;return JI(t)&&e instanceof t?t.prototype:e instanceof Zn?rE:null}});var Xa=h((f0,Hd)=>{"use strict";Hd.exports={}});var Qd=h((b0,Gd)=>{"use strict";var iE=J(),eo=Ue(),aE=Ht(),sE=Kn().indexOf,nE=Xa(),jd=iE([].push);Gd.exports=function(a,e){var t=aE(a),r=0,i=[],s;for(s in t)!eo(nE,s)&&eo(t,s)&&jd(i,s);for(;e.length>r;)eo(t,s=e[r++])&&(~sE(i,s)||jd(i,s));return i}});var to=h((g0,Wd)=>{"use strict";Wd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var ro=h((v0,Yd)=>{"use strict";var oE=Qd(),uE=to();Yd.exports=Object.keys||function(e){return oE(e,uE)}});var io=h((S0,Zd)=>{"use strict";var Kd=Pe(),lE=ie(),Xd=J(),cE=Ka(),dE=ro(),pE=Ht(),hE=Pn().f,Jd=Xd(hE),mE=Xd([].push),fE=Kd&&lE(function(){var a=Object.create(null);return a[2]=2,!Jd(a,2)}),zd=function(a){return function(e){for(var t=pE(e),r=dE(t),i=fE&&cE(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!Kd||(i?u in t:Jd(t,u)))&&mE(o,a?[u,t[u]]:t[u]);return o}};Zd.exports={entries:zd(!0),values:zd(!1)}});var ep=h(()=>{"use strict";var bE=K(),gE=io().entries;bE({target:"Object",stat:!0},{entries:function(e){return gE(e)}})});var rp=h((I0,tp)=>{"use strict";ep();var vE=br();tp.exports=vE.Object.entries});var ap=h((E0,ip)=>{"use strict";var SE=rp();ip.exports=SE});var xr=h((x0,sp)=>{"use strict";var yE=ap();sp.exports=yE});var Qt=h((P0,np)=>{"use strict";np.exports={}});var lp=h((w0,up)=>{"use strict";var TE=Y(),IE=W(),op=TE.WeakMap;up.exports=IE(op)&&/native code/.test(String(op))});var oo=h((k0,pp)=>{"use strict";var EE=lp(),dp=Y(),xE=ke(),PE=yr(),ao=Ue(),so=si(),wE=za(),kE=Xa(),cp="Object already initialized",no=dp.TypeError,AE=dp.WeakMap,Ja,ci,Za,RE=function(a){return Za(a)?ci(a):Ja(a,{})},LE=function(a){return function(e){var t;if(!xE(e)||(t=ci(e)).type!==a)throw new no("Incompatible receiver, "+a+" required");return t}};EE||so.state?(je=so.state||(so.state=new AE),je.get=je.get,je.has=je.has,je.set=je.set,Ja=function(a,e){if(je.has(a))throw new no(cp);return e.facade=a,je.set(a,e),e},ci=function(a){return je.get(a)||{}},Za=function(a){return je.has(a)}):(Wt=wE("state"),kE[Wt]=!0,Ja=function(a,e){if(ao(a,Wt))throw new no(cp);return e.facade=a,PE(a,Wt,e),e},ci=function(a){return ao(a,Wt)?a[Wt]:{}},Za=function(a){return ao(a,Wt)});var je,Wt;pp.exports={set:Ja,get:ci,has:Za,enforce:RE,getterFor:LE}});var co=h((A0,mp)=>{"use strict";var uo=Pe(),$E=Ue(),hp=Function.prototype,ME=uo&&Object.getOwnPropertyDescriptor,lo=$E(hp,"name"),DE=lo&&function(){}.name==="something",CE=lo&&(!uo||uo&&ME(hp,"name").configurable);mp.exports={EXISTS:lo,PROPER:DE,CONFIGURABLE:CE}});var bp=h(fp=>{"use strict";var VE=Pe(),BE=jn(),OE=Gt(),_E=Ze(),NE=Ht(),FE=ro();fp.f=VE&&!BE?Object.defineProperties:function(e,t){_E(e);for(var r=NE(t),i=FE(t),s=i.length,n=0,o;s>n;)OE.f(e,o=i[n++],r[o]);return e}});var po=h((L0,gp)=>{"use strict";var qE=ut();gp.exports=qE("document","documentElement")});var bo=h(($0,xp)=>{"use strict";var UE=Ze(),HE=bp(),vp=to(),jE=Xa(),GE=po(),QE=Ga(),WE=za(),Sp=">",yp="<",mo="prototype",fo="script",Ip=WE("IE_PROTO"),ho=function(){},Ep=function(a){return yp+fo+Sp+a+yp+"/"+fo+Sp},Tp=function(a){a.write(Ep("")),a.close();var e=a.parentWindow.Object;return a=null,e},YE=function(){var a=QE("iframe"),e="java"+fo+":",t;return a.style.display="none",GE.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Ep("document.F=Object")),t.close(),t.F},es,ts=function(){try{es=new ActiveXObject("htmlfile")}catch{}ts=typeof document<"u"?document.domain&&es?Tp(es):YE():Tp(es);for(var a=vp.length;a--;)delete ts[mo][vp[a]];return ts()};jE[Ip]=!0;xp.exports=Object.create||function(e,t){var r;return e!==null?(ho[mo]=UE(e),r=new ho,ho[mo]=null,r[Ip]=e):r=ts(),t===void 0?r:HE.f(r,t)}});var Pr=h((M0,Pp)=>{"use strict";var zE=yr();Pp.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:zE(a,e,t),a}});var yo=h((D0,Ap)=>{"use strict";var KE=ie(),XE=W(),JE=ke(),ZE=bo(),wp=Ka(),ex=Pr(),tx=ae(),rx=qe(),So=tx("iterator"),kp=!1,lt,go,vo;[].keys&&(vo=[].keys(),"next"in vo?(go=wp(wp(vo)),go!==Object.prototype&&(lt=go)):kp=!0);var ix=!JE(lt)||KE(function(){var a={};return lt[So].call(a)!==a});ix?lt={}:rx&&(lt=ZE(lt));XE(lt[So])||ex(lt,So,function(){return this});Ap.exports={IteratorPrototype:lt,BUGGY_SAFARI_ITERATORS:kp}});var rs=h((C0,Lp)=>{"use strict";var ax=ae(),sx=ax("toStringTag"),Rp={};Rp[sx]="z";Lp.exports=String(Rp)==="[object z]"});var di=h((V0,$p)=>{"use strict";var nx=rs(),ox=W(),is=Ut(),ux=ae(),lx=ux("toStringTag"),cx=Object,dx=is(function(){return arguments}())==="Arguments",px=function(a,e){try{return a[e]}catch{}};$p.exports=nx?is:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=px(e=cx(a),lx))=="string"?t:dx?is(e):(r=is(e))==="Object"&&ox(e.callee)?"Arguments":r}});var Dp=h((B0,Mp)=>{"use strict";var hx=rs(),mx=di();Mp.exports=hx?{}.toString:function(){return"[object "+mx(this)+"]"}});var pi=h((O0,Vp)=>{"use strict";var fx=rs(),bx=Gt().f,gx=yr(),vx=Ue(),Sx=Dp(),yx=ae(),Cp=yx("toStringTag");Vp.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(vx(i,Cp)||bx(i,Cp,{configurable:!0,value:e}),r&&!fx&&gx(i,"toString",Sx))}});var Op=h((_0,Bp)=>{"use strict";var Tx=yo().IteratorPrototype,Ix=bo(),Ex=ti(),xx=pi(),Px=Qt(),wx=function(){return this};Bp.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=Ix(Tx,{next:Ex(+!r,t)}),xx(a,i,!1,!0),Px[i]=wx,a}});var Np=h((N0,_p)=>{"use strict";var kx=J(),Ax=Je();_p.exports=function(a,e,t){try{return kx(Ax(Object.getOwnPropertyDescriptor(a,e)[t]))}catch{}}});var qp=h((F0,Fp)=>{"use strict";var Rx=ke();Fp.exports=function(a){return Rx(a)||a===null}});var Hp=h((q0,Up)=>{"use strict";var Lx=qp(),$x=String,Mx=TypeError;Up.exports=function(a){if(Lx(a))return a;throw new Mx("Can't set "+$x(a)+" as a prototype")}});var To=h((U0,jp)=>{"use strict";var Dx=Np(),Cx=ke(),Vx=Tt(),Bx=Hp();jp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=Dx(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch{}return function(i,s){return Vx(i),Bx(s),Cx(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var th=h((H0,eh)=>{"use strict";var Ox=K(),_x=we(),as=qe(),Jp=co(),Nx=W(),Fx=Op(),Gp=Ka(),Qp=To(),qx=pi(),Ux=yr(),Io=Pr(),Hx=ae(),Wp=Qt(),Zp=yo(),jx=Jp.PROPER,Gx=Jp.CONFIGURABLE,Yp=Zp.IteratorPrototype,ss=Zp.BUGGY_SAFARI_ITERATORS,hi=Hx("iterator"),zp="keys",mi="values",Kp="entries",Xp=function(){return this};eh.exports=function(a,e,t,r,i,s,n){Fx(t,e,r);var o=function(v){if(v===i&&p)return p;if(!ss&&v&&v in d)return d[v];switch(v){case zp:return function(){return new t(this,v)};case mi:return function(){return new t(this,v)};case Kp:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=a.prototype,c=d[hi]||d["@@iterator"]||i&&d[i],p=!ss&&c||o(i),m=e==="Array"&&d.entries||c,f,b,g;if(m&&(f=Gp(m.call(new a)),f!==Object.prototype&&f.next&&(!as&&Gp(f)!==Yp&&(Qp?Qp(f,Yp):Nx(f[hi])||Io(f,hi,Xp)),qx(f,u,!0,!0),as&&(Wp[u]=Xp))),jx&&i===mi&&c&&c.name!==mi&&(!as&&Gx?Ux(d,"name",mi):(l=!0,p=function(){return _x(c,this)})),i)if(b={values:o(mi),keys:s?p:o(zp),entries:o(Kp)},n)for(g in b)(ss||l||!(g in d))&&Io(d,g,b[g]);else Ox({target:e,proto:!0,forced:ss||l},b);return(!as||n)&&d[hi]!==p&&Io(d,hi,p,{name:i}),Wp[e]=p,b}});var ih=h((j0,rh)=>{"use strict";rh.exports=function(a,e){return{value:a,done:e}}});var xo=h((G0,uh)=>{"use strict";var Qx=Ht(),Eo=li(),ah=Qt(),nh=oo(),Wx=Gt().f,Yx=th(),ns=ih(),zx=qe(),Kx=Pe(),oh="Array Iterator",Xx=nh.set,Jx=nh.getterFor(oh);uh.exports=Yx(Array,"Array",function(a,e){Xx(this,{type:oh,target:Qx(a),index:0,kind:e})},function(){var a=Jx(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,ns(void 0,!0);switch(a.kind){case"keys":return ns(t,!1);case"values":return ns(e[t],!1)}return ns([t,e[t]],!1)},"values");var sh=ah.Arguments=ah.Array;Eo("keys");Eo("values");Eo("entries");if(!zx&&Kx&&sh.name!=="values")try{Wx(sh,"name",{value:"values"})}catch{}});var ch=h((Q0,lh)=>{"use strict";var Zx=ae(),eP=Qt(),tP=Zx("iterator"),rP=Array.prototype;lh.exports=function(a){return a!==void 0&&(eP.Array===a||rP[tP]===a)}});var Po=h((W0,ph)=>{"use strict";var iP=di(),dh=ai(),aP=fr(),sP=Qt(),nP=ae(),oP=nP("iterator");ph.exports=function(a){if(!aP(a))return dh(a,oP)||dh(a,"@@iterator")||sP[iP(a)]}});var mh=h((Y0,hh)=>{"use strict";var uP=we(),lP=Je(),cP=Ze(),dP=ii(),pP=Po(),hP=TypeError;hh.exports=function(a,e){var t=arguments.length<2?pP(a):e;if(lP(t))return cP(uP(t,a));throw new hP(dP(a)+" is not iterable")}});var gh=h((z0,bh)=>{"use strict";var mP=we(),fh=Ze(),fP=ai();bh.exports=function(a,e,t){var r,i;fh(a);try{if(r=fP(a,"return"),!r){if(e==="throw")throw t;return t}r=mP(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return fh(r),t}});var us=h((K0,Th)=>{"use strict";var bP=Sr(),gP=we(),vP=Ze(),SP=ii(),yP=ch(),TP=Er(),vh=ri(),IP=mh(),EP=Po(),Sh=gh(),xP=TypeError,os=function(a,e){this.stopped=a,this.result=e},yh=os.prototype;Th.exports=function(a,e,t){var r=t&&t.that,i=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=bP(e,r),l,d,c,p,m,f,b,g=function(w){return l&&Sh(l,"normal",w),new os(!0,w)},v=function(w){return i?(vP(w),o?u(w[0],w[1],g):u(w[0],w[1])):o?u(w,g):u(w)};if(s)l=a.iterator;else if(n)l=a;else{if(d=EP(a),!d)throw new xP(SP(a)+" is not iterable");if(yP(d)){for(c=0,p=TP(a);p>c;c++)if(m=v(a[c]),m&&vh(yh,m))return m;return new os(!1)}l=IP(a,d)}for(f=s?a.next:l.next;!(b=gP(f,l)).done;){try{m=v(b.value)}catch(w){Sh(l,"throw",w)}if(typeof m=="object"&&m&&vh(yh,m))return m}return new os(!1)}});var Eh=h((X0,Ih)=>{"use strict";var PP=Pe(),wP=Gt(),kP=ti();Ih.exports=function(a,e,t){PP?wP.f(a,e,kP(0,t)):a[e]=t}});var xh=h(()=>{"use strict";var AP=K(),RP=us(),LP=Eh();AP({target:"Object",stat:!0},{fromEntries:function(e){var t={};return RP(e,function(r,i){LP(t,r,i)},{AS_ENTRIES:!0}),t}})});var wh=h((eV,Ph)=>{"use strict";xo();xh();var $P=br();Ph.exports=$P.Object.fromEntries});var Ah=h((tV,kh)=>{"use strict";kh.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 Lh=h(()=>{"use strict";xo();var MP=Ah(),DP=Y(),CP=pi(),Rh=Qt();for(ls in MP)CP(DP[ls],ls),Rh[ls]=Rh.Array;var ls});var Mh=h((aV,$h)=>{"use strict";var VP=wh();Lh();$h.exports=VP});var wo=h((sV,Dh)=>{"use strict";var BP=Mh();Dh.exports=BP});var Ch=h(()=>{"use strict"});var ko=h((uV,Vh)=>{"use strict";var fi=Y(),OP=jt(),_P=Ut(),cs=function(a){return OP.slice(0,a.length)===a};Vh.exports=function(){return cs("Bun/")?"BUN":cs("Cloudflare-Workers")?"CLOUDFLARE":cs("Deno/")?"DENO":cs("Node.js/")?"NODE":fi.Bun&&typeof Bun.version=="string"?"BUN":fi.Deno&&typeof Deno.version=="object"?"DENO":_P(fi.process)==="process"?"NODE":fi.window&&fi.document?"BROWSER":"REST"}()});var ds=h((lV,Bh)=>{"use strict";var NP=ko();Bh.exports=NP==="NODE"});var _h=h((cV,Oh)=>{"use strict";var FP=Gt();Oh.exports=function(a,e,t){return FP.f(a,e,t)}});var qh=h((dV,Fh)=>{"use strict";var qP=ut(),UP=_h(),HP=ae(),jP=Pe(),Nh=HP("species");Fh.exports=function(a){var e=qP(a);jP&&e&&!e[Nh]&&UP(e,Nh,{configurable:!0,get:function(){return this}})}});var Hh=h((pV,Uh)=>{"use strict";var GP=ri(),QP=TypeError;Uh.exports=function(a,e){if(GP(e,a))return a;throw new QP("Incorrect invocation")}});var Ro=h((hV,jh)=>{"use strict";var WP=J(),YP=W(),Ao=si(),zP=WP(Function.toString);YP(Ao.inspectSource)||(Ao.inspectSource=function(a){return zP(a)});jh.exports=Ao.inspectSource});var $o=h((mV,zh)=>{"use strict";var KP=J(),XP=ie(),Gh=W(),JP=di(),ZP=ut(),ew=Ro(),Qh=function(){},Wh=ZP("Reflect","construct"),Lo=/^\s*(?:class|function)\b/,tw=KP(Lo.exec),rw=!Lo.test(Qh),bi=function(e){if(!Gh(e))return!1;try{return Wh(Qh,[],e),!0}catch{return!1}},Yh=function(e){if(!Gh(e))return!1;switch(JP(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return rw||!!tw(Lo,ew(e))}catch{return!0}};Yh.sham=!0;zh.exports=!Wh||XP(function(){var a;return bi(bi.call)||!bi(Object)||!bi(function(){a=!0})||a})?Yh:bi});var Xh=h((fV,Kh)=>{"use strict";var iw=$o(),aw=ii(),sw=TypeError;Kh.exports=function(a){if(iw(a))return a;throw new sw(aw(a)+" is not a constructor")}});var Mo=h((bV,Zh)=>{"use strict";var Jh=Ze(),nw=Xh(),ow=fr(),uw=ae(),lw=uw("species");Zh.exports=function(a,e){var t=Jh(a).constructor,r;return t===void 0||ow(r=Jh(t)[lw])?e:nw(r)}});var tm=h((gV,em)=>{"use strict";var cw=J();em.exports=cw([].slice)});var im=h((vV,rm)=>{"use strict";var dw=TypeError;rm.exports=function(a,e){if(a<e)throw new dw("Not enough arguments");return a}});var Do=h((SV,am)=>{"use strict";var pw=jt();am.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(pw)});var Uo=h((yV,hm)=>{"use strict";var Ae=Y(),hw=Tn(),mw=Sr(),sm=W(),fw=Ue(),pm=ie(),nm=po(),bw=tm(),om=Ga(),gw=im(),vw=Do(),Sw=ds(),No=Ae.setImmediate,Fo=Ae.clearImmediate,yw=Ae.process,Co=Ae.Dispatch,Tw=Ae.Function,um=Ae.MessageChannel,Iw=Ae.String,Vo=0,gi={},lm="onreadystatechange",vi,Yt,Bo,Oo;pm(function(){vi=Ae.location});var qo=function(a){if(fw(gi,a)){var e=gi[a];delete gi[a],e()}},_o=function(a){return function(){qo(a)}},cm=function(a){qo(a.data)},dm=function(a){Ae.postMessage(Iw(a),vi.protocol+"//"+vi.host)};(!No||!Fo)&&(No=function(e){gw(arguments.length,1);var t=sm(e)?e:Tw(e),r=bw(arguments,1);return gi[++Vo]=function(){hw(t,void 0,r)},Yt(Vo),Vo},Fo=function(e){delete gi[e]},Sw?Yt=function(a){yw.nextTick(_o(a))}:Co&&Co.now?Yt=function(a){Co.now(_o(a))}:um&&!vw?(Bo=new um,Oo=Bo.port2,Bo.port1.onmessage=cm,Yt=mw(Oo.postMessage,Oo)):Ae.addEventListener&&sm(Ae.postMessage)&&!Ae.importScripts&&vi&&vi.protocol!=="file:"&&!pm(dm)?(Yt=dm,Ae.addEventListener("message",cm,!1)):lm in om("script")?Yt=function(a){nm.appendChild(om("script"))[lm]=function(){nm.removeChild(this),qo(a)}}:Yt=function(a){setTimeout(_o(a),0)});hm.exports={set:No,clear:Fo}});var bm=h((TV,fm)=>{"use strict";var mm=Y(),Ew=Pe(),xw=Object.getOwnPropertyDescriptor;fm.exports=function(a){if(!Ew)return mm[a];var e=xw(mm,a);return e&&e.value}});var Ho=h((IV,vm)=>{"use strict";var gm=function(){this.head=null,this.tail=null};gm.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}}};vm.exports=gm});var ym=h((EV,Sm)=>{"use strict";var Pw=jt();Sm.exports=/ipad|iphone|ipod/i.test(Pw)&&typeof Pebble<"u"});var Im=h((xV,Tm)=>{"use strict";var ww=jt();Tm.exports=/web0s(?!.*chrome)/i.test(ww)});var Rm=h((PV,Am)=>{"use strict";var kr=Y(),kw=bm(),Em=Sr(),jo=Uo().set,Aw=Ho(),Rw=Do(),Lw=ym(),$w=Im(),Go=ds(),xm=kr.MutationObserver||kr.WebKitMutationObserver,Pm=kr.document,wm=kr.process,ps=kr.Promise,Yo=kw("queueMicrotask"),wr,Qo,Wo,hs,km;Yo||(Si=new Aw,yi=function(){var a,e;for(Go&&(a=wm.domain)&&a.exit();e=Si.get();)try{e()}catch(t){throw Si.head&&wr(),t}a&&a.enter()},!Rw&&!Go&&!$w&&xm&&Pm?(Qo=!0,Wo=Pm.createTextNode(""),new xm(yi).observe(Wo,{characterData:!0}),wr=function(){Wo.data=Qo=!Qo}):!Lw&&ps&&ps.resolve?(hs=ps.resolve(void 0),hs.constructor=ps,km=Em(hs.then,hs),wr=function(){km(yi)}):Go?wr=function(){wm.nextTick(yi)}:(jo=Em(jo,kr),wr=function(){jo(yi)}),Yo=function(a){Si.head||wr(),Si.add(a)});var Si,yi;Am.exports=Yo});var $m=h((wV,Lm)=>{"use strict";Lm.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch{}}});var ms=h((kV,Mm)=>{"use strict";Mm.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var zt=h((AV,Dm)=>{"use strict";var Mw=Y();Dm.exports=Mw.Promise});var Ar=h((RV,Om)=>{"use strict";var Dw=Y(),Ti=zt(),Cw=W(),Vw=Hn(),Bw=Ro(),Ow=ae(),Cm=ko(),_w=qe(),zo=Ln(),Vm=Ti&&Ti.prototype,Nw=Ow("species"),Ko=!1,Bm=Cw(Dw.PromiseRejectionEvent),Fw=Vw("Promise",function(){var a=Bw(Ti),e=a!==String(Ti);if(!e&&zo===66||_w&&!(Vm.catch&&Vm.finally))return!0;if(!zo||zo<51||!/native code/.test(a)){var t=new Ti(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[Nw]=r,Ko=t.then(function(){})instanceof r,!Ko)return!0}return!e&&(Cm==="BROWSER"||Cm==="DENO")&&!Bm});Om.exports={CONSTRUCTOR:Fw,REJECTION_EVENT:Bm,SUBCLASSING:Ko}});var Rr=h((LV,Nm)=>{"use strict";var _m=Je(),qw=TypeError,Uw=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new qw("Bad Promise constructor");e=r,t=i}),this.resolve=_m(e),this.reject=_m(t)};Nm.exports.f=function(a){return new Uw(a)}});var sf=h(()=>{"use strict";var Hw=K(),jw=qe(),vs=ds(),Et=Y(),Dr=we(),Fm=Pr(),qm=To(),Gw=pi(),Qw=qh(),Ww=Je(),gs=W(),Yw=ke(),zw=Hh(),Kw=Mo(),Qm=Uo().set,tu=Rm(),Xw=$m(),Jw=ms(),Zw=Ho(),Wm=oo(),Ss=zt(),ru=Ar(),Ym=Rr(),ys="Promise",zm=ru.CONSTRUCTOR,ek=ru.REJECTION_EVENT,tk=ru.SUBCLASSING,Xo=Wm.getterFor(ys),rk=Wm.set,Lr=Ss&&Ss.prototype,Kt=Ss,fs=Lr,Km=Et.TypeError,Jo=Et.document,iu=Et.process,Zo=Ym.f,ik=Zo,ak=!!(Jo&&Jo.createEvent&&Et.dispatchEvent),Xm="unhandledrejection",sk="rejectionhandled",Um=0,Jm=1,nk=2,au=1,Zm=2,bs,Hm,ok,jm,ef=function(a){var e;return Yw(a)&&gs(e=a.then)?e:!1},tf=function(a,e){var t=e.value,r=e.state===Jm,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,d;try{i?(r||(e.rejection===Zm&&lk(e),e.rejection=au),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),d=!0)),u===a.promise?n(new Km("Promise-chain cycle")):(l=ef(u))?Dr(l,u,s,n):s(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},rf=function(a,e){a.notified||(a.notified=!0,tu(function(){for(var t=a.reactions,r;r=t.get();)tf(r,a);a.notified=!1,e&&!a.rejection&&uk(a)}))},af=function(a,e,t){var r,i;ak?(r=Jo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Et.dispatchEvent(r)):r={promise:e,reason:t},!ek&&(i=Et["on"+a])?i(r):a===Xm&&Xw("Unhandled promise rejection",t)},uk=function(a){Dr(Qm,Et,function(){var e=a.facade,t=a.value,r=Gm(a),i;if(r&&(i=Jw(function(){vs?iu.emit("unhandledRejection",t,e):af(Xm,e,t)}),a.rejection=vs||Gm(a)?Zm:au,i.error))throw i.value})},Gm=function(a){return a.rejection!==au&&!a.parent},lk=function(a){Dr(Qm,Et,function(){var e=a.facade;vs?iu.emit("rejectionHandled",e):af(sk,e,a.value)})},$r=function(a,e,t){return function(r){a(e,r,t)}},Mr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=nk,rf(a,!0))},eu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Km("Promise can't be resolved itself");var r=ef(e);r?tu(function(){var i={done:!1};try{Dr(r,e,$r(eu,i,a),$r(Mr,i,a))}catch(s){Mr(i,s,a)}}):(a.value=e,a.state=Jm,rf(a,!1))}catch(i){Mr({done:!1},i,a)}}};if(zm&&(Kt=function(e){zw(this,fs),Ww(e),Dr(bs,this);var t=Xo(this);try{e($r(eu,t),$r(Mr,t))}catch(r){Mr(t,r)}},fs=Kt.prototype,bs=function(e){rk(this,{type:ys,done:!1,notified:!1,parent:!1,reactions:new Zw,rejection:!1,state:Um,value:void 0})},bs.prototype=Fm(fs,"then",function(e,t){var r=Xo(this),i=Zo(Kw(this,Kt));return r.parent=!0,i.ok=gs(e)?e:!0,i.fail=gs(t)&&t,i.domain=vs?iu.domain:void 0,r.state===Um?r.reactions.add(i):tu(function(){tf(i,r)}),i.promise}),Hm=function(){var a=new bs,e=Xo(a);this.promise=a,this.resolve=$r(eu,e),this.reject=$r(Mr,e)},Ym.f=Zo=function(a){return a===Kt||a===ok?new Hm(a):ik(a)},!jw&&gs(Ss)&&Lr!==Object.prototype)){jm=Lr.then,tk||Fm(Lr,"then",function(e,t){var r=this;return new Kt(function(i,s){Dr(jm,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Lr.constructor}catch{}qm&&qm(Lr,fs)}Hw({global:!0,constructor:!0,wrap:!0,forced:zm},{Promise:Kt});Gw(Kt,ys,!1,!0);Qw(ys)});var cf=h((DV,lf)=>{"use strict";var ck=ae(),of=ck("iterator"),uf=!1;try{nf=0,su={next:function(){return{done:!!nf++}},return:function(){uf=!0}},su[of]=function(){return this},Array.from(su,function(){throw 2})}catch{}var nf,su;lf.exports=function(a,e){try{if(!e&&!uf)return!1}catch{return!1}var t=!1;try{var r={};r[of]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch{}return t}});var nu=h((CV,df)=>{"use strict";var dk=zt(),pk=cf(),hk=Ar().CONSTRUCTOR;df.exports=hk||!pk(function(a){dk.all(a).then(void 0,function(){})})});var pf=h(()=>{"use strict";var mk=K(),fk=we(),bk=Je(),gk=Rr(),vk=ms(),Sk=us(),yk=nu();mk({target:"Promise",stat:!0,forced:yk},{all:function(e){var t=this,r=gk.f(t),i=r.resolve,s=r.reject,n=vk(function(){var o=bk(t.resolve),u=[],l=0,d=1;Sk(e,function(c){var p=l++,m=!1;d++,fk(o,t,c).then(function(f){m||(m=!0,u[p]=f,--d||i(u))},s)}),--d||i(u)});return n.error&&s(n.value),r.promise}})});var mf=h(()=>{"use strict";var Tk=K(),Ik=qe(),Ek=Ar().CONSTRUCTOR,uu=zt(),xk=ut(),Pk=W(),wk=Pr(),hf=uu&&uu.prototype;Tk({target:"Promise",proto:!0,forced:Ek,real:!0},{catch:function(a){return this.then(void 0,a)}});!Ik&&Pk(uu)&&(ou=xk("Promise").prototype.catch,hf.catch!==ou&&wk(hf,"catch",ou,{unsafe:!0}));var ou});var ff=h(()=>{"use strict";var kk=K(),Ak=we(),Rk=Je(),Lk=Rr(),$k=ms(),Mk=us(),Dk=nu();kk({target:"Promise",stat:!0,forced:Dk},{race:function(e){var t=this,r=Lk.f(t),i=r.reject,s=$k(function(){var n=Rk(t.resolve);Mk(e,function(o){Ak(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var bf=h(()=>{"use strict";var Ck=K(),Vk=Rr(),Bk=Ar().CONSTRUCTOR;Ck({target:"Promise",stat:!0,forced:Bk},{reject:function(e){var t=Vk.f(this),r=t.reject;return r(e),t.promise}})});var lu=h((HV,gf)=>{"use strict";var Ok=Ze(),_k=ke(),Nk=Rr();gf.exports=function(a,e){if(Ok(a),_k(e)&&e.constructor===a)return e;var t=Nk.f(a),r=t.resolve;return r(e),t.promise}});var yf=h(()=>{"use strict";var Fk=K(),qk=ut(),vf=qe(),Uk=zt(),Sf=Ar().CONSTRUCTOR,Hk=lu(),jk=qk("Promise"),Gk=vf&&!Sf;Fk({target:"Promise",stat:!0,forced:vf||Sf},{resolve:function(e){return Hk(Gk&&this===jk?Uk:this,e)}})});var Tf=h(()=>{"use strict";sf();pf();mf();ff();bf();yf()});var Pf=h(()=>{"use strict";var Qk=K(),Wk=qe(),Ts=zt(),Yk=ie(),Ef=ut(),xf=W(),zk=Mo(),If=lu(),Kk=Pr(),du=Ts&&Ts.prototype,Xk=!!Ts&&Yk(function(){du.finally.call({then:function(){}},function(){})});Qk({target:"Promise",proto:!0,real:!0,forced:Xk},{finally:function(a){var e=zk(this,Ef("Promise")),t=xf(a);return this.then(t?function(r){return If(e,a()).then(function(){return r})}:a,t?function(r){return If(e,a()).then(function(){throw r})}:a)}});!Wk&&xf(Ts)&&(cu=Ef("Promise").prototype.finally,du.finally!==cu&&Kk(du,"finally",cu,{unsafe:!0}));var cu});var kf=h((KV,wf)=>{"use strict";Ch();Tf();Pf();var Jk=It();wf.exports=Jk("Promise","finally")});var Rf=h((XV,Af)=>{"use strict";var Zk=kf();Af.exports=Zk});var Is=h((JV,Lf)=>{"use strict";var eA=Rf();Lf.exports=eA});var Hf=h(()=>{"use strict";var mA=K(),fA=io().values;mA({target:"Object",stat:!0},{values:function(e){return fA(e)}})});var Gf=h((BB,jf)=>{"use strict";Hf();var bA=br();jf.exports=bA.Object.values});var Wf=h((OB,Qf)=>{"use strict";var gA=Gf();Qf.exports=gA});var Vr=h((_B,Yf)=>{"use strict";var vA=Wf();Yf.exports=vA});var ob=h(()=>{"use strict";var CA=K(),VA=gr(),BA=Er(),OA=ui(),_A=li();CA({target:"Array",proto:!0},{at:function(e){var t=VA(this),r=BA(t),i=OA(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});_A("at")});var lb=h((pO,ub)=>{"use strict";ob();var NA=It();ub.exports=NA("Array","at")});var db=h((hO,cb)=>{"use strict";var FA=lb();cb.exports=FA});var Or=h((mO,pb)=>{"use strict";var qA=db();pb.exports=qA});var Cu=h((F_,Ub)=>{"use strict";var IR=Ut();Ub.exports=Array.isArray||function(e){return IR(e)==="Array"}});var jb=h((q_,Hb)=>{"use strict";var ER=TypeError,xR=9007199254740991;Hb.exports=function(a){if(a>xR)throw ER("Maximum allowed index exceeded");return a}});var Wb=h((U_,Qb)=>{"use strict";var PR=Cu(),wR=Er(),kR=jb(),AR=Sr(),Gb=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,d=n?AR(n,o):!1,c,p;l<r;)l in t&&(c=d?d(t[l],l,e):t[l],s>0&&PR(c)?(p=wR(c),u=Gb(a,e,c,p,u,s-1)-1):(kR(u+1),a[u]=c),u++),l++;return u};Qb.exports=Gb});var Xb=h((H_,Kb)=>{"use strict";var Yb=Cu(),RR=$o(),LR=ke(),$R=ae(),MR=$R("species"),zb=Array;Kb.exports=function(a){var e;return Yb(a)&&(e=a.constructor,RR(e)&&(e===zb||Yb(e.prototype))?e=void 0:LR(e)&&(e=e[MR],e===null&&(e=void 0))),e===void 0?zb:e}});var Zb=h((j_,Jb)=>{"use strict";var DR=Xb();Jb.exports=function(a,e){return new(DR(a))(e===0?0:e)}});var eg=h(()=>{"use strict";var CR=K(),VR=Wb(),BR=Je(),OR=gr(),_R=Er(),NR=Zb();CR({target:"Array",proto:!0},{flatMap:function(e){var t=OR(this),r=_R(t),i;return BR(e),i=NR(t,0),i.length=VR(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var tg=h(()=>{"use strict";var FR=li();FR("flatMap")});var ig=h((z_,rg)=>{"use strict";eg();tg();var qR=It();rg.exports=qR("Array","flatMap")});var sg=h((K_,ag)=>{"use strict";var UR=ig();ag.exports=UR});var Vu=h((X_,ng)=>{"use strict";var HR=sg();ng.exports=HR});var Bi=h((oN,bg)=>{"use strict";var XR=di(),JR=String;bg.exports=function(a){if(XR(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return JR(a)}});var Ou=h((uN,gg)=>{"use strict";gg.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 yg=h((lN,Sg)=>{"use strict";var ZR=J(),eL=Tt(),tL=Bi(),Nu=Ou(),vg=ZR("".replace),rL=RegExp("^["+Nu+"]+"),iL=RegExp("(^|[^"+Nu+"])["+Nu+"]+$"),_u=function(a){return function(e){var t=tL(eL(e));return a&1&&(t=vg(t,rL,"")),a&2&&(t=vg(t,iL,"$1")),t}};Sg.exports={start:_u(1),end:_u(2),trim:_u(3)}});var xg=h((cN,Eg)=>{"use strict";var aL=co().PROPER,sL=ie(),Tg=Ou(),Ig="\u200B\x85\u180E";Eg.exports=function(a){return sL(function(){return!!Tg[a]()||Ig[a]()!==Ig||aL&&Tg[a].name!==a})}});var Fu=h((dN,Pg)=>{"use strict";var nL=yg().start,oL=xg();Pg.exports=oL("trimStart")?function(){return nL(this)}:"".trimStart});var kg=h(()=>{"use strict";var uL=K(),wg=Fu();uL({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==wg},{trimLeft:wg})});var Rg=h(()=>{"use strict";kg();var lL=K(),Ag=Fu();lL({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Ag},{trimStart:Ag})});var $g=h((bN,Lg)=>{"use strict";Rg();var cL=It();Lg.exports=cL("String","trimLeft")});var Dg=h((gN,Mg)=>{"use strict";var dL=$g();Mg.exports=dL});var Vg=h((vN,Cg)=>{"use strict";var pL=Dg();Cg.exports=pL});var Xg=h(()=>{"use strict"});var Jg=h(()=>{"use strict"});var ev=h((Xq,Zg)=>{"use strict";var VL=ke(),BL=Ut(),OL=ae(),_L=OL("match");Zg.exports=function(a){var e;return VL(a)&&((e=a[_L])!==void 0?!!e:BL(a)==="RegExp")}});var rv=h((Jq,tv)=>{"use strict";var NL=Ze();tv.exports=function(){var a=NL(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 sv=h((Zq,av)=>{"use strict";var FL=we(),qL=Ue(),UL=ri(),HL=rv(),iv=RegExp.prototype;av.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in iv)&&!qL(a,"flags")&&UL(iv,a)?FL(HL,a):e}});var ov=h((eU,nv)=>{"use strict";var zu=J(),jL=gr(),GL=Math.floor,Wu=zu("".charAt),QL=zu("".replace),Yu=zu("".slice),WL=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,YL=/\$([$&'`]|\d{1,2})/g;nv.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=YL;return i!==void 0&&(i=jL(i),u=WL),QL(s,u,function(l,d){var c;switch(Wu(d,0)){case"$":return"$";case"&":return a;case"`":return Yu(e,0,t);case"'":return Yu(e,n);case"<":c=i[Yu(d,1,-1)];break;default:var p=+d;if(p===0)return l;if(p>o){var m=GL(p/10);return m===0?l:m<=o?r[m-1]===void 0?Wu(d,1):r[m-1]+Wu(d,1):l}c=r[p-1]}return c===void 0?"":c})}});var cv=h(()=>{"use strict";var zL=K(),KL=we(),Xu=J(),uv=Tt(),XL=W(),JL=fr(),ZL=ev(),Hr=Bi(),e$=ai(),t$=sv(),r$=ov(),i$=ae(),a$=qe(),s$=i$("replace"),n$=TypeError,Ku=Xu("".indexOf),o$=Xu("".replace),lv=Xu("".slice),u$=Math.max;zL({target:"String",proto:!0},{replaceAll:function(e,t){var r=uv(this),i,s,n,o,u,l,d,c,p,m,f=0,b="";if(!JL(e)){if(i=ZL(e),i&&(s=Hr(uv(t$(e))),!~Ku(s,"g")))throw new n$("`.replaceAll` does not allow non-global regexes");if(n=e$(e,s$),n)return KL(n,e,r,t);if(a$&&i)return o$(Hr(r),e,t)}for(o=Hr(r),u=Hr(e),l=XL(t),l||(t=Hr(t)),d=u.length,c=u$(1,d),p=Ku(o,u);p!==-1;)m=l?Hr(t(u,p,o)):r$(u,o,p,[],void 0,t),b+=lv(o,f,p)+m,f=p+d,p=p+c>o.length?-1:Ku(o,u,p+c);return f<o.length&&(b+=lv(o,f)),b}})});var pv=h((iU,dv)=>{"use strict";Xg();Jg();cv();var l$=It();dv.exports=l$("String","replaceAll")});var mv=h((aU,hv)=>{"use strict";var c$=pv();hv.exports=c$});var bv=h((sU,fv)=>{"use strict";var d$=mv();fv.exports=d$});var vv=h((nU,gv)=>{"use strict";var p$=ui(),h$=Bi(),m$=Tt(),f$=RangeError;gv.exports=function(e){var t=h$(m$(this)),r="",i=p$(e);if(i<0||i===1/0)throw new f$("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var Ev=h((oU,Iv)=>{"use strict";var Tv=J(),b$=zn(),Sv=Bi(),g$=vv(),v$=Tt(),S$=Tv(g$),y$=Tv("".slice),T$=Math.ceil,yv=function(a){return function(e,t,r){var i=Sv(v$(e)),s=b$(t),n=i.length,o=r===void 0?" ":Sv(r),u,l;return s<=n||o===""?i:(u=s-n,l=S$(o,T$(u/o.length)),l.length>u&&(l=y$(l,0,u)),a?i+l:l+i)}};Iv.exports={start:yv(!1),end:yv(!0)}});var Pv=h((uU,xv)=>{"use strict";var I$=jt();xv.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(I$)});var wv=h(()=>{"use strict";var E$=K(),x$=Ev().start,P$=Pv();E$({target:"String",proto:!0,forced:P$},{padStart:function(e){return x$(this,e,arguments.length>1?arguments[1]:void 0)}})});var Av=h((dU,kv)=>{"use strict";wv();var w$=It();kv.exports=w$("String","padStart")});var Lv=h((pU,Rv)=>{"use strict";var k$=Av();Rv.exports=k$});var Mv=h((hU,$v)=>{"use strict";var A$=Lv();$v.exports=A$});var _l="2.0.124-dev.b149ab67.0";var me=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(me||{}),yt=(P=>(P.MPEG="MPEG",P.DASH="DASH",P.DASH_SEP="DASH_SEP",P.DASH_SEP_VK="DASH_SEP",P.DASH_WEBM="DASH_WEBM",P.DASH_WEBM_AV1="DASH_WEBM_AV1",P.DASH_STREAMS="DASH_STREAMS",P.DASH_WEBM_VK="DASH_WEBM",P.DASH_ONDEMAND="DASH_ONDEMAND",P.DASH_ONDEMAND_VK="DASH_ONDEMAND",P.DASH_LIVE="DASH_LIVE",P.DASH_LIVE_CMAF="DASH_LIVE_CMAF",P.DASH_LIVE_WEBM="DASH_LIVE_WEBM",P.HLS="HLS",P.HLS_ONDEMAND="HLS_ONDEMAND",P.HLS_JS="HLS",P.HLS_LIVE="HLS_LIVE",P.HLS_LIVE_CMAF="HLS_LIVE_CMAF",P.WEB_RTC_LIVE="WEB_RTC_LIVE",P))(yt||{});var Ua=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(Ua||{}),vn=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(vn||{});var Sn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Sn||{});var ly=D(He(),1);import{assertNever as Bd,assertNonNullable as qI,isNonNullable as Wa,ValueSubject as Xn,Subject as UI,Subscription as HI,merge as jI,observableFrom as GI,fromEvent as Md,map as Dd,tap as Cd,filterChanged as QI,isNullable as Jn,ErrorCategory as Vd}from"@vkontakte/videoplayer-shared";var $d=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e(),r.onerror=i=>t(i),document.body.appendChild(r)});var Ya=class{constructor(e){this.connection$=new Xn(void 0);this.castState$=new Xn("NOT_AVAILABLE");this.errorEvent$=new UI;this.realCastState$=new Xn("NOT_AVAILABLE");this.subscription=new HI;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 r=Wa(window.chrome?.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},i||$d("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Vd.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(){Wa(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Jn(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Jn(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),r=cast.framework.CastContext.getInstance();this.subscription.add(Md(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=r.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 Bd(i.sessionState)}})).add(jI(Md(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Cd(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),Dd(i=>i.castState)),GI([r.getCastState()])).pipe(QI(),Dd(WI),Cd(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{let s=i==="CONNECTED",n=Wa(this.connection$.getValue());if(s&&!n){let o=r.getCurrentSession();qI(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;(Jn(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?Wa(this.connection$.getValue())?"CONNECTED":"AVAILABLE":i)}))}initializeCastApi(){let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:r}),this.initListeners()}catch(i){this.errorEvent$.next({id:"ChromecastInitializer",category:Vd.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:i})}}},WI=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 Bd(a)}};var Rl=D(He(),1),HS=D(xr(),1),jS=D(wo(),1);var Ff=D(Is(),1);import{assertNever as $f}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 r=new URL(a);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(a);return!r.searchParams.get("offset_p")&&e===0?a:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:$f(t)}return a},Es=(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:$f(e)}};var T=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as tA,Subject as xs,merge as Mf}from"@vkontakte/videoplayer-shared";var $=class{constructor(e){this.transitionStarted$=new xs;this.transitionEnded$=new xs;this.transitionUpdated$=new xs;this.forceChanged$=new xs;this.stateChangeStarted$=Mf(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Mf(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,r=this.state;this.transition=void 0,this.prevState=r,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:r,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,r=this.state;r===e||tA(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as rA}from"@vkontakte/videoplayer-shared";var Df=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return rA(a)}};import{assertNever as Cr,assertNonNullable as Xt,debounce as Cf,ErrorCategory as Vf,fromEvent as Jt,isNonNullable as Bf,map as Of,merge as _f,observableFrom as iA,Subject as aA,Subscription as pu,timeout as sA,getHighestQuality as nA}from"@vkontakte/videoplayer-shared";var oA=5,uA=5,lA=500,Nf=7e3,Ii=class{constructor(e){this.subscription=new pu;this.loadMediaTimeoutSubscription=new pu;this.videoState=new $("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(i?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Cr(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:Cr(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:Cr(e)}break}default:Cr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Df(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 pu;this.subscription.add(e),this.subscription.add(_f(this.videoState.stateChangeStarted$.pipe(Of(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(Of(i=>`stateChangeEnded$ ${JSON.stringify(i)}`))).subscribe(i=>this.log({message:`[videoState] ${i}`})));let t=(i,s)=>this.subscription.add(i.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let i=new aA;e.add(i.pipe(Cf(lA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>oA)&&i.next(o),s=o})),e.add(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);let{remotePlayer:s}=this.params.connection,n=i.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<uA&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),T(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:Cr(n)}}),t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=_f(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,iA(["init"])).pipe(Cf(0));t(r,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"),T(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),T(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?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),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),T(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&T(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),r={volume:e.volume??t.volume,muted:e.muted??t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,r,i,s;switch(e){case"MPEG":{let l=t[e];Xt(l);let d=nA(Object.keys(l));Xt(d);let c=l[d];Xt(c),r=c,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];Xt(l),r=l.url,i="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];Xt(l),r=l.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];Xt(l),r=l.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];Xt(l),r=se(l.url),i="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:Vf.VIDEO_PIPELINE,message:l,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Cr(e)}let n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??r,i);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return Bf(o)&&(n.metadata.title=o),Bf(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((i,s)=>{this.loadMediaTimeoutSubscription.add(sA(Nf).subscribe(()=>s(`timeout(${Nf})`)))});(0,Ff.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},i=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${i}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Vf.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Mu=D(He(),1);import{clearVideoElement as Uf}from"@vkontakte/videoplayer-shared";import{clearVideoElement as cA}from"@vkontakte/videoplayer-shared";var qf=a=>{try{a.pause(),a.playbackRate=0,cA(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as dA,Subscription as pA}from"@vkontakte/videoplayer-shared";var hu=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)}},mu=window.WeakMap?new WeakMap:new hu,fu=window.WeakMap?new WeakMap:new Map,hA=(a,e=20)=>{let t=0;return dA(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},fe=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?Uf(t):(t=document.createElement("video"),a.appendChild(t)),mu.set(t,r);let i=new pA;return i.add(hA(t,e)),fu.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.setAttribute("x-yandex-pip","false"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},be=a=>{fu.get(a)?.unsubscribe(),fu.delete(a);let t=mu.get(a);mu.delete(a),t?Uf(a):qf(a)};var gu=D(Vr(),1);import{assertNonNullable as Ei,isNonNullable as tt,isNullable as TA,fromEvent as Br,merge as zf,observableFrom as Kf,filterChanged as Xf,map as xi,Subject as Jf,Subscription as IA,ValueSubject as EA,ErrorCategory as xA}from"@vkontakte/videoplayer-shared";import{isNonNullable as bu,isNullable as SA,Subscription as yA}from"@vkontakte/videoplayer-shared";var Ps=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=SA(i),l=new yA;return i&&l.add(i.subscribe(d=>{let c=a.getState();r(d,c)&&a.setState(d)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(d=>{t(d.to),u&&a.setState(d.to)},s)),l},et=(a,e,t)=>Ps(e,()=>a.loop,r=>{bu(r)&&(a.loop=r)},{onError:t}),ge=(a,e,t,r)=>Ps(e,()=>({muted:a.muted,volume:a.volume}),i=>{bu(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||i?.muted===s?.muted&&i?.volume===s?.volume,changed$:t,onError:r}),$e=(a,e,t,r)=>Ps(e,()=>a.playbackRate,i=>{bu(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),xt=Ps;var PA=a=>["__",a.language,a.label].join("|"),wA=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},vu=class a{constructor(e){this.available$=new Jf;this.current$=new EA(void 0);this.error$=new Jf;this.subscription=new IA;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:xA.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(xt(t.internalTextTracks,()=>(0,gu.default)(this.internalTracks),s=>{tt(s)&&this.setInternal(s)},{equal:(s,n)=>tt(s)&&tt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(xi(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(xt(t.externalTextTracks,()=>(0,gu.default)(this.externalTracks),s=>{tt(s)&&this.setExternal(s)},{equal:(s,n)=>tt(s)&&tt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(xi(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(xt(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:i})),this.subscription.add(xt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Ei(this.video);let{textTracks:e}=this.video;this.subscription.add(Br(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(zf(Br(e,"addtrack"),Br(e,"removetrack"),Kf(["init"])).pipe(xi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Xf((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(zf(Br(e,"change"),Kf(["init"])).pipe(xi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),xi(r=>r&&this.htmlTextTrackToITextTrack(r).id),Xf()).subscribe(this.current$));let t=r=>this.applyCueSettings(r.target?.activeCues??null);this.subscription.add(Br(e,"addtrack").subscribe(r=>{r.track?.addEventListener("cuechange",t);let i=s=>{let n=s.target?.cues??null;n&&n.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",i))};r.track?.addEventListener("cuechange",i)})),this.subscription.add(Br(e,"removetrack").subscribe(r=>{r.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;tt(t.align)&&(i.align=t.align),tt(t.position)&&(i.position=t.position),tt(t.size)&&(i.size=t.size),tt(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){Ei(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:r}=e,i=e.id?e.id:PA(e),s=this.externalTracks.has(i),n=(s?this.externalTracks.get(i)?.isAuto:this.internalTracks.get(i)?.isAuto)??i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:this.externalTracks.get(i)?.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:this.internalTracks.get(i)?.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(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){Ei(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(TA(e)||!wA(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){Ei(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){Ei(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.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)}},Me=vu;var dt=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 Zf=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Su=a=>{let e=Zf(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},eb=a=>{let e=Zf(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as De,map as Pt,merge as rb,filterChanged as AA,isNonNullable as ib,Subject as RA,filter as ab,mapTo as sb,combine as LA,once as $A,ErrorCategory as MA,ValueSubject as nb,clientChecker as DA}from"@vkontakte/videoplayer-shared";var kA=3,tb=(a,e,t=kA)=>{let r=0,i=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(r=n,i=o,!t)return{from:r,to:i};for(let u=s-1;u>=0;u--)a.end(u)+t>=r&&(r=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=i&&(i=a.end(u))}}return{from:r,to:i}};var ve=a=>{let e=P=>De(a,P).pipe(sb(void 0)),r=rb(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(P=>De(a,P))).pipe(Pt(P=>P.type==="ended"?a.readyState<2:a.readyState<3),AA()),i=rb(De(a,"progress"),De(a,"timeupdate")).pipe(Pt(()=>tb(a.buffered,a.currentTime))),s=DA.isSafari?LA({play:e("play").pipe($A()),playing:e("playing")}).pipe(sb(void 0)):e("playing"),n=De(a,"volumechange").pipe(Pt(()=>({muted:a.muted,volume:a.volume}))),o=De(a,"ratechange").pipe(Pt(()=>a.playbackRate)),u=De(a,"error").pipe(ab(()=>!!(a.error||a.played.length)),Pt(()=>{let P=a.error;return{id:P?`MediaError#${P.code}`:"HtmlVideoError",category:MA.VIDEO_PIPELINE,message:P?P.message:"Error event from HTML video element",thrown:a.error??void 0}})),l=De(a,"timeupdate").pipe(Pt(()=>a.currentTime)),d=new RA,c=.3,p;l.subscribe(P=>{a.loop&&ib(p)&&ib(P)&&p>=a.duration-c&&P<=c&&d.next(p),p=P});let m=e("pause").pipe(ab(()=>!a.error&&p!==a.duration)),f=De(a,"enterpictureinpicture"),b=De(a,"leavepictureinpicture"),g=new nb(eb(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new nb(Su(a));return De(a,"fullscreenchange").pipe(Pt(()=>Su(a))).subscribe(v),{playing$:s,pause$:m,canplay$:e("canplay"),ended$:e("ended"),looped$:d,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:De(a,"durationchange").pipe(Pt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v,enterPip$:f,leavePip$:b}};import{VideoQuality as wt}from"@vkontakte/videoplayer-shared";var kt=a=>{switch(a){case"mobile":return wt.Q_144P;case"lowest":return wt.Q_240P;case"low":return wt.Q_360P;case"sd":case"medium":return wt.Q_480P;case"hd":case"high":return wt.Q_720P;case"fullhd":case"full":return wt.Q_1080P;case"quadhd":case"quad":return wt.Q_1440P;case"ultrahd":case"ultra":return wt.Q_2160P}};var At=D(Or(),1),Sb=D(He(),1),ws=D(xr(),1);import{isNonNullable as Z,isNullable as Tu,now as yb,isHigher as Iu,isHigherOrEqual as Eu,isInvariantQuality as bb,isLower as gb,isLowerOrEqual as xu,videoSizeToQuality as UA,assertNotEmptyArray as Tb,assertNonNullable as HA}from"@vkontakte/videoplayer-shared";var yu=!1,pt={},hb=a=>{yu=a},mb=()=>{pt={}},fb=a=>{a(pt)},Pi=(a,e)=>{yu&&(pt.meta=pt.meta??{},pt.meta[a]=e)},ce=class{constructor(e){this.name=e}next(e){if(!yu)return;pt.series=pt.series??{};let t=pt.series[this.name]??[];t.push([Date.now(),e]),pt.series[this.name]=t}};var jA=new ce("best_bitrate"),Ib=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var Pu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),wi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=yb()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Eb='Assertion "ABR Tracks is empty array" failed',ks=(a,e,t,r)=>{let i=[...e].sort(Pu(1)),s=[...t].sort(Pu(1)),n=s.filter(u=>Z(u.bitrate)&&Z(a.bitrate)?a.bitrate/u.bitrate>r:!0),o=(0,At.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1)))??(0,At.default)(s,-1);return o&&(0,Sb.default)(n,o)?o:n.length?(0,At.default)(n,-1):(0,At.default)(s,0)},vb=a=>"quality"in a,xb=(a,e,t,r)=>{let i=Z(r?.last?.bitrate)&&Z(t?.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&yb()-r.history[t.id]<=i&&(!r.last||t.id!==r.last.id);if(t?.id&&r&&!s&&r.recordSelection(t),s&&r?.last){let n=r.last;r?.recordSwitch(n);let o=vb(n)?"video":"audio",u=vb(n)?n.quality:n.bitrate;return e({message:`
|
|
6
|
+
var fy=Object.create;var Ol=Object.defineProperty;var by=Object.getOwnPropertyDescriptor;var gy=Object.getOwnPropertyNames;var Sy=Object.getPrototypeOf,vy=Object.prototype.hasOwnProperty;var m=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var yy=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of gy(e))!vy.call(i,a)&&a!==t&&Ol(i,a,{get:()=>e[a],enumerable:!(r=by(e,a))||r.enumerable});return i};var V=(i,e,t)=>(t=i!=null?fy(Sy(i)):{},yy(e||!i||!i.__esModule?Ol(t,"default",{value:i,enumerable:!0}):t,i));var z=m((yn,Nl)=>{"use strict";var ei=function(i){return i&&i.Math===Math&&i};Nl.exports=ei(typeof globalThis=="object"&&globalThis)||ei(typeof window=="object"&&window)||ei(typeof self=="object"&&self)||ei(typeof global=="object"&&global)||ei(typeof yn=="object"&&yn)||function(){return this}()||Function("return this")()});var ae=m((YD,Fl)=>{"use strict";Fl.exports=function(i){try{return!!i()}catch{return!0}}});var ti=m((zD,ql)=>{"use strict";var Ty=ae();ql.exports=!Ty(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var Tn=m((KD,Gl)=>{"use strict";var Iy=ti(),jl=Function.prototype,Ul=jl.apply,Hl=jl.call;Gl.exports=typeof Reflect=="object"&&Reflect.apply||(Iy?Hl.bind(Ul):function(){return Hl.apply(Ul,arguments)})});var ee=m((XD,Yl)=>{"use strict";var Ql=ti(),Wl=Function.prototype,In=Wl.call,Ey=Ql&&Wl.bind.bind(In,In);Yl.exports=Ql?Ey:function(i){return function(){return In.apply(i,arguments)}}});var jt=m((JD,Kl)=>{"use strict";var zl=ee(),xy=zl({}.toString),Py=zl("".slice);Kl.exports=function(i){return Py(xy(i),8,-1)}});var En=m((ZD,Xl)=>{"use strict";var ky=jt(),wy=ee();Xl.exports=function(i){if(ky(i)==="Function")return wy(i)}});var Y=m((e0,Jl)=>{"use strict";var xn=typeof document=="object"&&document.all;Jl.exports=typeof xn>"u"&&xn!==void 0?function(i){return typeof i=="function"||i===xn}:function(i){return typeof i=="function"}});var ke=m((t0,Zl)=>{"use strict";var Ay=ae();Zl.exports=!Ay(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var we=m((r0,ec)=>{"use strict";var Ry=ti(),ja=Function.prototype.call;ec.exports=Ry?ja.bind(ja):function(){return ja.apply(ja,arguments)}});var Pn=m(ic=>{"use strict";var tc={}.propertyIsEnumerable,rc=Object.getOwnPropertyDescriptor,$y=rc&&!tc.call({1:2},1);ic.f=$y?function(e){var t=rc(this,e);return!!t&&t.enumerable}:tc});var ri=m((a0,ac)=>{"use strict";ac.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var nc=m((s0,sc)=>{"use strict";var Ly=ee(),My=ae(),Dy=jt(),kn=Object,Cy=Ly("".split);sc.exports=My(function(){return!kn("z").propertyIsEnumerable(0)})?function(i){return Dy(i)==="String"?Cy(i,""):kn(i)}:kn});var fr=m((n0,oc)=>{"use strict";oc.exports=function(i){return i==null}});var It=m((o0,uc)=>{"use strict";var Vy=fr(),By=TypeError;uc.exports=function(i){if(Vy(i))throw new By("Can't call method on "+i);return i}});var Gt=m((u0,lc)=>{"use strict";var Oy=nc(),_y=It();lc.exports=function(i){return Oy(_y(i))}});var Ae=m((l0,cc)=>{"use strict";var Ny=Y();cc.exports=function(i){return typeof i=="object"?i!==null:Ny(i)}});var br=m((c0,dc)=>{"use strict";dc.exports={}});var lt=m((d0,hc)=>{"use strict";var wn=br(),An=z(),Fy=Y(),pc=function(i){return Fy(i)?i:void 0};hc.exports=function(i,e){return arguments.length<2?pc(wn[i])||pc(An[i]):wn[i]&&wn[i][e]||An[i]&&An[i][e]}});var ii=m((p0,mc)=>{"use strict";var qy=ee();mc.exports=qy({}.isPrototypeOf)});var Qt=m((h0,gc)=>{"use strict";var Uy=z(),fc=Uy.navigator,bc=fc&&fc.userAgent;gc.exports=bc?String(bc):""});var $n=m((m0,Ec)=>{"use strict";var Ic=z(),Rn=Qt(),Sc=Ic.process,vc=Ic.Deno,yc=Sc&&Sc.versions||vc&&vc.version,Tc=yc&&yc.v8,qe,Ga;Tc&&(qe=Tc.split("."),Ga=qe[0]>0&&qe[0]<4?1:+(qe[0]+qe[1]));!Ga&&Rn&&(qe=Rn.match(/Edge\/(\d+)/),(!qe||qe[1]>=74)&&(qe=Rn.match(/Chrome\/(\d+)/),qe&&(Ga=+qe[1])));Ec.exports=Ga});var Ln=m((f0,Pc)=>{"use strict";var xc=$n(),Hy=ae(),jy=z(),Gy=jy.String;Pc.exports=!!Object.getOwnPropertySymbols&&!Hy(function(){var i=Symbol("symbol detection");return!Gy(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&xc&&xc<41})});var Mn=m((b0,kc)=>{"use strict";var Qy=Ln();kc.exports=Qy&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Dn=m((g0,wc)=>{"use strict";var Wy=lt(),Yy=Y(),zy=ii(),Ky=Mn(),Xy=Object;wc.exports=Ky?function(i){return typeof i=="symbol"}:function(i){var e=Wy("Symbol");return Yy(e)&&zy(e.prototype,Xy(i))}});var ai=m((S0,Ac)=>{"use strict";var Jy=String;Ac.exports=function(i){try{return Jy(i)}catch{return"Object"}}});var Ze=m((v0,Rc)=>{"use strict";var Zy=Y(),eT=ai(),tT=TypeError;Rc.exports=function(i){if(Zy(i))return i;throw new tT(eT(i)+" is not a function")}});var si=m((y0,$c)=>{"use strict";var rT=Ze(),iT=fr();$c.exports=function(i,e){var t=i[e];return iT(t)?void 0:rT(t)}});var Mc=m((T0,Lc)=>{"use strict";var Cn=we(),Vn=Y(),Bn=Ae(),aT=TypeError;Lc.exports=function(i,e){var t,r;if(e==="string"&&Vn(t=i.toString)&&!Bn(r=Cn(t,i))||Vn(t=i.valueOf)&&!Bn(r=Cn(t,i))||e!=="string"&&Vn(t=i.toString)&&!Bn(r=Cn(t,i)))return r;throw new aT("Can't convert object to primitive value")}});var Ue=m((I0,Dc)=>{"use strict";Dc.exports=!0});var Bc=m((E0,Vc)=>{"use strict";var Cc=z(),sT=Object.defineProperty;Vc.exports=function(i,e){try{sT(Cc,i,{value:e,configurable:!0,writable:!0})}catch{Cc[i]=e}return e}});var ni=m((x0,Nc)=>{"use strict";var nT=Ue(),oT=z(),uT=Bc(),Oc="__core-js_shared__",_c=Nc.exports=oT[Oc]||uT(Oc,{});(_c.versions||(_c.versions=[])).push({version:"3.38.0",mode:nT?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var On=m((P0,qc)=>{"use strict";var Fc=ni();qc.exports=function(i,e){return Fc[i]||(Fc[i]=e||{})}});var gr=m((k0,Uc)=>{"use strict";var lT=It(),cT=Object;Uc.exports=function(i){return cT(lT(i))}});var He=m((w0,Hc)=>{"use strict";var dT=ee(),pT=gr(),hT=dT({}.hasOwnProperty);Hc.exports=Object.hasOwn||function(e,t){return hT(pT(e),t)}});var _n=m((A0,jc)=>{"use strict";var mT=ee(),fT=0,bT=Math.random(),gT=mT(1 .toString);jc.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+gT(++fT+bT,36)}});var se=m((R0,Qc)=>{"use strict";var ST=z(),vT=On(),Gc=He(),yT=_n(),TT=Ln(),IT=Mn(),Sr=ST.Symbol,Nn=vT("wks"),ET=IT?Sr.for||Sr:Sr&&Sr.withoutSetter||yT;Qc.exports=function(i){return Gc(Nn,i)||(Nn[i]=TT&&Gc(Sr,i)?Sr[i]:ET("Symbol."+i)),Nn[i]}});var Kc=m(($0,zc)=>{"use strict";var xT=we(),Wc=Ae(),Yc=Dn(),PT=si(),kT=Mc(),wT=se(),AT=TypeError,RT=wT("toPrimitive");zc.exports=function(i,e){if(!Wc(i)||Yc(i))return i;var t=PT(i,RT),r;if(t){if(e===void 0&&(e="default"),r=xT(t,i,e),!Wc(r)||Yc(r))return r;throw new AT("Can't convert object to primitive value")}return e===void 0&&(e="number"),kT(i,e)}});var Fn=m((L0,Xc)=>{"use strict";var $T=Kc(),LT=Dn();Xc.exports=function(i){var e=$T(i,"string");return LT(e)?e:e+""}});var Qa=m((M0,Zc)=>{"use strict";var MT=z(),Jc=Ae(),qn=MT.document,DT=Jc(qn)&&Jc(qn.createElement);Zc.exports=function(i){return DT?qn.createElement(i):{}}});var Un=m((D0,ed)=>{"use strict";var CT=ke(),VT=ae(),BT=Qa();ed.exports=!CT&&!VT(function(){return Object.defineProperty(BT("div"),"a",{get:function(){return 7}}).a!==7})});var id=m(rd=>{"use strict";var OT=ke(),_T=we(),NT=Pn(),FT=ri(),qT=Gt(),UT=Fn(),HT=He(),jT=Un(),td=Object.getOwnPropertyDescriptor;rd.f=OT?td:function(e,t){if(e=qT(e),t=UT(t),jT)try{return td(e,t)}catch{}if(HT(e,t))return FT(!_T(NT.f,e,t),e[t])}});var Hn=m((V0,ad)=>{"use strict";var GT=ae(),QT=Y(),WT=/#|\.prototype\./,oi=function(i,e){var t=zT[YT(i)];return t===XT?!0:t===KT?!1:QT(e)?GT(e):!!e},YT=oi.normalize=function(i){return String(i).replace(WT,".").toLowerCase()},zT=oi.data={},KT=oi.NATIVE="N",XT=oi.POLYFILL="P";ad.exports=oi});var vr=m((B0,nd)=>{"use strict";var sd=En(),JT=Ze(),ZT=ti(),eI=sd(sd.bind);nd.exports=function(i,e){return JT(i),e===void 0?i:ZT?eI(i,e):function(){return i.apply(e,arguments)}}});var jn=m((O0,od)=>{"use strict";var tI=ke(),rI=ae();od.exports=tI&&rI(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var et=m((_0,ud)=>{"use strict";var iI=Ae(),aI=String,sI=TypeError;ud.exports=function(i){if(iI(i))return i;throw new sI(aI(i)+" is not an object")}});var Wt=m(cd=>{"use strict";var nI=ke(),oI=Un(),uI=jn(),Wa=et(),ld=Fn(),lI=TypeError,Gn=Object.defineProperty,cI=Object.getOwnPropertyDescriptor,Qn="enumerable",Wn="configurable",Yn="writable";cd.f=nI?uI?function(e,t,r){if(Wa(e),t=ld(t),Wa(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Yn in r&&!r[Yn]){var a=cI(e,t);a&&a[Yn]&&(e[t]=r.value,r={configurable:Wn in r?r[Wn]:a[Wn],enumerable:Qn in r?r[Qn]:a[Qn],writable:!1})}return Gn(e,t,r)}:Gn:function(e,t,r){if(Wa(e),t=ld(t),Wa(r),oI)try{return Gn(e,t,r)}catch{}if("get"in r||"set"in r)throw new lI("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var yr=m((F0,dd)=>{"use strict";var dI=ke(),pI=Wt(),hI=ri();dd.exports=dI?function(i,e,t){return pI.f(i,e,hI(1,t))}:function(i,e,t){return i[e]=t,i}});var X=m((q0,hd)=>{"use strict";var ui=z(),mI=Tn(),fI=En(),bI=Y(),gI=id().f,SI=Hn(),Tr=br(),vI=vr(),Ir=yr(),pd=He();ni();var yI=function(i){var e=function(t,r,a){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,r)}return new i(t,r,a)}return mI(i,this,arguments)};return e.prototype=i.prototype,e};hd.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?ui:a?ui[t]:ui[t]&&ui[t].prototype,o=r?Tr:Tr[t]||Ir(Tr,t,{})[t],u=o.prototype,l,c,d,p,h,f,b,g,S;for(p in e)l=SI(r?p:t+(a?".":"#")+p,i.forced),c=!l&&n&&pd(n,p),f=o[p],c&&(i.dontCallGetSet?(S=gI(n,p),b=S&&S.value):b=n[p]),h=c&&b?b:e[p],!(!l&&!s&&typeof f==typeof h)&&(i.bind&&c?g=vI(h,ui):i.wrap&&c?g=yI(h):s&&bI(h)?g=fI(h):g=h,(i.sham||h&&h.sham||f&&f.sham)&&Ir(g,"sham",!0),Ir(o,p,g),s&&(d=t+"Prototype",pd(Tr,d)||Ir(Tr,d,{}),Ir(Tr[d],p,h),i.real&&u&&(l||!u[p])&&Ir(u,p,h)))}});var fd=m((U0,md)=>{"use strict";var TI=Math.ceil,II=Math.floor;md.exports=Math.trunc||function(e){var t=+e;return(t>0?II:TI)(t)}});var li=m((H0,bd)=>{"use strict";var EI=fd();bd.exports=function(i){var e=+i;return e!==e||e===0?0:EI(e)}});var Sd=m((j0,gd)=>{"use strict";var xI=li(),PI=Math.max,kI=Math.min;gd.exports=function(i,e){var t=xI(i);return t<0?PI(t+e,0):kI(t,e)}});var zn=m((G0,vd)=>{"use strict";var wI=li(),AI=Math.min;vd.exports=function(i){var e=wI(i);return e>0?AI(e,9007199254740991):0}});var Er=m((Q0,yd)=>{"use strict";var RI=zn();yd.exports=function(i){return RI(i.length)}});var Kn=m((W0,Id)=>{"use strict";var $I=Gt(),LI=Sd(),MI=Er(),Td=function(i){return function(e,t,r){var a=$I(e),s=MI(a);if(s===0)return!i&&-1;var n=LI(r,s),o;if(i&&t!==t){for(;s>n;)if(o=a[n++],o!==o)return!0}else for(;s>n;n++)if((i||n in a)&&a[n]===t)return i||n||0;return!i&&-1}};Id.exports={includes:Td(!0),indexOf:Td(!1)}});var ci=m((Y0,Ed)=>{"use strict";Ed.exports=function(){}});var xd=m(()=>{"use strict";var DI=X(),CI=Kn().includes,VI=ae(),BI=ci(),OI=VI(function(){return!Array(1).includes()});DI({target:"Array",proto:!0,forced:OI},{includes:function(e){return CI(this,e,arguments.length>1?arguments[1]:void 0)}});BI("includes")});var Et=m((X0,Pd)=>{"use strict";var _I=lt();Pd.exports=_I});var wd=m((J0,kd)=>{"use strict";xd();var NI=Et();kd.exports=NI("Array","includes")});var Rd=m((Z0,Ad)=>{"use strict";var FI=wd();Ad.exports=FI});var je=m((eC,$d)=>{"use strict";var qI=Rd();$d.exports=qI});var Ka=m((pC,_d)=>{"use strict";var zI=On(),KI=_n(),Od=zI("keys");_d.exports=function(i){return Od[i]||(Od[i]=KI(i))}});var Fd=m((hC,Nd)=>{"use strict";var XI=ae();Nd.exports=!XI(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var Xa=m((mC,Ud)=>{"use strict";var JI=He(),ZI=Y(),eE=gr(),tE=Ka(),rE=Fd(),qd=tE("IE_PROTO"),Zn=Object,iE=Zn.prototype;Ud.exports=rE?Zn.getPrototypeOf:function(i){var e=eE(i);if(JI(e,qd))return e[qd];var t=e.constructor;return ZI(t)&&e instanceof t?t.prototype:e instanceof Zn?iE:null}});var Ja=m((fC,Hd)=>{"use strict";Hd.exports={}});var Qd=m((bC,Gd)=>{"use strict";var aE=ee(),eo=He(),sE=Gt(),nE=Kn().indexOf,oE=Ja(),jd=aE([].push);Gd.exports=function(i,e){var t=sE(i),r=0,a=[],s;for(s in t)!eo(oE,s)&&eo(t,s)&&jd(a,s);for(;e.length>r;)eo(t,s=e[r++])&&(~nE(a,s)||jd(a,s));return a}});var to=m((gC,Wd)=>{"use strict";Wd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var ro=m((SC,Yd)=>{"use strict";var uE=Qd(),lE=to();Yd.exports=Object.keys||function(e){return uE(e,lE)}});var io=m((vC,Zd)=>{"use strict";var Kd=ke(),cE=ae(),Xd=ee(),dE=Xa(),pE=ro(),hE=Gt(),mE=Pn().f,Jd=Xd(mE),fE=Xd([].push),bE=Kd&&cE(function(){var i=Object.create(null);return i[2]=2,!Jd(i,2)}),zd=function(i){return function(e){for(var t=hE(e),r=pE(t),a=bE&&dE(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!Kd||(a?u in t:Jd(t,u)))&&fE(o,i?[u,t[u]]:t[u]);return o}};Zd.exports={entries:zd(!0),values:zd(!1)}});var ep=m(()=>{"use strict";var gE=X(),SE=io().entries;gE({target:"Object",stat:!0},{entries:function(e){return SE(e)}})});var rp=m((IC,tp)=>{"use strict";ep();var vE=br();tp.exports=vE.Object.entries});var ap=m((EC,ip)=>{"use strict";var yE=rp();ip.exports=yE});var xr=m((xC,sp)=>{"use strict";var TE=ap();sp.exports=TE});var Yt=m((PC,np)=>{"use strict";np.exports={}});var lp=m((kC,up)=>{"use strict";var IE=z(),EE=Y(),op=IE.WeakMap;up.exports=EE(op)&&/native code/.test(String(op))});var oo=m((wC,pp)=>{"use strict";var xE=lp(),dp=z(),PE=Ae(),kE=yr(),ao=He(),so=ni(),wE=Ka(),AE=Ja(),cp="Object already initialized",no=dp.TypeError,RE=dp.WeakMap,Za,di,es,$E=function(i){return es(i)?di(i):Za(i,{})},LE=function(i){return function(e){var t;if(!PE(e)||(t=di(e)).type!==i)throw new no("Incompatible receiver, "+i+" required");return t}};xE||so.state?(Ge=so.state||(so.state=new RE),Ge.get=Ge.get,Ge.has=Ge.has,Ge.set=Ge.set,Za=function(i,e){if(Ge.has(i))throw new no(cp);return e.facade=i,Ge.set(i,e),e},di=function(i){return Ge.get(i)||{}},es=function(i){return Ge.has(i)}):(zt=wE("state"),AE[zt]=!0,Za=function(i,e){if(ao(i,zt))throw new no(cp);return e.facade=i,kE(i,zt,e),e},di=function(i){return ao(i,zt)?i[zt]:{}},es=function(i){return ao(i,zt)});var Ge,zt;pp.exports={set:Za,get:di,has:es,enforce:$E,getterFor:LE}});var co=m((AC,mp)=>{"use strict";var uo=ke(),ME=He(),hp=Function.prototype,DE=uo&&Object.getOwnPropertyDescriptor,lo=ME(hp,"name"),CE=lo&&function(){}.name==="something",VE=lo&&(!uo||uo&&DE(hp,"name").configurable);mp.exports={EXISTS:lo,PROPER:CE,CONFIGURABLE:VE}});var bp=m(fp=>{"use strict";var BE=ke(),OE=jn(),_E=Wt(),NE=et(),FE=Gt(),qE=ro();fp.f=BE&&!OE?Object.defineProperties:function(e,t){NE(e);for(var r=FE(t),a=qE(t),s=a.length,n=0,o;s>n;)_E.f(e,o=a[n++],r[o]);return e}});var po=m(($C,gp)=>{"use strict";var UE=lt();gp.exports=UE("document","documentElement")});var bo=m((LC,xp)=>{"use strict";var HE=et(),jE=bp(),Sp=to(),GE=Ja(),QE=po(),WE=Qa(),YE=Ka(),vp=">",yp="<",mo="prototype",fo="script",Ip=YE("IE_PROTO"),ho=function(){},Ep=function(i){return yp+fo+vp+i+yp+"/"+fo+vp},Tp=function(i){i.write(Ep("")),i.close();var e=i.parentWindow.Object;return i=null,e},zE=function(){var i=WE("iframe"),e="java"+fo+":",t;return i.style.display="none",QE.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Ep("document.F=Object")),t.close(),t.F},ts,rs=function(){try{ts=new ActiveXObject("htmlfile")}catch{}rs=typeof document<"u"?document.domain&&ts?Tp(ts):zE():Tp(ts);for(var i=Sp.length;i--;)delete rs[mo][Sp[i]];return rs()};GE[Ip]=!0;xp.exports=Object.create||function(e,t){var r;return e!==null?(ho[mo]=HE(e),r=new ho,ho[mo]=null,r[Ip]=e):r=rs(),t===void 0?r:jE.f(r,t)}});var Pr=m((MC,Pp)=>{"use strict";var KE=yr();Pp.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:KE(i,e,t),i}});var yo=m((DC,Ap)=>{"use strict";var XE=ae(),JE=Y(),ZE=Ae(),ex=bo(),kp=Xa(),tx=Pr(),rx=se(),ix=Ue(),vo=rx("iterator"),wp=!1,ct,go,So;[].keys&&(So=[].keys(),"next"in So?(go=kp(kp(So)),go!==Object.prototype&&(ct=go)):wp=!0);var ax=!ZE(ct)||XE(function(){var i={};return ct[vo].call(i)!==i});ax?ct={}:ix&&(ct=ex(ct));JE(ct[vo])||tx(ct,vo,function(){return this});Ap.exports={IteratorPrototype:ct,BUGGY_SAFARI_ITERATORS:wp}});var is=m((CC,$p)=>{"use strict";var sx=se(),nx=sx("toStringTag"),Rp={};Rp[nx]="z";$p.exports=String(Rp)==="[object z]"});var pi=m((VC,Lp)=>{"use strict";var ox=is(),ux=Y(),as=jt(),lx=se(),cx=lx("toStringTag"),dx=Object,px=as(function(){return arguments}())==="Arguments",hx=function(i,e){try{return i[e]}catch{}};Lp.exports=ox?as:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=hx(e=dx(i),cx))=="string"?t:px?as(e):(r=as(e))==="Object"&&ux(e.callee)?"Arguments":r}});var Dp=m((BC,Mp)=>{"use strict";var mx=is(),fx=pi();Mp.exports=mx?{}.toString:function(){return"[object "+fx(this)+"]"}});var hi=m((OC,Vp)=>{"use strict";var bx=is(),gx=Wt().f,Sx=yr(),vx=He(),yx=Dp(),Tx=se(),Cp=Tx("toStringTag");Vp.exports=function(i,e,t,r){var a=t?i:i&&i.prototype;a&&(vx(a,Cp)||gx(a,Cp,{configurable:!0,value:e}),r&&!bx&&Sx(a,"toString",yx))}});var Op=m((_C,Bp)=>{"use strict";var Ix=yo().IteratorPrototype,Ex=bo(),xx=ri(),Px=hi(),kx=Yt(),wx=function(){return this};Bp.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=Ex(Ix,{next:xx(+!r,t)}),Px(i,a,!1,!0),kx[a]=wx,i}});var Np=m((NC,_p)=>{"use strict";var Ax=ee(),Rx=Ze();_p.exports=function(i,e,t){try{return Ax(Rx(Object.getOwnPropertyDescriptor(i,e)[t]))}catch{}}});var qp=m((FC,Fp)=>{"use strict";var $x=Ae();Fp.exports=function(i){return $x(i)||i===null}});var Hp=m((qC,Up)=>{"use strict";var Lx=qp(),Mx=String,Dx=TypeError;Up.exports=function(i){if(Lx(i))return i;throw new Dx("Can't set "+Mx(i)+" as a prototype")}});var To=m((UC,jp)=>{"use strict";var Cx=Np(),Vx=Ae(),Bx=It(),Ox=Hp();jp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=Cx(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch{}return function(a,s){return Bx(a),Ox(s),Vx(a)&&(i?t(a,s):a.__proto__=s),a}}():void 0)});var th=m((HC,eh)=>{"use strict";var _x=X(),Nx=we(),ss=Ue(),Jp=co(),Fx=Y(),qx=Op(),Gp=Xa(),Qp=To(),Ux=hi(),Hx=yr(),Io=Pr(),jx=se(),Wp=Yt(),Zp=yo(),Gx=Jp.PROPER,Qx=Jp.CONFIGURABLE,Yp=Zp.IteratorPrototype,ns=Zp.BUGGY_SAFARI_ITERATORS,mi=jx("iterator"),zp="keys",fi="values",Kp="entries",Xp=function(){return this};eh.exports=function(i,e,t,r,a,s,n){qx(t,e,r);var o=function(S){if(S===a&&p)return p;if(!ns&&S&&S in c)return c[S];switch(S){case zp:return function(){return new t(this,S)};case fi:return function(){return new t(this,S)};case Kp:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=i.prototype,d=c[mi]||c["@@iterator"]||a&&c[a],p=!ns&&d||o(a),h=e==="Array"&&c.entries||d,f,b,g;if(h&&(f=Gp(h.call(new i)),f!==Object.prototype&&f.next&&(!ss&&Gp(f)!==Yp&&(Qp?Qp(f,Yp):Fx(f[mi])||Io(f,mi,Xp)),Ux(f,u,!0,!0),ss&&(Wp[u]=Xp))),Gx&&a===fi&&d&&d.name!==fi&&(!ss&&Qx?Hx(c,"name",fi):(l=!0,p=function(){return Nx(d,this)})),a)if(b={values:o(fi),keys:s?p:o(zp),entries:o(Kp)},n)for(g in b)(ns||l||!(g in c))&&Io(c,g,b[g]);else _x({target:e,proto:!0,forced:ns||l},b);return(!ss||n)&&c[mi]!==p&&Io(c,mi,p,{name:a}),Wp[e]=p,b}});var ih=m((jC,rh)=>{"use strict";rh.exports=function(i,e){return{value:i,done:e}}});var xo=m((GC,uh)=>{"use strict";var Wx=Gt(),Eo=ci(),ah=Yt(),nh=oo(),Yx=Wt().f,zx=th(),os=ih(),Kx=Ue(),Xx=ke(),oh="Array Iterator",Jx=nh.set,Zx=nh.getterFor(oh);uh.exports=zx(Array,"Array",function(i,e){Jx(this,{type:oh,target:Wx(i),index:0,kind:e})},function(){var i=Zx(this),e=i.target,t=i.index++;if(!e||t>=e.length)return i.target=void 0,os(void 0,!0);switch(i.kind){case"keys":return os(t,!1);case"values":return os(e[t],!1)}return os([t,e[t]],!1)},"values");var sh=ah.Arguments=ah.Array;Eo("keys");Eo("values");Eo("entries");if(!Kx&&Xx&&sh.name!=="values")try{Yx(sh,"name",{value:"values"})}catch{}});var ch=m((QC,lh)=>{"use strict";var eP=se(),tP=Yt(),rP=eP("iterator"),iP=Array.prototype;lh.exports=function(i){return i!==void 0&&(tP.Array===i||iP[rP]===i)}});var Po=m((WC,ph)=>{"use strict";var aP=pi(),dh=si(),sP=fr(),nP=Yt(),oP=se(),uP=oP("iterator");ph.exports=function(i){if(!sP(i))return dh(i,uP)||dh(i,"@@iterator")||nP[aP(i)]}});var mh=m((YC,hh)=>{"use strict";var lP=we(),cP=Ze(),dP=et(),pP=ai(),hP=Po(),mP=TypeError;hh.exports=function(i,e){var t=arguments.length<2?hP(i):e;if(cP(t))return dP(lP(t,i));throw new mP(pP(i)+" is not iterable")}});var gh=m((zC,bh)=>{"use strict";var fP=we(),fh=et(),bP=si();bh.exports=function(i,e,t){var r,a;fh(i);try{if(r=bP(i,"return"),!r){if(e==="throw")throw t;return t}r=fP(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return fh(r),t}});var ls=m((KC,Th)=>{"use strict";var gP=vr(),SP=we(),vP=et(),yP=ai(),TP=ch(),IP=Er(),Sh=ii(),EP=mh(),xP=Po(),vh=gh(),PP=TypeError,us=function(i,e){this.stopped=i,this.result=e},yh=us.prototype;Th.exports=function(i,e,t){var r=t&&t.that,a=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=gP(e,r),l,c,d,p,h,f,b,g=function(P){return l&&vh(l,"normal",P),new us(!0,P)},S=function(P){return a?(vP(P),o?u(P[0],P[1],g):u(P[0],P[1])):o?u(P,g):u(P)};if(s)l=i.iterator;else if(n)l=i;else{if(c=xP(i),!c)throw new PP(yP(i)+" is not iterable");if(TP(c)){for(d=0,p=IP(i);p>d;d++)if(h=S(i[d]),h&&Sh(yh,h))return h;return new us(!1)}l=EP(i,c)}for(f=s?i.next:l.next;!(b=SP(f,l)).done;){try{h=S(b.value)}catch(P){vh(l,"throw",P)}if(typeof h=="object"&&h&&Sh(yh,h))return h}return new us(!1)}});var Eh=m((XC,Ih)=>{"use strict";var kP=ke(),wP=Wt(),AP=ri();Ih.exports=function(i,e,t){kP?wP.f(i,e,AP(0,t)):i[e]=t}});var xh=m(()=>{"use strict";var RP=X(),$P=ls(),LP=Eh();RP({target:"Object",stat:!0},{fromEntries:function(e){var t={};return $P(e,function(r,a){LP(t,r,a)},{AS_ENTRIES:!0}),t}})});var kh=m((eV,Ph)=>{"use strict";xo();xh();var MP=br();Ph.exports=MP.Object.fromEntries});var Ah=m((tV,wh)=>{"use strict";wh.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 $h=m(()=>{"use strict";xo();var DP=Ah(),CP=z(),VP=hi(),Rh=Yt();for(cs in DP)VP(CP[cs],cs),Rh[cs]=Rh.Array;var cs});var Mh=m((aV,Lh)=>{"use strict";var BP=kh();$h();Lh.exports=BP});var ko=m((sV,Dh)=>{"use strict";var OP=Mh();Dh.exports=OP});var Ch=m(()=>{"use strict"});var wo=m((uV,Vh)=>{"use strict";var bi=z(),_P=Qt(),NP=jt(),ds=function(i){return _P.slice(0,i.length)===i};Vh.exports=function(){return ds("Bun/")?"BUN":ds("Cloudflare-Workers")?"CLOUDFLARE":ds("Deno/")?"DENO":ds("Node.js/")?"NODE":bi.Bun&&typeof Bun.version=="string"?"BUN":bi.Deno&&typeof Deno.version=="object"?"DENO":NP(bi.process)==="process"?"NODE":bi.window&&bi.document?"BROWSER":"REST"}()});var ps=m((lV,Bh)=>{"use strict";var FP=wo();Bh.exports=FP==="NODE"});var _h=m((cV,Oh)=>{"use strict";var qP=Wt();Oh.exports=function(i,e,t){return qP.f(i,e,t)}});var qh=m((dV,Fh)=>{"use strict";var UP=lt(),HP=_h(),jP=se(),GP=ke(),Nh=jP("species");Fh.exports=function(i){var e=UP(i);GP&&e&&!e[Nh]&&HP(e,Nh,{configurable:!0,get:function(){return this}})}});var Hh=m((pV,Uh)=>{"use strict";var QP=ii(),WP=TypeError;Uh.exports=function(i,e){if(QP(e,i))return i;throw new WP("Incorrect invocation")}});var Ro=m((hV,jh)=>{"use strict";var YP=ee(),zP=Y(),Ao=ni(),KP=YP(Function.toString);zP(Ao.inspectSource)||(Ao.inspectSource=function(i){return KP(i)});jh.exports=Ao.inspectSource});var Lo=m((mV,zh)=>{"use strict";var XP=ee(),JP=ae(),Gh=Y(),ZP=pi(),ek=lt(),tk=Ro(),Qh=function(){},Wh=ek("Reflect","construct"),$o=/^\s*(?:class|function)\b/,rk=XP($o.exec),ik=!$o.test(Qh),gi=function(e){if(!Gh(e))return!1;try{return Wh(Qh,[],e),!0}catch{return!1}},Yh=function(e){if(!Gh(e))return!1;switch(ZP(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return ik||!!rk($o,tk(e))}catch{return!0}};Yh.sham=!0;zh.exports=!Wh||JP(function(){var i;return gi(gi.call)||!gi(Object)||!gi(function(){i=!0})||i})?Yh:gi});var Xh=m((fV,Kh)=>{"use strict";var ak=Lo(),sk=ai(),nk=TypeError;Kh.exports=function(i){if(ak(i))return i;throw new nk(sk(i)+" is not a constructor")}});var Mo=m((bV,Zh)=>{"use strict";var Jh=et(),ok=Xh(),uk=fr(),lk=se(),ck=lk("species");Zh.exports=function(i,e){var t=Jh(i).constructor,r;return t===void 0||uk(r=Jh(t)[ck])?e:ok(r)}});var tm=m((gV,em)=>{"use strict";var dk=ee();em.exports=dk([].slice)});var im=m((SV,rm)=>{"use strict";var pk=TypeError;rm.exports=function(i,e){if(i<e)throw new pk("Not enough arguments");return i}});var Do=m((vV,am)=>{"use strict";var hk=Qt();am.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(hk)});var Uo=m((yV,hm)=>{"use strict";var Re=z(),mk=Tn(),fk=vr(),sm=Y(),bk=He(),pm=ae(),nm=po(),gk=tm(),om=Qa(),Sk=im(),vk=Do(),yk=ps(),No=Re.setImmediate,Fo=Re.clearImmediate,Tk=Re.process,Co=Re.Dispatch,Ik=Re.Function,um=Re.MessageChannel,Ek=Re.String,Vo=0,Si={},lm="onreadystatechange",vi,Kt,Bo,Oo;pm(function(){vi=Re.location});var qo=function(i){if(bk(Si,i)){var e=Si[i];delete Si[i],e()}},_o=function(i){return function(){qo(i)}},cm=function(i){qo(i.data)},dm=function(i){Re.postMessage(Ek(i),vi.protocol+"//"+vi.host)};(!No||!Fo)&&(No=function(e){Sk(arguments.length,1);var t=sm(e)?e:Ik(e),r=gk(arguments,1);return Si[++Vo]=function(){mk(t,void 0,r)},Kt(Vo),Vo},Fo=function(e){delete Si[e]},yk?Kt=function(i){Tk.nextTick(_o(i))}:Co&&Co.now?Kt=function(i){Co.now(_o(i))}:um&&!vk?(Bo=new um,Oo=Bo.port2,Bo.port1.onmessage=cm,Kt=fk(Oo.postMessage,Oo)):Re.addEventListener&&sm(Re.postMessage)&&!Re.importScripts&&vi&&vi.protocol!=="file:"&&!pm(dm)?(Kt=dm,Re.addEventListener("message",cm,!1)):lm in om("script")?Kt=function(i){nm.appendChild(om("script"))[lm]=function(){nm.removeChild(this),qo(i)}}:Kt=function(i){setTimeout(_o(i),0)});hm.exports={set:No,clear:Fo}});var bm=m((TV,fm)=>{"use strict";var mm=z(),xk=ke(),Pk=Object.getOwnPropertyDescriptor;fm.exports=function(i){if(!xk)return mm[i];var e=Pk(mm,i);return e&&e.value}});var Ho=m((IV,Sm)=>{"use strict";var gm=function(){this.head=null,this.tail=null};gm.prototype={add:function(i){var e={item:i,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var i=this.head;if(i){var e=this.head=i.next;return e===null&&(this.tail=null),i.item}}};Sm.exports=gm});var ym=m((EV,vm)=>{"use strict";var kk=Qt();vm.exports=/ipad|iphone|ipod/i.test(kk)&&typeof Pebble<"u"});var Im=m((xV,Tm)=>{"use strict";var wk=Qt();Tm.exports=/web0s(?!.*chrome)/i.test(wk)});var Rm=m((PV,Am)=>{"use strict";var wr=z(),Ak=bm(),Em=vr(),jo=Uo().set,Rk=Ho(),$k=Do(),Lk=ym(),Mk=Im(),Go=ps(),xm=wr.MutationObserver||wr.WebKitMutationObserver,Pm=wr.document,km=wr.process,hs=wr.Promise,Yo=Ak("queueMicrotask"),kr,Qo,Wo,ms,wm;Yo||(yi=new Rk,Ti=function(){var i,e;for(Go&&(i=km.domain)&&i.exit();e=yi.get();)try{e()}catch(t){throw yi.head&&kr(),t}i&&i.enter()},!$k&&!Go&&!Mk&&xm&&Pm?(Qo=!0,Wo=Pm.createTextNode(""),new xm(Ti).observe(Wo,{characterData:!0}),kr=function(){Wo.data=Qo=!Qo}):!Lk&&hs&&hs.resolve?(ms=hs.resolve(void 0),ms.constructor=hs,wm=Em(ms.then,ms),kr=function(){wm(Ti)}):Go?kr=function(){km.nextTick(Ti)}:(jo=Em(jo,wr),kr=function(){jo(Ti)}),Yo=function(i){yi.head||kr(),yi.add(i)});var yi,Ti;Am.exports=Yo});var Lm=m((kV,$m)=>{"use strict";$m.exports=function(i,e){try{arguments.length===1?console.error(i):console.error(i,e)}catch{}}});var fs=m((wV,Mm)=>{"use strict";Mm.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var Xt=m((AV,Dm)=>{"use strict";var Dk=z();Dm.exports=Dk.Promise});var Ar=m((RV,Om)=>{"use strict";var Ck=z(),Ii=Xt(),Vk=Y(),Bk=Hn(),Ok=Ro(),_k=se(),Cm=wo(),Nk=Ue(),zo=$n(),Vm=Ii&&Ii.prototype,Fk=_k("species"),Ko=!1,Bm=Vk(Ck.PromiseRejectionEvent),qk=Bk("Promise",function(){var i=Ok(Ii),e=i!==String(Ii);if(!e&&zo===66||Nk&&!(Vm.catch&&Vm.finally))return!0;if(!zo||zo<51||!/native code/.test(i)){var t=new Ii(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[Fk]=r,Ko=t.then(function(){})instanceof r,!Ko)return!0}return!e&&(Cm==="BROWSER"||Cm==="DENO")&&!Bm});Om.exports={CONSTRUCTOR:qk,REJECTION_EVENT:Bm,SUBCLASSING:Ko}});var Rr=m(($V,Nm)=>{"use strict";var _m=Ze(),Uk=TypeError,Hk=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw new Uk("Bad Promise constructor");e=r,t=a}),this.resolve=_m(e),this.reject=_m(t)};Nm.exports.f=function(i){return new Hk(i)}});var sf=m(()=>{"use strict";var jk=X(),Gk=Ue(),vs=ps(),xt=z(),Dr=we(),Fm=Pr(),qm=To(),Qk=hi(),Wk=qh(),Yk=Ze(),Ss=Y(),zk=Ae(),Kk=Hh(),Xk=Mo(),Qm=Uo().set,tu=Rm(),Jk=Lm(),Zk=fs(),ew=Ho(),Wm=oo(),ys=Xt(),ru=Ar(),Ym=Rr(),Ts="Promise",zm=ru.CONSTRUCTOR,tw=ru.REJECTION_EVENT,rw=ru.SUBCLASSING,Xo=Wm.getterFor(Ts),iw=Wm.set,$r=ys&&ys.prototype,Jt=ys,bs=$r,Km=xt.TypeError,Jo=xt.document,iu=xt.process,Zo=Ym.f,aw=Zo,sw=!!(Jo&&Jo.createEvent&&xt.dispatchEvent),Xm="unhandledrejection",nw="rejectionhandled",Um=0,Jm=1,ow=2,au=1,Zm=2,gs,Hm,uw,jm,ef=function(i){var e;return zk(i)&&Ss(e=i.then)?e:!1},tf=function(i,e){var t=e.value,r=e.state===Jm,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,u,l,c;try{a?(r||(e.rejection===Zm&&cw(e),e.rejection=au),a===!0?u=t:(o&&o.enter(),u=a(t),o&&(o.exit(),c=!0)),u===i.promise?n(new Km("Promise-chain cycle")):(l=ef(u))?Dr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},rf=function(i,e){i.notified||(i.notified=!0,tu(function(){for(var t=i.reactions,r;r=t.get();)tf(r,i);i.notified=!1,e&&!i.rejection&&lw(i)}))},af=function(i,e,t){var r,a;sw?(r=Jo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),xt.dispatchEvent(r)):r={promise:e,reason:t},!tw&&(a=xt["on"+i])?a(r):i===Xm&&Jk("Unhandled promise rejection",t)},lw=function(i){Dr(Qm,xt,function(){var e=i.facade,t=i.value,r=Gm(i),a;if(r&&(a=Zk(function(){vs?iu.emit("unhandledRejection",t,e):af(Xm,e,t)}),i.rejection=vs||Gm(i)?Zm:au,a.error))throw a.value})},Gm=function(i){return i.rejection!==au&&!i.parent},cw=function(i){Dr(Qm,xt,function(){var e=i.facade;vs?iu.emit("rejectionHandled",e):af(nw,e,i.value)})},Lr=function(i,e,t){return function(r){i(e,r,t)}},Mr=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=ow,rf(i,!0))},eu=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw new Km("Promise can't be resolved itself");var r=ef(e);r?tu(function(){var a={done:!1};try{Dr(r,e,Lr(eu,a,i),Lr(Mr,a,i))}catch(s){Mr(a,s,i)}}):(i.value=e,i.state=Jm,rf(i,!1))}catch(a){Mr({done:!1},a,i)}}};if(zm&&(Jt=function(e){Kk(this,bs),Yk(e),Dr(gs,this);var t=Xo(this);try{e(Lr(eu,t),Lr(Mr,t))}catch(r){Mr(t,r)}},bs=Jt.prototype,gs=function(e){iw(this,{type:Ts,done:!1,notified:!1,parent:!1,reactions:new ew,rejection:!1,state:Um,value:void 0})},gs.prototype=Fm(bs,"then",function(e,t){var r=Xo(this),a=Zo(Xk(this,Jt));return r.parent=!0,a.ok=Ss(e)?e:!0,a.fail=Ss(t)&&t,a.domain=vs?iu.domain:void 0,r.state===Um?r.reactions.add(a):tu(function(){tf(a,r)}),a.promise}),Hm=function(){var i=new gs,e=Xo(i);this.promise=i,this.resolve=Lr(eu,e),this.reject=Lr(Mr,e)},Ym.f=Zo=function(i){return i===Jt||i===uw?new Hm(i):aw(i)},!Gk&&Ss(ys)&&$r!==Object.prototype)){jm=$r.then,rw||Fm($r,"then",function(e,t){var r=this;return new Jt(function(a,s){Dr(jm,r,a,s)}).then(e,t)},{unsafe:!0});try{delete $r.constructor}catch{}qm&&qm($r,bs)}jk({global:!0,constructor:!0,wrap:!0,forced:zm},{Promise:Jt});Qk(Jt,Ts,!1,!0);Wk(Ts)});var cf=m((DV,lf)=>{"use strict";var dw=se(),of=dw("iterator"),uf=!1;try{nf=0,su={next:function(){return{done:!!nf++}},return:function(){uf=!0}},su[of]=function(){return this},Array.from(su,function(){throw 2})}catch{}var nf,su;lf.exports=function(i,e){try{if(!e&&!uf)return!1}catch{return!1}var t=!1;try{var r={};r[of]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch{}return t}});var nu=m((CV,df)=>{"use strict";var pw=Xt(),hw=cf(),mw=Ar().CONSTRUCTOR;df.exports=mw||!hw(function(i){pw.all(i).then(void 0,function(){})})});var pf=m(()=>{"use strict";var fw=X(),bw=we(),gw=Ze(),Sw=Rr(),vw=fs(),yw=ls(),Tw=nu();fw({target:"Promise",stat:!0,forced:Tw},{all:function(e){var t=this,r=Sw.f(t),a=r.resolve,s=r.reject,n=vw(function(){var o=gw(t.resolve),u=[],l=0,c=1;yw(e,function(d){var p=l++,h=!1;c++,bw(o,t,d).then(function(f){h||(h=!0,u[p]=f,--c||a(u))},s)}),--c||a(u)});return n.error&&s(n.value),r.promise}})});var mf=m(()=>{"use strict";var Iw=X(),Ew=Ue(),xw=Ar().CONSTRUCTOR,uu=Xt(),Pw=lt(),kw=Y(),ww=Pr(),hf=uu&&uu.prototype;Iw({target:"Promise",proto:!0,forced:xw,real:!0},{catch:function(i){return this.then(void 0,i)}});!Ew&&kw(uu)&&(ou=Pw("Promise").prototype.catch,hf.catch!==ou&&ww(hf,"catch",ou,{unsafe:!0}));var ou});var ff=m(()=>{"use strict";var Aw=X(),Rw=we(),$w=Ze(),Lw=Rr(),Mw=fs(),Dw=ls(),Cw=nu();Aw({target:"Promise",stat:!0,forced:Cw},{race:function(e){var t=this,r=Lw.f(t),a=r.reject,s=Mw(function(){var n=$w(t.resolve);Dw(e,function(o){Rw(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var bf=m(()=>{"use strict";var Vw=X(),Bw=Rr(),Ow=Ar().CONSTRUCTOR;Vw({target:"Promise",stat:!0,forced:Ow},{reject:function(e){var t=Bw.f(this),r=t.reject;return r(e),t.promise}})});var lu=m((HV,gf)=>{"use strict";var _w=et(),Nw=Ae(),Fw=Rr();gf.exports=function(i,e){if(_w(i),Nw(e)&&e.constructor===i)return e;var t=Fw.f(i),r=t.resolve;return r(e),t.promise}});var yf=m(()=>{"use strict";var qw=X(),Uw=lt(),Sf=Ue(),Hw=Xt(),vf=Ar().CONSTRUCTOR,jw=lu(),Gw=Uw("Promise"),Qw=Sf&&!vf;qw({target:"Promise",stat:!0,forced:Sf||vf},{resolve:function(e){return jw(Qw&&this===Gw?Hw:this,e)}})});var Tf=m(()=>{"use strict";sf();pf();mf();ff();bf();yf()});var Pf=m(()=>{"use strict";var Ww=X(),Yw=Ue(),Is=Xt(),zw=ae(),Ef=lt(),xf=Y(),Kw=Mo(),If=lu(),Xw=Pr(),du=Is&&Is.prototype,Jw=!!Is&&zw(function(){du.finally.call({then:function(){}},function(){})});Ww({target:"Promise",proto:!0,real:!0,forced:Jw},{finally:function(i){var e=Kw(this,Ef("Promise")),t=xf(i);return this.then(t?function(r){return If(e,i()).then(function(){return r})}:i,t?function(r){return If(e,i()).then(function(){throw r})}:i)}});!Yw&&xf(Is)&&(cu=Ef("Promise").prototype.finally,du.finally!==cu&&Xw(du,"finally",cu,{unsafe:!0}));var cu});var wf=m((KV,kf)=>{"use strict";Ch();Tf();Pf();var Zw=Et();kf.exports=Zw("Promise","finally")});var Rf=m((XV,Af)=>{"use strict";var eA=wf();Af.exports=eA});var Es=m((JV,$f)=>{"use strict";var tA=Rf();$f.exports=tA});var Hf=m(()=>{"use strict";var fA=X(),bA=io().values;fA({target:"Object",stat:!0},{values:function(e){return bA(e)}})});var Gf=m((BB,jf)=>{"use strict";Hf();var gA=br();jf.exports=gA.Object.values});var Wf=m((OB,Qf)=>{"use strict";var SA=Gf();Qf.exports=SA});var Vr=m((_B,Yf)=>{"use strict";var vA=Wf();Yf.exports=vA});var ob=m(()=>{"use strict";var VA=X(),BA=gr(),OA=Er(),_A=li(),NA=ci();VA({target:"Array",proto:!0},{at:function(e){var t=BA(this),r=OA(t),a=_A(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});NA("at")});var lb=m((pO,ub)=>{"use strict";ob();var FA=Et();ub.exports=FA("Array","at")});var db=m((hO,cb)=>{"use strict";var qA=lb();cb.exports=qA});var Or=m((mO,pb)=>{"use strict";var UA=db();pb.exports=UA});var Cu=m((F_,Ub)=>{"use strict";var ER=jt();Ub.exports=Array.isArray||function(e){return ER(e)==="Array"}});var jb=m((q_,Hb)=>{"use strict";var xR=TypeError,PR=9007199254740991;Hb.exports=function(i){if(i>PR)throw xR("Maximum allowed index exceeded");return i}});var Wb=m((U_,Qb)=>{"use strict";var kR=Cu(),wR=Er(),AR=jb(),RR=vr(),Gb=function(i,e,t,r,a,s,n,o){for(var u=a,l=0,c=n?RR(n,o):!1,d,p;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&kR(d)?(p=wR(d),u=Gb(i,e,d,p,u,s-1)-1):(AR(u+1),i[u]=d),u++),l++;return u};Qb.exports=Gb});var Xb=m((H_,Kb)=>{"use strict";var Yb=Cu(),$R=Lo(),LR=Ae(),MR=se(),DR=MR("species"),zb=Array;Kb.exports=function(i){var e;return Yb(i)&&(e=i.constructor,$R(e)&&(e===zb||Yb(e.prototype))?e=void 0:LR(e)&&(e=e[DR],e===null&&(e=void 0))),e===void 0?zb:e}});var Zb=m((j_,Jb)=>{"use strict";var CR=Xb();Jb.exports=function(i,e){return new(CR(i))(e===0?0:e)}});var eg=m(()=>{"use strict";var VR=X(),BR=Wb(),OR=Ze(),_R=gr(),NR=Er(),FR=Zb();VR({target:"Array",proto:!0},{flatMap:function(e){var t=_R(this),r=NR(t),a;return OR(e),a=FR(t,0),a.length=BR(a,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),a}})});var tg=m(()=>{"use strict";var qR=ci();qR("flatMap")});var ig=m((z_,rg)=>{"use strict";eg();tg();var UR=Et();rg.exports=UR("Array","flatMap")});var sg=m((K_,ag)=>{"use strict";var HR=ig();ag.exports=HR});var Vu=m((X_,ng)=>{"use strict";var jR=sg();ng.exports=jR});var Oi=m((oN,bg)=>{"use strict";var JR=pi(),ZR=String;bg.exports=function(i){if(JR(i)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return ZR(i)}});var Ou=m((uN,gg)=>{"use strict";gg.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 yg=m((lN,vg)=>{"use strict";var e$=ee(),t$=It(),r$=Oi(),Nu=Ou(),Sg=e$("".replace),i$=RegExp("^["+Nu+"]+"),a$=RegExp("(^|[^"+Nu+"])["+Nu+"]+$"),_u=function(i){return function(e){var t=r$(t$(e));return i&1&&(t=Sg(t,i$,"")),i&2&&(t=Sg(t,a$,"$1")),t}};vg.exports={start:_u(1),end:_u(2),trim:_u(3)}});var xg=m((cN,Eg)=>{"use strict";var s$=co().PROPER,n$=ae(),Tg=Ou(),Ig="\u200B\x85\u180E";Eg.exports=function(i){return n$(function(){return!!Tg[i]()||Ig[i]()!==Ig||s$&&Tg[i].name!==i})}});var Fu=m((dN,Pg)=>{"use strict";var o$=yg().start,u$=xg();Pg.exports=u$("trimStart")?function(){return o$(this)}:"".trimStart});var wg=m(()=>{"use strict";var l$=X(),kg=Fu();l$({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==kg},{trimLeft:kg})});var Rg=m(()=>{"use strict";wg();var c$=X(),Ag=Fu();c$({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Ag},{trimStart:Ag})});var Lg=m((bN,$g)=>{"use strict";Rg();var d$=Et();$g.exports=d$("String","trimLeft")});var Dg=m((gN,Mg)=>{"use strict";var p$=Lg();Mg.exports=p$});var Vg=m((SN,Cg)=>{"use strict";var h$=Dg();Cg.exports=h$});var Xg=m(()=>{"use strict"});var Jg=m(()=>{"use strict"});var eS=m((Xq,Zg)=>{"use strict";var B$=Ae(),O$=jt(),_$=se(),N$=_$("match");Zg.exports=function(i){var e;return B$(i)&&((e=i[N$])!==void 0?!!e:O$(i)==="RegExp")}});var rS=m((Jq,tS)=>{"use strict";var F$=et();tS.exports=function(){var i=F$(this),e="";return i.hasIndices&&(e+="d"),i.global&&(e+="g"),i.ignoreCase&&(e+="i"),i.multiline&&(e+="m"),i.dotAll&&(e+="s"),i.unicode&&(e+="u"),i.unicodeSets&&(e+="v"),i.sticky&&(e+="y"),e}});var sS=m((Zq,aS)=>{"use strict";var q$=we(),U$=He(),H$=ii(),j$=rS(),iS=RegExp.prototype;aS.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in iS)&&!U$(i,"flags")&&H$(iS,i)?q$(j$,i):e}});var oS=m((eU,nS)=>{"use strict";var zu=ee(),G$=gr(),Q$=Math.floor,Wu=zu("".charAt),W$=zu("".replace),Yu=zu("".slice),Y$=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,z$=/\$([$&'`]|\d{1,2})/g;nS.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,u=z$;return a!==void 0&&(a=G$(a),u=Y$),W$(s,u,function(l,c){var d;switch(Wu(c,0)){case"$":return"$";case"&":return i;case"`":return Yu(e,0,t);case"'":return Yu(e,n);case"<":d=a[Yu(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=Q$(p/10);return h===0?l:h<=o?r[h-1]===void 0?Wu(c,1):r[h-1]+Wu(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var cS=m(()=>{"use strict";var K$=X(),X$=we(),Xu=ee(),uS=It(),J$=Y(),Z$=fr(),eL=eS(),Hr=Oi(),tL=si(),rL=sS(),iL=oS(),aL=se(),sL=Ue(),nL=aL("replace"),oL=TypeError,Ku=Xu("".indexOf),uL=Xu("".replace),lS=Xu("".slice),lL=Math.max;K$({target:"String",proto:!0},{replaceAll:function(e,t){var r=uS(this),a,s,n,o,u,l,c,d,p,h,f=0,b="";if(!Z$(e)){if(a=eL(e),a&&(s=Hr(uS(rL(e))),!~Ku(s,"g")))throw new oL("`.replaceAll` does not allow non-global regexes");if(n=tL(e,nL),n)return X$(n,e,r,t);if(sL&&a)return uL(Hr(r),e,t)}for(o=Hr(r),u=Hr(e),l=J$(t),l||(t=Hr(t)),c=u.length,d=lL(1,c),p=Ku(o,u);p!==-1;)h=l?Hr(t(u,p,o)):iL(u,o,p,[],void 0,t),b+=lS(o,f,p)+h,f=p+c,p=p+d>o.length?-1:Ku(o,u,p+d);return f<o.length&&(b+=lS(o,f)),b}})});var pS=m((iU,dS)=>{"use strict";Xg();Jg();cS();var cL=Et();dS.exports=cL("String","replaceAll")});var mS=m((aU,hS)=>{"use strict";var dL=pS();hS.exports=dL});var bS=m((sU,fS)=>{"use strict";var pL=mS();fS.exports=pL});var SS=m((nU,gS)=>{"use strict";var hL=li(),mL=Oi(),fL=It(),bL=RangeError;gS.exports=function(e){var t=mL(fL(this)),r="",a=hL(e);if(a<0||a===1/0)throw new bL("Wrong number of repetitions");for(;a>0;(a>>>=1)&&(t+=t))a&1&&(r+=t);return r}});var ES=m((oU,IS)=>{"use strict";var TS=ee(),gL=zn(),vS=Oi(),SL=SS(),vL=It(),yL=TS(SL),TL=TS("".slice),IL=Math.ceil,yS=function(i){return function(e,t,r){var a=vS(vL(e)),s=gL(t),n=a.length,o=r===void 0?" ":vS(r),u,l;return s<=n||o===""?a:(u=s-n,l=yL(o,IL(u/o.length)),l.length>u&&(l=TL(l,0,u)),i?a+l:l+a)}};IS.exports={start:yS(!1),end:yS(!0)}});var PS=m((uU,xS)=>{"use strict";var EL=Qt();xS.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(EL)});var kS=m(()=>{"use strict";var xL=X(),PL=ES().start,kL=PS();xL({target:"String",proto:!0,forced:kL},{padStart:function(e){return PL(this,e,arguments.length>1?arguments[1]:void 0)}})});var AS=m((dU,wS)=>{"use strict";kS();var wL=Et();wS.exports=wL("String","padStart")});var $S=m((pU,RS)=>{"use strict";var AL=AS();RS.exports=AL});var MS=m((hU,LS)=>{"use strict";var RL=$S();LS.exports=RL});var _l="2.0.124-dev.c7e94945.0";var be=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(be||{}),Tt=(v=>(v.MPEG="MPEG",v.DASH="DASH",v.DASH_SEP="DASH_SEP",v.DASH_SEP_VK="DASH_SEP",v.DASH_WEBM="DASH_WEBM",v.DASH_WEBM_AV1="DASH_WEBM_AV1",v.DASH_STREAMS="DASH_STREAMS",v.DASH_WEBM_VK="DASH_WEBM",v.DASH_ONDEMAND="DASH_ONDEMAND",v.DASH_ONDEMAND_VK="DASH_ONDEMAND",v.DASH_LIVE="DASH_LIVE",v.DASH_LIVE_CMAF="DASH_LIVE_CMAF",v.DASH_LIVE_WEBM="DASH_LIVE_WEBM",v.HLS="HLS",v.HLS_ONDEMAND="HLS_ONDEMAND",v.HLS_JS="HLS",v.HLS_LIVE="HLS_LIVE",v.HLS_LIVE_CMAF="HLS_LIVE_CMAF",v.WEB_RTC_LIVE="WEB_RTC_LIVE",v))(Tt||{});var Ha=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(Ha||{}),Sn=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Sn||{});var vn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(vn||{});var cy=V(je(),1);import{assertNever as Bd,assertNonNullable as UI,isNonNullable as Ya,ValueSubject as Xn,Subject as HI,Subscription as jI,merge as GI,observableFrom as QI,fromEvent as Md,map as Dd,tap as Cd,filterChanged as WI,isNullable as Jn,ErrorCategory as Vd}from"@vkontakte/videoplayer-shared";var Ld=i=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",i),r.onload=()=>e(),r.onerror=a=>t(a),document.body.appendChild(r)});var za=class{constructor(e){this.connection$=new Xn(void 0);this.castState$=new Xn("NOT_AVAILABLE");this.errorEvent$=new HI;this.realCastState$=new Xn("NOT_AVAILABLE");this.subscription=new jI;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 r=Ya(window.chrome?.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},a||Ld("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Vd.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(){Ya(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Jn(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Jn(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),r=cast.framework.CastContext.getInstance();this.subscription.add(Md(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{switch(a.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=r.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 Bd(a.sessionState)}})).add(GI(Md(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Cd(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),Dd(a=>a.castState)),QI([r.getCastState()])).pipe(WI(),Dd(YI),Cd(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=Ya(this.connection$.getValue());if(s&&!n){let o=r.getCurrentSession();UI(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;(Jn(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a==="CONNECTED"?Ya(this.connection$.getValue())?"CONNECTED":"AVAILABLE":a)}))}initializeCastApi(){let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:Vd.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},YI=i=>{switch(i){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 Bd(i)}};var Rl=V(je(),1),jv=V(xr(),1),Gv=V(ko(),1);var Ff=V(Es(),1);import{assertNever as Lf}from"@vkontakte/videoplayer-shared";var ne=(i,e=0,t=0)=>{switch(t){case 0:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return i;let r=new URL(i);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(i);return!r.searchParams.get("offset_p")&&e===0?i:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:Lf(t)}return i},xs=(i,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(i);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(i);return Number(t.searchParams.get("offset_p")??0)}default:Lf(e)}};var I=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};import{isNonNullable as rA,Subject as Ps,merge as Mf}from"@vkontakte/videoplayer-shared";var M=class{constructor(e){this.transitionStarted$=new Ps;this.transitionEnded$=new Ps;this.transitionUpdated$=new Ps;this.forceChanged$=new Ps;this.stateChangeStarted$=Mf(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Mf(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,r=this.state;this.transition=void 0,this.prevState=r,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:r,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,r=this.state;r===e||rA(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as iA}from"@vkontakte/videoplayer-shared";var Df=i=>{switch(i){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return iA(i)}};import{assertNever as Cr,assertNonNullable as Zt,debounce as Cf,ErrorCategory as Vf,fromEvent as er,isNonNullable as Bf,map as Of,merge as _f,observableFrom as aA,Subject as sA,Subscription as pu,timeout as nA,getHighestQuality as oA}from"@vkontakte/videoplayer-shared";var uA=5,lA=5,cA=500,Nf=7e3,Ei=class{constructor(e){this.subscription=new pu;this.loadMediaTimeoutSubscription=new pu;this.videoState=new M("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(a?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Cr(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:Cr(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:Cr(e)}break}default:Cr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Df(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 pu;this.subscription.add(e),this.subscription.add(_f(this.videoState.stateChangeStarted$.pipe(Of(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(Of(a=>`stateChangeEnded$ ${JSON.stringify(a)}`))).subscribe(a=>this.log({message:`[videoState] ${a}`})));let t=(a,s)=>this.subscription.add(a.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let a=new sA;e.add(a.pipe(Cf(cA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(er(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>uA)&&a.next(o),s=o})),e.add(er(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(er(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(er(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(er(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{this.logRemoteEvent(a);let{remotePlayer:s}=this.params.connection,n=a.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<lA&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),I(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:Cr(n)}}),t(er(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(er(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=_f(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,aA(["init"])).pipe(Cf(0));t(r,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"),I(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),I(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?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),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),I(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&I(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),r={volume:e.volume??t.volume,muted:e.muted??t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,r,a,s;switch(e){case"MPEG":{let l=t[e];Zt(l);let c=oA(Object.keys(l));Zt(c);let d=l[c];Zt(d),r=d,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];Zt(l),r=l.url,a="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];Zt(l),r=l.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];Zt(l),r=l.url,a="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];Zt(l),r=ne(l.url),a="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:Vf.VIDEO_PIPELINE,message:l,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Cr(e)}let n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??r,a);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return Bf(o)&&(n.metadata.title=o),Bf(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((a,s)=>{this.loadMediaTimeoutSubscription.add(nA(Nf).subscribe(()=>s(`timeout(${Nf})`)))});(0,Ff.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},a=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${a}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Vf.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Mu=V(je(),1);import{clearVideoElement as Uf}from"@vkontakte/videoplayer-shared";import{clearVideoElement as dA}from"@vkontakte/videoplayer-shared";var qf=i=>{try{i.pause(),i.playbackRate=0,dA(i),i.remove()}catch(e){console.error(e)}};import{fromEvent as pA,Subscription as hA}from"@vkontakte/videoplayer-shared";var hu=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)}},mu=window.WeakMap?new WeakMap:new hu,fu=window.WeakMap?new WeakMap:new Map,mA=(i,e=20)=>{let t=0;return pA(i,"ratechange").subscribe(r=>{t++,t>=e&&(i.currentTime=i.currentTime,t=0)})},ge=(i,{audioVideoSyncRate:e})=>{let t=i.querySelector("video"),r=!!t;t?Uf(t):(t=document.createElement("video"),i.appendChild(t)),mu.set(t,r);let a=new hA;return a.add(mA(t,e)),fu.set(t,a),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.setAttribute("x-yandex-pip","false"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},Se=i=>{fu.get(i)?.unsubscribe(),fu.delete(i);let t=mu.get(i);mu.delete(i),t?Uf(i):qf(i)};var gu=V(Vr(),1);import{assertNonNullable as xi,isNonNullable as rt,isNullable as IA,fromEvent as Br,merge as zf,observableFrom as Kf,filterChanged as Xf,map as Pi,Subject as Jf,Subscription as EA,ValueSubject as xA,ErrorCategory as PA}from"@vkontakte/videoplayer-shared";import{isNonNullable as bu,isNullable as yA,Subscription as TA}from"@vkontakte/videoplayer-shared";var ks=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),u=yA(a),l=new TA;return a&&l.add(a.subscribe(c=>{let d=i.getState();r(c,d)&&i.setState(c)},s)),r(o,n)||(t(n),u&&i.setState(n)),l.add(i.stateChangeStarted$.subscribe(c=>{t(c.to),u&&i.setState(c.to)},s)),l},tt=(i,e,t)=>ks(e,()=>i.loop,r=>{bu(r)&&(i.loop=r)},{onError:t}),ve=(i,e,t,r)=>ks(e,()=>({muted:i.muted,volume:i.volume}),a=>{bu(a)&&(i.muted=a.muted,i.volume=a.volume)},{equal:(a,s)=>a===s||a?.muted===s?.muted&&a?.volume===s?.volume,changed$:t,onError:r}),Me=(i,e,t,r)=>ks(e,()=>i.playbackRate,a=>{bu(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),Pt=ks;var kA=i=>["__",i.language,i.label].join("|"),wA=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},Su=class i{constructor(e){this.available$=new Jf;this.current$=new xA(void 0);this.error$=new Jf;this.subscription=new EA;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let a=s=>{this.error$.next({id:"TextTracksManager",category:PA.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(Pt(t.internalTextTracks,()=>(0,gu.default)(this.internalTracks),s=>{rt(s)&&this.setInternal(s)},{equal:(s,n)=>rt(s)&&rt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Pi(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(Pt(t.externalTextTracks,()=>(0,gu.default)(this.externalTracks),s=>{rt(s)&&this.setExternal(s)},{equal:(s,n)=>rt(s)&&rt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Pi(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(Pt(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:a})),this.subscription.add(Pt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){xi(this.video);let{textTracks:e}=this.video;this.subscription.add(Br(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(zf(Br(e,"addtrack"),Br(e,"removetrack"),Kf(["init"])).pipe(Pi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Xf((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add(zf(Br(e,"change"),Kf(["init"])).pipe(Pi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Pi(r=>r&&this.htmlTextTrackToITextTrack(r).id),Xf()).subscribe(this.current$));let t=r=>this.applyCueSettings(r.target?.activeCues??null);this.subscription.add(Br(e,"addtrack").subscribe(r=>{r.track?.addEventListener("cuechange",t);let a=s=>{let n=s.target?.cues??null;n&&n.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",a))};r.track?.addEventListener("cuechange",a)})),this.subscription.add(Br(e,"removetrack").subscribe(r=>{r.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let a=r;rt(t.align)&&(a.align=t.align),rt(t.position)&&(a.position=t.position),rt(t.size)&&(a.size=t.size),rt(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){xi(this.video);let t=[...this.video.textTracks];return e?t:t.filter(i.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:r}=e,a=e.id?e.id:kA(e),s=this.externalTracks.has(a),n=(s?this.externalTracks.get(a)?.isAuto:this.internalTracks.get(a)?.isAuto)??a.includes("auto");return s?{id:a,type:"external",isAuto:n,language:t,label:r,url:this.externalTracks.get(a)?.url}:{id:a,type:"internal",isAuto:n,language:t,label:r,url:this.internalTracks.get(a)?.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(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:a,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===a&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(a=>a.id===r)).forEach(([,r])=>this.detach(r))}select(e){xi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(IA(e)||!wA(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){xi(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){xi(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.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)}},De=Su;var pt=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 Zf=i=>{let e=i;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},vu=i=>{let e=Zf(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},eb=i=>{let e=Zf(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};import{fromEvent as Ce,map as kt,merge as rb,filterChanged as RA,isNonNullable as ib,Subject as $A,filter as ab,mapTo as sb,combine as LA,once as MA,ErrorCategory as DA,ValueSubject as nb,clientChecker as CA}from"@vkontakte/videoplayer-shared";var AA=3,tb=(i,e,t=AA)=>{let r=0,a=0;for(let s=0;s<i.length;s++){let n=i.start(s),o=i.end(s);if(n<=e&&e<=o){if(r=n,a=o,!t)return{from:r,to:a};for(let u=s-1;u>=0;u--)i.end(u)+t>=r&&(r=i.start(u));for(let u=s+1;u<i.length;u++)i.start(u)-t<=a&&(a=i.end(u))}}return{from:r,to:a}};var ye=i=>{let e=v=>Ce(i,v).pipe(sb(void 0)),r=rb(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(v=>Ce(i,v))).pipe(kt(v=>v.type==="ended"?i.readyState<2:i.readyState<3),RA()),a=rb(Ce(i,"progress"),Ce(i,"timeupdate")).pipe(kt(()=>tb(i.buffered,i.currentTime))),s=CA.isSafari?LA({play:e("play").pipe(MA()),playing:e("playing")}).pipe(sb(void 0)):e("playing"),n=Ce(i,"volumechange").pipe(kt(()=>({muted:i.muted,volume:i.volume}))),o=Ce(i,"ratechange").pipe(kt(()=>i.playbackRate)),u=Ce(i,"error").pipe(ab(()=>!!(i.error||i.played.length)),kt(()=>{let v=i.error;return{id:v?`MediaError#${v.code}`:"HtmlVideoError",category:DA.VIDEO_PIPELINE,message:v?v.message:"Error event from HTML video element",thrown:i.error??void 0}})),l=Ce(i,"timeupdate").pipe(kt(()=>i.currentTime)),c=new $A,d=.3,p;l.subscribe(v=>{i.loop&&ib(p)&&ib(v)&&p>=i.duration-d&&v<=d&&c.next(p),p=v});let h=e("pause").pipe(ab(()=>!i.error&&p!==i.duration)),f=Ce(i,"enterpictureinpicture"),b=Ce(i,"leavepictureinpicture"),g=new nb(eb(i));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let S=new nb(vu(i));return Ce(i,"fullscreenchange").pipe(kt(()=>vu(i))).subscribe(S),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Ce(i,"durationchange").pipe(kt(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:S,enterPip$:f,leavePip$:b}};import{VideoQuality as wt}from"@vkontakte/videoplayer-shared";var At=i=>{switch(i){case"mobile":return wt.Q_144P;case"lowest":return wt.Q_240P;case"low":return wt.Q_360P;case"sd":case"medium":return wt.Q_480P;case"hd":case"high":return wt.Q_720P;case"fullhd":case"full":return wt.Q_1080P;case"quadhd":case"quad":return wt.Q_1440P;case"ultrahd":case"ultra":return wt.Q_2160P}};var Rt=V(Or(),1),vb=V(je(),1),ws=V(xr(),1);import{isNonNullable as J,isNullable as Tu,now as yb,isHigher as Iu,isHigherOrEqual as Eu,isInvariantQuality as bb,isLower as gb,isLowerOrEqual as xu,videoSizeToQuality as HA,assertNotEmptyArray as Tb,assertNonNullable as jA}from"@vkontakte/videoplayer-shared";var yu=!1,ht={},hb=i=>{yu=i},mb=()=>{ht={}},fb=i=>{i(ht)},ki=(i,e)=>{yu&&(ht.meta=ht.meta??{},ht.meta[i]=e)},de=class{constructor(e){this.name=e}next(e){if(!yu)return;ht.series=ht.series??{};let t=ht.series[this.name]??[];t.push([Date.now(),e]),ht.series[this.name]=t}};var GA=new de("best_bitrate"),Ib=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;var Pu=i=>(e,t)=>i*(Number(e.bitrate)-Number(t.bitrate)),wi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=yb()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Eb='Assertion "ABR Tracks is empty array" failed',As=(i,e,t,r)=>{let a=[...e].sort(Pu(1)),s=[...t].sort(Pu(1)),n=s.filter(u=>J(u.bitrate)&&J(i.bitrate)?i.bitrate/u.bitrate>r:!0),o=(0,Rt.default)(s,Math.round(s.length*a.indexOf(i)/(a.length+1)))??(0,Rt.default)(s,-1);return o&&(0,vb.default)(n,o)?o:n.length?(0,Rt.default)(n,-1):(0,Rt.default)(s,0)},Sb=i=>"quality"in i,xb=(i,e,t,r)=>{let a=J(r?.last?.bitrate)&&J(t?.bitrate)&&r.last.bitrate<t.bitrate?i.trackCooldownIncreaseQuality:i.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&yb()-r.history[t.id]<=a&&(!r.last||t.id!==r.last.id);if(t?.id&&r&&!s&&r.recordSelection(t),s&&r?.last){let n=r.last;r?.recordSwitch(n);let o=Sb(n)?"video":"audio",u=Sb(n)?n.quality:n.bitrate;return e({message:`
|
|
8
8
|
[last ${o} selected] ${u}
|
|
9
|
-
`}),n}return r?.recordSwitch(t),t},
|
|
9
|
+
`}),n}return r?.recordSwitch(t),t},QA=(i,e)=>Math.log(e)/Math.log(i),$t=(i,{container:e,estimatedThroughput:t,tuning:r,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:f})=>{Tb(i,Eb);let b=r.containerSizeFactor;if(r.usePixelRatio&&window.devicePixelRatio){let T=window.devicePixelRatio;if(r.pixelRatioMultiplier)b*=r.pixelRatioMultiplier*(T-1)+1;else{let W=r.pixelRatioLogBase,[fe=0,w=0,C=0]=r.pixelRatioLogCoefficients,B=QA(W,fe*T+w)+C;Number.isFinite(B)&&(b*=B)}}let g=r.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*b,height:e.height*b}:void 0,S=r.considerPlaybackRate&&J(o)?o:1,P=i.filter(T=>!bb(T.quality)).sort((T,W)=>Iu(T.quality,W.quality)?-1:1),v=(0,Rt.default)(P,-1)?.quality,R=(0,Rt.default)(P,0)?.quality,y=Tu(a)||J(a.min)&&J(a.max)&&gb(a.max,a.min)||J(a.min)&&R&&Iu(a.min,R)||J(a.max)&&v&&gb(a.max,v),E=S*Ib(n??.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),L={},q=P.filter(T=>{let W=!0;if(g)if(T.size)W=T.size.width<=g.width&&T.size.height<=g.height;else{let st=g&&HA(g);W=st?xu(T.quality,st):!0}if(!W)return L[T.quality]="FitsContainer",!1;let fe=h||t;if(!(J(fe)&&isFinite(fe)&&J(T.bitrate)?fe-s>=T.bitrate*E:!0))return L[T.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&J(r.minBufferToSwitchUp)&&u&&!bb(u.quality)&&(n??0)<r.minBufferToSwitchUp&&Iu(T.quality,u.quality))return L[T.quality]="Buffer",!1;if(!!d&&Eu(T.quality,d))return L[T.quality]="DroppedFramesLimit",!1;if(!!p&&Eu(T.quality,p))return L[T.quality]="StallsLimit",!1;let j=y||(Tu(a.max)||xu(T.quality,a.max))&&(Tu(a.min)||Eu(T.quality,a.min)),Be=J(c)&&!c?xu(T.quality,r.backgroundVideoQualityLimit):!0;return!j||!Be?(L[T.quality]="FitsQualityLimits",!1):!0})[0];q&&q.bitrate&&GA.next(q.bitrate);let H=q??(0,Rt.default)(P,-1)??i[0],$=l?.last,k=xb(r,f,H,l);return J(l)&&k.quality!==$?.quality&&f({message:`
|
|
10
10
|
[VIDEO TRACKS ABR]
|
|
11
11
|
[available video tracks]
|
|
12
|
-
${
|
|
12
|
+
${i.map(T=>`{ id: ${T.id}, quality: ${T.quality}, bitrate: ${T.bitrate}, size: ${T.size?.width}:${T.size?.height} }`).join(`
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[tuning]
|
|
16
|
-
${(0,ws.default)(r??{}).map(([
|
|
16
|
+
${(0,ws.default)(r??{}).map(([T,W])=>`${T}: ${W}`).join(`
|
|
17
17
|
`)}
|
|
18
18
|
|
|
19
19
|
[limit params]
|
|
20
20
|
containerSizeFactor: ${b},
|
|
21
21
|
containerSizeLimit: ${g?.width??0} x ${g?.height??0},
|
|
22
22
|
estimatedThroughput: ${t},
|
|
23
|
-
stallsPredictedThroughput: ${
|
|
23
|
+
stallsPredictedThroughput: ${h},
|
|
24
24
|
reserve: ${s},
|
|
25
25
|
playbackRate: ${o},
|
|
26
|
-
playbackRateFactor: ${
|
|
26
|
+
playbackRateFactor: ${S},
|
|
27
27
|
forwardBufferHealth: ${n},
|
|
28
|
-
bitrateFactor: ${
|
|
28
|
+
bitrateFactor: ${E},
|
|
29
29
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
30
|
-
droppedVideoMaxQualityLimit: ${
|
|
30
|
+
droppedVideoMaxQualityLimit: ${d},
|
|
31
31
|
stallsVideoMaxQualityLimit: ${p},
|
|
32
32
|
limitsAreInvalid: ${y},
|
|
33
|
-
maxQualityLimit: ${
|
|
34
|
-
minQualityLimit: ${
|
|
33
|
+
maxQualityLimit: ${a?.max},
|
|
34
|
+
minQualityLimit: ${a?.min},
|
|
35
35
|
|
|
36
36
|
[limited video tracks]
|
|
37
|
-
${(0,ws.default)(
|
|
37
|
+
${(0,ws.default)(L).map(([T,W])=>`${T}: ${W}`).join(`
|
|
38
38
|
`)||"All tracks are available"}
|
|
39
39
|
|
|
40
|
-
[best video track] ${
|
|
41
|
-
[selected video track] ${
|
|
42
|
-
`}),
|
|
40
|
+
[best video track] ${q?.quality}
|
|
41
|
+
[selected video track] ${k?.quality}
|
|
42
|
+
`}),k},Pb=(i,e,t,{estimatedThroughput:r,tuning:a,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{Tb(t,Eb);let c=a.considerPlaybackRate&&J(s)?s:1,d=[...t].sort(Pu(-1)),p=i.bitrate;jA(p);let h=c*Ib(n??.5,a.bitrateAudioFactorAtEmptyBuffer,a.bitrateAudioFactorAtFullBuffer),f,b=As(i,e,t,a.minVideoAudioRatio),g=l||r;J(g)&&isFinite(g)&&(f=d.find(v=>J(v.bitrate)&&J(b?.bitrate)?g-p>=v.bitrate*h&&v.bitrate>=b.bitrate:!1)),f||(f=b);let S=o?.last,P=f&&xb(a,u,f,o);return J(o)&&P?.bitrate!==S?.bitrate&&u({message:`
|
|
43
43
|
[AUDIO TRACKS ABR]
|
|
44
44
|
[available audio tracks]
|
|
45
45
|
${t.map(v=>`{ id: ${v.id}, bitrate: ${v.bitrate} }`).join(`
|
|
46
46
|
`)}
|
|
47
47
|
|
|
48
48
|
[tuning]
|
|
49
|
-
${(0,ws.default)(
|
|
49
|
+
${(0,ws.default)(a??{}).map(([v,R])=>`${v}: ${R}`).join(`
|
|
50
50
|
`)}
|
|
51
51
|
|
|
52
52
|
[limit params]
|
|
@@ -54,20 +54,20 @@ var my=Object.create;var Ol=Object.defineProperty;var fy=Object.getOwnPropertyDe
|
|
|
54
54
|
stallsPredictedThroughput: ${l},
|
|
55
55
|
reserve: ${p},
|
|
56
56
|
playbackRate: ${s},
|
|
57
|
-
playbackRateFactor: ${
|
|
57
|
+
playbackRateFactor: ${c},
|
|
58
58
|
forwardBufferHealth: ${n},
|
|
59
|
-
bitrateFactor: ${
|
|
60
|
-
minBufferToSwitchUp: ${
|
|
59
|
+
bitrateFactor: ${h},
|
|
60
|
+
minBufferToSwitchUp: ${a.minBufferToSwitchUp},
|
|
61
61
|
|
|
62
62
|
[selected audio track] ${f?.id}
|
|
63
|
-
`}),f&&xb(i,u,f,o)};var ee=a=>new URL(a).hostname;import{assertNever as Vb,assertNonNullable as Bb,combine as pR,debounce as hR,ErrorCategory as Ob,filter as _b,filterChanged as mR,isNonNullable as Lu,map as Ms,merge as Nb,observableFrom as fR,once as bR,Subscription as gR,ValueSubject as $u,videoQualityToHeight as vR,videoSizeToQuality as SR}from"@vkontakte/videoplayer-shared";var kb=D(He(),1),wb=a=>{if(a instanceof DOMException&&(0,kb.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"))},Se=async(a,e)=>{let t=a.muted;try{await a.play()}catch(r){if(!wb(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{await a.play()}catch(i){return wb(i)&&(a.muted=!1,console.warn(i)),!1}}return!0};import{isNonNullable as Rs,isNullable as YA,assertNonNullable as Ri}from"@vkontakte/videoplayer-shared";var Rb=D(Vr(),1);import{isNonNullable as Ab,assertNonNullable as As,now as QA}from"@vkontakte/videoplayer-shared";function te(){return QA()}function wu(a){return te()-a}function ku(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,i=n=>r.test(n);return{resolve:(n,o,u=!1)=>{i(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Lb(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function _r(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,d,c,p=!1,m="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;As(d);let x=wu(d),q;if(x<b){q=b-x,setTimeout(g,q);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,I()},v=x=>(s=x,S),w=x=>(c=x,S),P=()=>(m="json",S),L=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,c&&c(),t&&t()}},y=x=>(p=x,S),I=()=>{d=te(),n=new i,n.open("get",a);let x=0,q,xe=0,Ve=()=>(As(d),Math.max(d,Math.max(q||0,xe||0)));if(s&&n.addEventListener("progress",k=>{let C=te();s.updateChunk&&k.loaded>x&&(s.updateChunk(Ve(),k.loaded-x),x=k.loaded,q=C)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>L())),n.addEventListener("load",()=>{if(u)return;As(n);let k=n.status;if(k>=200&&k<300){let{response:C,responseType:O}=n,A=C?.byteLength;if(typeof A=="number"&&s){let H=A-x;H&&s.updateChunk&&s.updateChunk(Ve(),H)}O==="json"&&(!C||!(0,Rb.default)(C).length)?L():(c&&c(),e(C))}else L()}),n.addEventListener("error",()=>{L()}),p){let k=()=>{As(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(xe=te(),n.removeEventListener("readystatechange",k))};n.addEventListener("readystatechange",k)}return n.responseType=m,n.send(),S},S={withBitrateReporting:v,withParallel:y,withJSONResponse:P,withRetryCount:x=>(l=x,S),withRetryInterval:(x,q)=>(Ab(x)&&(b=x),Ab(q)&&(f=q),S),withTimeout:x=>(o=x,S),withFinally:w,send:I,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return S}var ki=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,r){return{start:e,end:t,bytes:r}}_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 r=0,i=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,i+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;i+=u,s.start=t,s.bytes-=u}}}if(i>0&&r>0){let s=i*8/(r/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(i)}/${Math.round(r)} 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,r){return this.intervals.push(this._createInterval(e,t,r)),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 $b=D(Vr(),1);var Ai=class{constructor(e,t,r,i,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=r,this.MAX_PARALLEL_REQUESTS=i,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 r=te(),i=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=te()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=_r(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=te()}_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=te();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!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,$b.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,i){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=i,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}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=i,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 zA}from"@vkontakte/videoplayer-shared";var Ls=1e4,Au=3;var KA=6e4,XA=10,JA=1,ZA=500,Li=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=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.params=e,this.soundProhibitedEvent$=new zA,this.chunkRateEstimator=new ki(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ku(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,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=ku(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,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-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}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.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,r=t.buffered.length,i;r!==0&&(i=t.buffered.start(r-1),t.currentTime<i&&(e("Fixup stall"),t.currentTime=i))}_selectQuality(e){let{videoElement:t}=this.params,r,i,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!i||s.bitrate>i.bitrate)&&(i=s):(!r||r.bitrate>s.bitrate)&&(r=s));return i||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Rs(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:i,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Lb(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Ai(Au,Ls,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,l=null,d=!1,c=()=>{let L=s&&(!d||d===this.rep);return L||t("Not running!"),L},p=(L,y,I)=>{u&&u.abort(),u=_r(this.urlResolver.resolve(L,!1),y,I,()=>this._retryCallback()).withTimeout(Ls).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Au).withFinally(()=>{u=null}).send()},m=(L,y,I)=>{Ri(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(L,!1),y,I,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=L=>{let y=r.playbackRate;r.playbackRate!==L&&(t(`Playback rate switch: ${y}=>${L}`),r.playbackRate=L)},b=L=>{this.lowLatency=L,t(`lowLatency changed to ${L}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let L=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let I=te()-1e4,R=0;for(let F=0;F<this.bufferStates.length;F++){let U=this.bufferStates[F];L=Math.min(L,U.buf),U.ts<I&&R++}this.bufferStates.splice(0,R),t(`update playback rate; minBuffer=${L} drop=${R} jitter=${this.sourceJitter}`);let Q=L-JA;this.sourceJitter>=0?Q-=this.sourceJitter/2:this.sourceJitter-=1,Q>3?f(1.15):Q>1?f(1.1):Q>.3?f(1.05):f(1)}},v=L=>{let y,I=()=>y&&y.start?y.start.length:0,R=k=>y.start[k]/1e3,Q=k=>y.dur[k]/1e3,F=k=>y.fragIndex+k,U=(k,C)=>({chunkIdx:F(k),startTS:R(k),dur:Q(k),discontinuity:C}),S=()=>{let k=0;if(y&&y.dur){let C=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,O=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,A=C;this.sourceJitter>1&&(A+=this.sourceJitter-1);let H=y.dur.length-1;for(;H>=0&&(A-=y.dur[H],!(A<=0));--H);k=Math.min(H,y.dur.length-1-O),k=Math.max(k,0)}return U(k,!0)},x=k=>{let C=I();if(!(C<=0)){if(Rs(k)){for(let O=0;O<C;O++)if(R(O)>k)return U(O)}return S()}},q=k=>{let C=I(),O=k?k.chunkIdx+1:0,A=O-y.fragIndex;if(!(C<=0)){if(!k||A<0||A-C>XA)return t(`Resync: offset=${A} bChunks=${C} chunk=`+JSON.stringify(k)),S();if(!(A>=C))return U(O-y.fragIndex,!1)}},xe=(k,C,O)=>{l&&l.abort(),l=_r(this.urlResolver.resolve(k,!0,this.lowLatency),C,O,()=>this._retryCallback()).withTimeout(Ls).withRetryCount(Au).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(k,C)=>{xe(L,O=>{if(!c())return;y=O;let A=!!y.lowLatency;A!==this.lowLatency&&b(A);let H=0;for(let at=0;at<y.dur.length;++at)H+=y.dur[at];H>0&&(Ri(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(H/y.dur.length)),i({name:"index",zeroTime:y.zeroTime,shiftDuration:y.shiftDuration}),this.sourceJitter=y.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,y.jitter/1e3)):1,k(x(C))},()=>this._handleNetworkError())},nextChunk:q}},w=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Ri(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:L=>{let{videoElement:y,logger:I}=this.params,R=v(e.jidxUrl),Q,F,U,S,x=0,q,xe,Ve,k=()=>{q&&(clearTimeout(q),q=void 0);let V=Math.max(ZA,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),re=x+V,ue=te(),X=Math.min(1e4,re-ue);x=ue;let ze=()=>{l||c()&&R.seek(()=>{c()&&(x=te(),C(),k())})};X>0?q=window.setTimeout(()=>{this.paused?k():ze()},X):ze()},C=()=>{let V;for(;V=R.nextChunk(S);)S=V,lr(V);let re=R.nextChunk(U);if(re){if(U&&re.discontinuity){I("Detected discontinuity; restarting playback"),this.paused?k():(w(),this._initPlayerWith(e));return}at(re)}else k()},O=(V,re)=>{if(!c()||!this.sourceBuffer)return;let ue,X,ze,Be=Oe=>{window.setTimeout(()=>{c()&&O(V,re)},Oe)};if(this.sourceBuffer.updating)I("Source buffer is updating; delaying appendBuffer"),Be(100);else{let Oe=te(),st=y.currentTime;!this.paused&&y.buffered.length>1&&xe===st&&Oe-Ve>500&&(I("Stall suspected; trying to fix"),this._fixupStall()),xe!==st&&(xe=st,Ve=Oe);let gt=this._getBufferSizeSec();if(gt>30)I(`Buffered ${gt} seconds; delaying appendBuffer`),Be(2e3);else try{this.sourceBuffer.appendBuffer(V),this.videoPlayStarted?(this.bufferStates.push({ts:Oe,buf:gt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),re&&re()}catch(nt){if(nt.name==="QuotaExceededError")I("QuotaExceededError; delaying appendBuffer"),ze=this.sourceBuffer.buffered.length,ze!==0&&(ue=this.sourceBuffer.buffered.start(0),X=st,X-ue>4&&this.sourceBuffer.remove(ue,X-3)),Be(1e3);else throw nt}}},A=()=>{F&&Q&&(I([`Appending chunk, sz=${F.byteLength}:`,JSON.stringify(U)]),O(F,function(){F=null,C()}))},H=V=>e.fragUrlTemplate.replace("%%id%%",V.chunkIdx),at=V=>{c()&&m(H(V),(re,ue)=>{if(c()){if(ue/=1e3,F=re,U=V,n=V.startTS,ue){let X=Math.min(10,V.dur/ue);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*X:X}A()}},()=>this._handleNetworkError())},lr=V=>{c()&&(Ri(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(H(V),!1)))},Ye=V=>{c()&&(e.cachedHeader=V,O(V,()=>{Q=!0,A()}))};s=!0,R.seek(V=>{if(c()){if(x=te(),!V){k();return}S=V,!YA(L)||V.startTS>L?at(V):(U=V,C())}},L),e.cachedHeader?Ye(e.cachedHeader):p(e.headerUrl,Ye,()=>this._handleNetworkError())},stop:w,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),Rs(i)&&(i+=.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,Ri(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Rs(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=c=>{if(!this.autoQuality)return;let p,m,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(m=this._getBufferSizeSec(),f=c/this.bitrate,m>10&&f>.8||m>15&&f>.5||m>20&&f>.3)){e(`Not switching: buffer=${Math.floor(m)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}p=this._selectQuality(c),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${c}`)},s={updateChunk:(p,m)=>{let f=te();if(this.chunkRateEstimator.addInterval(p,f,m)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:m,duration:f-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let c=s.get();if(c&&o&&this.autoQuality){if(u&&c>o&&wu(n)<3e4)return;r(c)}u=this.autoQuality};return{updateChunk:(c,p)=>{let m=s.updateChunk(c,p);return m&&l(),m},notifySwitch:c=>{let p=te();c<o&&(n=p),o=c}}}_fetchManifest(e,t,r){this.manifestRequest=_r(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Ls).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;Se(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n?.length?(n.forEach((u,l)=>{u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({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))},KA))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Cb=D(xr(),1);import{debounce as eR,filter as Mb,fromEvent as tR,interval as rR,isHigher as iR,isInvariantQuality as aR,isLower as sR,merge as nR,Subject as Db,Subscription as oR}from"@vkontakte/videoplayer-shared";var Ru=class{constructor(){this.onDroopedVideoFramesLimit$=new Db;this.subscription=new oR;this.playing=!1;this.tracks=[];this.forceChecker$=new Db;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&&!aR(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,i=t-this.prevDroppedVideoFrames,s=1-(r-i)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&iR(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(tR(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=rR(this.droppedFramesChecker.checkTime).pipe(Mb(()=>this.playing),Mb(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(eR(this.droppedFramesChecker.checkTime)),r=nR(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),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,Cb.default)(this.limitCounts).filter(([,r])=>r>=this.droppedFramesChecker.countLimit).sort(([r],[i])=>sR(r,i)?-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}},$s=Ru;import{map as uR,Observable as lR}from"@vkontakte/videoplayer-shared";import{fromEvent as cR}from"@vkontakte/videoplayer-shared";var $i=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var dR=(a,e)=>new lR(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||$i()))},{...r,...e});i.observe(a);let s=cR(document,"visibilitychange").pipe(uR(n=>!document.hidden||$i())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Ce=dR;var yR=["paused","playing","ready"],TR=["paused","playing","ready"],Mi=class{constructor(e){this.subscription=new gR;this.videoState=new $("stopped");this.representations$=new $u([]);this.droppedFramesManager=new $s;this.maxSeekBackTime$=new $u(1/0);this.zeroTime$=new $u(void 0);this.liveOffset=new dt;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:Ob.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,r=[];for(let i of t){let s=i.name??i.index.toString(10),n=kt(i.name)??SR(i.video),o=i.bitrate/1e3,u={...i.video};if(!n)continue;let l={id:s,quality:n,bitrate:o,size:u};r.push({track:l,representation:i})}this.representations$.next(r),this.params.output.availableVideoTracks$.next(r.map(({track:i})=>i)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,r=this.representations$.getValue().find(({representation:i})=>i===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),Lu(r)&&this.params.output.currentVideoTrack$.next(r);break}case"bandwidth":{let{size:t,duration:r}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,r);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(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,Mu.default)(TR,e)&&(n||o)){this.prepare();return}if(i?.to!=="paused"&&s.state==="requested"&&(0,Mu.default)(yR,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(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=i?.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(se(this.params.source.url,u))}return;default:return Vb(e)}};this.textTracksManager=new Me(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:Ob.WTF,message:"DashLiveProvider internal logic error",thrown:i})};Nb(this.videoState.stateChangeStarted$.pipe(Ms(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Ms(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=fe(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(ee(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 r=ve(this.video);this.subscription.add(this.representations$.pipe(Ms(i=>i.map(({track:s})=>s)),_b(i=>!!i.length),bR()).subscribe(i=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:i}))),this.subscription.add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(mR(),Ms(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(pR({zeroTime:this.zeroTime$.pipe(_b(Lu)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(et(this.video,this.params.desiredState.isLooped,t)).add(ge(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add($e(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ce(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&vR(i);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:i})})).add(this.videoState.stateChangeEnded$.subscribe(i=>{switch(i.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 Vb(i.to)}},t)).add(Nb(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,fR(["init"])).pipe(hR(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),be(this.video)}createLiveDashPlayer(){let e=new Li({videoElement:this.video,videoState:this.videoState,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(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&Lu(t)?t:Rt(e.map(({track:l})=>l),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},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=i?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let l=e.find(({track:d})=>d.id===s)?.representation;Bb(l,"Representations missing"),this.dash.startPlay(l,r)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:r})=>r.id===e.id)?.representation;Bb(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(),r=this.videoState.getState(),i=t==="paused"&&r==="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)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var Fb=Mi;var hS=D(He(),1);var rt=(a,e)=>{let t=0;for(let r=0;r<a.length;r++){let i=a.start(r)*1e3,s=a.end(r)*1e3;i<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as lM,assertNonNullable as cM,debounce as dM,ErrorCategory as vl,filter as cS,filterChanged as Ia,fromEvent as pM,isNonNullable as dS,map as Sl,merge as en,observableFrom as yl,once as pS,Subscription as hM}from"@vkontakte/videoplayer-shared";var Ds=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Nr=class extends Ds{constructor(){super(),this.listeners||Ds.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)}},Di=class{constructor(){Object.defineProperty(this,"signal",{value:new Nr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document>"u")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch{r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(Di.prototype[Symbol.toStringTag]="AbortController",Nr.prototype[Symbol.toStringTag]="AbortSignal");function Cs(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 Du(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!Cs({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(l,d){let c;d&&d.signal&&(c=d.signal,delete d.signal);let p=new t(l,d);return c&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let d=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(d){let c;try{c=new DOMException("Aborted","AbortError")}catch{c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);let p=new Promise((m,f)=>{d.addEventListener("abort",()=>f(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var Ci=Cs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),qb=Ci?Du({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ge=Ci?qb.fetch:window.fetch,O_=Ci?qb.Request:window.Request,ne=Ci?Di:window.AbortController,__=Ci?Nr:window.AbortSignal;var ml=D(Vu(),1);var Os=D(Or(),1);var ht=()=>window.ManagedMediaSource||window.MediaSource,Vs=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),og=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),ug=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Fs,clientChecker as _s}from"@vkontakte/videoplayer-shared";var Ns=document.createElement("video"),QR='video/mp4; codecs="avc1.42000a,mp4a.40.2"',WR='video/mp4; codecs="hev1.1.6.L93.B0"',lg='video/webm; codecs="vp09.00.10.08"',cg='video/webm; codecs="av01.0.00M.08"',YR='audio/mp4; codecs="mp4a.40.2"',zR='audio/webm; codecs="opus"',Vi={mms:Vs(),mse:og(),hls:!!(Ns.canPlayType?.("application/x-mpegurl")||Ns.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},ye={mp4:!!Ns.canPlayType?.("video/mp4"),webm:!!Ns.canPlayType?.("video/webm"),cmaf:!0},Te={h264:!!ht()?.isTypeSupported?.(QR),h265:!!ht()?.isTypeSupported?.(WR),vp9:!!ht()?.isTypeSupported?.(lg),av1:!!ht()?.isTypeSupported?.(cg),aac:!!ht()?.isTypeSupported?.(YR),opus:!!ht()?.isTypeSupported?.(zR)},Fr=(Te.h264||Te.h265)&&Te.aac,Zt,KR=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:cg}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:lg}})]);Zt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{KR()}catch(a){console.error(a)}var qr=Vi.hls&&ye.mp4,dg=()=>Object.keys(Te).filter(a=>Te[a]),pg=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let i=Vi.mse&&(!r||!!window.MediaStreamTrack)||Vi.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return i&&ye.mp4&&Fr;case"DASH_WEBM":return i&&ye.webm&&Te.vp9&&Te.opus;case"DASH_WEBM_AV1":return i&&ye.webm&&Te.av1&&Te.opus;case"DASH_STREAMS":return i&&(ye.mp4&&Fr||ye.webm&&(Te.vp9||Te.av1)&&(Te.opus||Te.aac));case"DASH_LIVE":return i&&ye.mp4&&Fr;case"DASH_LIVE_CMAF":return i&&ye.mp4&&Fr&&ye.cmaf;case"DASH_ONDEMAND":return i&&ye.mp4&&Fr;case"HLS":case"HLS_ONDEMAND":return qr||e&&i&&ye.mp4&&Fr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return qr;case"MPEG":return ye.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Vi.webrtc&&Vi.ws&&Te.h264&&(ye.mp4||ye.webm);default:return Fs(s)}})},Bs=a=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(a){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return Zt?Zt[t].smooth?[t,e]:Zt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Zt?Zt[t].powerEfficient?[t,e]:Zt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Fs(a)}return[e,t]},hg=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...Bs(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(_s.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[...i,"MPEG",...Bs(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Bs(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Bs(a),...i,"HLS","HLS_ONDEMAND"];default:Fs(e)}return qr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},mg=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],i=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...i],n=[...i,...r],o,u=_s.isMac&&_s.isSafari;if(_s.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:Fs(a)}else qr&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Bu=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],fg=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,Os.default)(t.value.split("."),0)}for(let t of a){let r=(0,Os.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,Os.default)(e.value.split("."),0)};var Bg=D(Vg(),1);import{ErrorCategory as Oi}from"@vkontakte/videoplayer-shared";var Og=a=>{if(!a)return{id:"EmptyResponse",category:Oi.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Oi.NETWORK,message:`UV Error ${a}`};let e=(0,Bg.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Oi.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:Oi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Oi.PARSER,message:"Response is valid XML, but parser failed"}};var Lt=(a,e,t=0)=>{for(let r=0;r<a.length;r++)if(a.start(r)*1e3-t<=e&&a.end(r)*1e3+t>e)return!0;return!1};import{abortable as pl,assertNonNullable as sr,clientChecker as H$,combine as Wr,ErrorCategory as Vt,filter as va,filterChanged as Ys,flattenObject as Sa,fromEvent as nr,getTraceSubscriptionMethod as j$,interval as hl,isNonNullable as rS,map as ya,merge as or,now as G$,Subject as iS,Subscription as aS,tap as Q$,throttle as W$,ValueSubject as z}from"@vkontakte/videoplayer-shared";var Us=D(He(),1),Gr=D(Or(),1),Hs=D(Vu(),1);var hL=(a,e={})=>{let r=e.timeout||1,i=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-i-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-i))}})},1)},mL=a=>window.clearTimeout(a),_g=a=>typeof a=="function"&&a?.toString().endsWith("{ [native code] }"),Ng=!_g(window.requestIdleCallback)||!_g(window.cancelIdleCallback),qu=Ng?hL:window.requestIdleCallback,_i=Ng?mL:window.cancelIdleCallback;var Yv=D(Is(),1);import{assertNever as fL,ErrorCategory as Fg,clientChecker as Uu,Subject as qg}from"@vkontakte/videoplayer-shared";var bL=18,Ug=!1;try{Ug=Uu.isSafari&&!!Uu.macVersion&&Uu.macVersion<=bL}catch(a){console.error(a)}var Hu=class{constructor(e){this.bufferFull$=new qg;this.error$=new qg;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:Fg.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(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})}async remove(e,t,r){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let r,i=s=>{this.abortRequested=!1,t(s)};Ug&&e?r={operation:"safariAbort",init:e,callback:i}:r={operation:"abort",callback:i};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,r&&(this.queue=[r]),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(i){i instanceof DOMException&&i.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):i instanceof DOMException&&i.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Fg.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:i}),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:fL(t)}}},Hg=Hu;var ju=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 Mt,assertNonNullable as Ie,clientChecker as M$,ErrorCategory as Dt,fromEvent as ol,getExponentialDelay as ul,isNonNullable as jr,isNullable as oe,now as qs,once as D$,Subject as C$,Subscription as V$,ValueSubject as rr}from"@vkontakte/videoplayer-shared";var B=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let i=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,i)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}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 Ur=class extends B{};var Ni=class extends B{constructor(t,r){super(t,r);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let i=this.content.byteOffset,s=i+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(i,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var Fi=class extends B{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let i=this.readString(4);this.compatibleBrands.push(i),r-=4}}};var qi=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var G=class extends B{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Ui=class extends G{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var Hi=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ji=class extends B{constructor(e,t){super(e,t),this.data=this.content}};var er=class extends G{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,l=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var Gi=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Qi=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Wi=class extends G{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Yi=class extends G{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var zi=class extends G{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Ki=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Xi=class extends G{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 Ji=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Zi=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ea=class extends G{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ta=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ra=class extends G{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 ia=class extends G{constructor(t,r){super(t,r);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 aa=class extends G{constructor(t,r){super(t,r);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 i=0;i<this.sampleCount;i++)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 sa=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var na=class extends G{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var oa=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var vL={ftyp:Fi,moov:qi,mvhd:Ui,moof:Hi,mdat:ji,sidx:er,trak:Gi,mdia:Ki,mfhd:ea,tkhd:Xi,traf:ta,tfhd:ra,tfdt:ia,trun:aa,minf:Ji,sv3d:Qi,st3d:Wi,prhd:Yi,proj:Zi,equi:zi,uuid:Ni,stbl:sa,stsd:na,avc1:oa,unknown:Ur},mt=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch{break}return t}createBox(e,t){let r=vL[e];return r?new r(t,new a):new Ur(t,new a)}};var $t=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var yL=new TextDecoder("ascii"),TL=a=>yL.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",IL=a=>{let e=new er(a,new mt),t=e.earliestPresentationTime/e.timescale*1e3,r=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},EL=(a,e)=>{let r=new mt().parse(a),i=new $t(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,c)},xL=a=>{let t=new mt().parse(a),r=new $t(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},PL=a=>{let t=new mt().parse(a);return new $t(t).find("sidx")?.timescale},wL=(a,e)=>{let r=new mt().parse(a),s=new $t(r).findAll("traf"),n=s[s.length-1].children.find(c=>c.type==="tfhd"),o=s[s.length-1].children.find(c=>c.type==="tfdt"),u=s[s.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,p)=>c+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},kL=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}}},r=new mt().parse(a),i=new $t(r);if(i.find("sv3d")){e.is3dVideo=!0;let n=i.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=i.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=i.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},jg={validateData:TL,parseInit:kL,getIndexRange:()=>{},parseSegments:IL,parseFeedableSegmentChunk:EL,getChunkEndTime:wL,getServerLatencyTimestamps:xL,getTimescaleFromIndex:PL};var la=D(He(),1);import{assertNonNullable as Qu,isNonNullable as Yg,isNullable as RL}from"@vkontakte/videoplayer-shared";import{assertNever as AL}from"@vkontakte/videoplayer-shared";var Gg={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"}},Qg=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 r=ua(a,t),i=r in Gg,s=i?Gg[r].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,d=ua(u),c=l*2**((o-1)*8)+d,p=t+o,m;return p+c>a.byteLength?m=new DataView(a.buffer,a.byteOffset+p):m=new DataView(a.buffer,a.byteOffset+p,c),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+c,value:m,valueSize:c}},ua=(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},Qe=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return ua(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:AL(e)}},tr=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=Qg(r);if(!e(i))return;i.type==="master"&&tr(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},Wg=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=Qg(a);return tr(i.value,({tag:s,type:n,value:o})=>(s===17143?e=Qe(o,n):s===17026?t=Qe(o,n):s===17029&&(r=Qe(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var zg=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],LL=[231,22612,22743,167,171,163,160,175],$L=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,d=!1,c=0;return tr(a,({tag:p,type:m,value:f,valueSize:b})=>{if(p===21419){let g=Qe(f,m);l=ua(g)}else p!==21420&&(l=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=Qe(f,m):p===17545?i=Qe(f,m):p===21420&&l===475249515?u=Qe(f,m):p===374648427?tr(f,({tag:g,type:v,value:w})=>g===30321?(d=Qe(w,v)===1,!1):!0):s&&n&&(0,la.default)(zg,p)&&(o=!0),!o}),Qu(e,"Failed to parse webm Segment start"),Qu(t,"Failed to parse webm Segment end"),Qu(i,"Failed to parse webm Segment duration"),r=r??1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},ML=a=>{if(RL(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},DL=(a,e)=>{let t=!1,r=!1,i=o=>Yg(o.time)&&Yg(o.position),s=[],n;return tr(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=Qe(l,u));break;case 183:break;case 241:n&&(n.position=Qe(l,u));break;default:t&&(0,la.default)(zg,o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:d}=o,c=s[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},CL=a=>{let e=0,t=!1;try{tr(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,la.default)(LL,r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||=(0,la.default)([163,160,175],r.tag)),!0):!1)}catch{}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},Kg={validateData:Wg,parseInit:$L,getIndexRange:ML,parseSegments:DL,parseFeedableSegmentChunk:CL};var ca=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return Kg;case"mp4":return jg}}throw new ReferenceError(`Unsupported mime type ${a}`)};var al=D(bv(),1),Uv=D(xr(),1),Hv=D(Mv(),1),jv=D(Or(),1),sl=D(Vr(),1);var Dv=D(He(),1),Ju=a=>{let e=a.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[i,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[i,s,n]=r;return!!(i&&parseInt(i,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let i=r[0];if(!i||i.length!==6)return!1;let[s,n]=i.toUpperCase(),o=s+n;return(0,Dv.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as $$,isNullable as Fv}from"@vkontakte/videoplayer-shared";var Cv=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Vv=a=>{try{let e=R$(),t=a.match(e),{groups:r}=t??{};if(r){let i={};if(r.extensions){let o=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(o||[]).forEach(u=>{i[u[0]]=u.slice(2)})}let s=r.variants?.split(/-/).filter(o=>o!==""),n={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:i,variants:s};return Object.keys(n).forEach(o=>{let u=n[o];(typeof u>"u"||u==="")&&delete n[o]}),n}return null}catch{return null}};function R$(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
64
|
-
(?<language>${`(?:[a-z]{2,3}(?:-${
|
|
63
|
+
`}),P};var te=i=>new URL(i).hostname;import{assertNever as Vb,assertNonNullable as Bb,combine as hR,debounce as mR,ErrorCategory as Ob,filter as _b,filterChanged as fR,isNonNullable as $u,map as Ds,merge as Nb,observableFrom as bR,once as gR,Subscription as SR,ValueSubject as Lu,videoQualityToHeight as vR,videoSizeToQuality as yR}from"@vkontakte/videoplayer-shared";var wb=V(je(),1),kb=i=>{if(i instanceof DOMException&&(0,wb.default)(["Failed to load because no supported source was found.","The element has no supported sources."],i.message))throw i;return!(i instanceof DOMException&&(i.code===20||i.name==="AbortError"))},Te=async(i,e)=>{let t=i.muted;try{await i.play()}catch(r){if(!kb(r))return!1;if(e&&e(),t)return console.warn(r),!1;i.muted=!0;try{await i.play()}catch(a){return kb(a)&&(i.muted=!1,console.warn(a)),!1}}return!0};import{isNonNullable as $s,isNullable as zA,assertNonNullable as $i}from"@vkontakte/videoplayer-shared";var Rb=V(Vr(),1);import{isNonNullable as Ab,assertNonNullable as Rs,now as WA}from"@vkontakte/videoplayer-shared";function re(){return WA()}function ku(i){return re()-i}function wu(i){let e=i.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,a=n=>r.test(n);return{resolve:(n,o,u=!1)=>{a(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function $b(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function _r(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;Rs(c);let k=ku(c),T;if(k<b){T=b-k,setTimeout(g,T);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new a,E()},S=k=>(s=k,$),P=k=>(d=k,$),v=()=>(h="json",$),R=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},y=k=>(p=k,$),E=()=>{c=re(),n=new a,n.open("get",i);let k=0,T,W=0,fe=()=>(Rs(c),Math.max(c,Math.max(T||0,W||0)));if(s&&n.addEventListener("progress",w=>{let C=re();s.updateChunk&&w.loaded>k&&(s.updateChunk(fe(),w.loaded-k),k=w.loaded,T=C)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>R())),n.addEventListener("load",()=>{if(u)return;Rs(n);let w=n.status;if(w>=200&&w<300){let{response:C,responseType:B}=n,A=C?.byteLength;if(typeof A=="number"&&s){let j=A-k;j&&s.updateChunk&&s.updateChunk(fe(),j)}B==="json"&&(!C||!(0,Rb.default)(C).length)?R():(d&&d(),e(C))}else R()}),n.addEventListener("error",()=>{R()}),p){let w=()=>{Rs(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(W=re(),n.removeEventListener("readystatechange",w))};n.addEventListener("readystatechange",w)}return n.responseType=h,n.send(),$},$={withBitrateReporting:S,withParallel:y,withJSONResponse:v,withRetryCount:k=>(l=k,$),withRetryInterval:(k,T)=>(Ab(k)&&(b=k),Ab(T)&&(f=T),$),withTimeout:k=>(o=k,$),withFinally:P,send:E,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return $}var Ai=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,r){return{start:e,end:t,bytes:r}}_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 r=0,a=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,a+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;a+=u,s.start=t,s.bytes-=u}}}if(a>0&&r>0){let s=a*8/(r/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(a)}/${Math.round(r)} 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,r){return this.intervals.push(this._createInterval(e,t,r)),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 Lb=V(Vr(),1);var Ri=class{constructor(e,t,r,a,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=r,this.MAX_PARALLEL_REQUESTS=a,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 r=re(),a=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=re()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=_r(t,s,()=>a("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=re()}_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=re();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!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,Lb.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,a){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=a,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}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=a,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 KA}from"@vkontakte/videoplayer-shared";var Ls=1e4,Au=3;var XA=6e4,JA=10,ZA=1,eR=500,Li=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=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.params=e,this.soundProhibitedEvent$=new KA,this.chunkRateEstimator=new Ai(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=wu(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,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=wu(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,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-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}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.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,r=t.buffered.length,a;r!==0&&(a=t.buffered.start(r-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){let{videoElement:t}=this.params,r,a,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!a||s.bitrate>a.bitrate)&&(a=s):(!r||r.bitrate>s.bitrate)&&(r=s));return a||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||$s(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:a,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),a.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,a.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{$b(a,"progress",()=>{a.buffered.length?(a.currentTime=a.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Ri(Au,Ls,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:a}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let R=s&&(!c||c===this.rep);return R||t("Not running!"),R},p=(R,y,E)=>{u&&u.abort(),u=_r(this.urlResolver.resolve(R,!1),y,E,()=>this._retryCallback()).withTimeout(Ls).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Au).withFinally(()=>{u=null}).send()},h=(R,y,E)=>{$i(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(R,!1),y,E,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=R=>{let y=r.playbackRate;r.playbackRate!==R&&(t(`Playback rate switch: ${y}=>${R}`),r.playbackRate=R)},b=R=>{this.lowLatency=R,t(`lowLatency changed to ${R}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let R=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let E=re()-1e4,L=0;for(let q=0;q<this.bufferStates.length;q++){let H=this.bufferStates[q];R=Math.min(R,H.buf),H.ts<E&&L++}this.bufferStates.splice(0,L),t(`update playback rate; minBuffer=${R} drop=${L} jitter=${this.sourceJitter}`);let U=R-ZA;this.sourceJitter>=0?U-=this.sourceJitter/2:this.sourceJitter-=1,U>3?f(1.15):U>1?f(1.1):U>.3?f(1.05):f(1)}},S=R=>{let y,E=()=>y&&y.start?y.start.length:0,L=w=>y.start[w]/1e3,U=w=>y.dur[w]/1e3,q=w=>y.fragIndex+w,H=(w,C)=>({chunkIdx:q(w),startTS:L(w),dur:U(w),discontinuity:C}),$=()=>{let w=0;if(y&&y.dur){let C=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,B=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,A=C;this.sourceJitter>1&&(A+=this.sourceJitter-1);let j=y.dur.length-1;for(;j>=0&&(A-=y.dur[j],!(A<=0));--j);w=Math.min(j,y.dur.length-1-B),w=Math.max(w,0)}return H(w,!0)},k=w=>{let C=E();if(!(C<=0)){if($s(w)){for(let B=0;B<C;B++)if(L(B)>w)return H(B)}return $()}},T=w=>{let C=E(),B=w?w.chunkIdx+1:0,A=B-y.fragIndex;if(!(C<=0)){if(!w||A<0||A-C>JA)return t(`Resync: offset=${A} bChunks=${C} chunk=`+JSON.stringify(w)),$();if(!(A>=C))return H(B-y.fragIndex,!1)}},W=(w,C,B)=>{l&&l.abort(),l=_r(this.urlResolver.resolve(w,!0,this.lowLatency),C,B,()=>this._retryCallback()).withTimeout(Ls).withRetryCount(Au).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(w,C)=>{W(R,B=>{if(!d())return;y=B;let A=!!y.lowLatency;A!==this.lowLatency&&b(A);let j=0;for(let Be=0;Be<y.dur.length;++Be)j+=y.dur[Be];j>0&&($i(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(j/y.dur.length)),a({name:"index",zeroTime:y.zeroTime,shiftDuration:y.shiftDuration}),this.sourceJitter=y.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,y.jitter/1e3)):1,w(k(C))},()=>this._handleNetworkError())},nextChunk:T}},P=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),$i(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:R=>{let{videoElement:y,logger:E}=this.params,L=S(e.jidxUrl),U,q,H,$,k=0,T,W,fe,w=()=>{T&&(clearTimeout(T),T=void 0);let O=Math.max(eR,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ie=k+O,le=re(),Z=Math.min(1e4,ie-le);k=le;let Ke=()=>{l||d()&&L.seek(()=>{d()&&(k=re(),C(),w())})};Z>0?T=window.setTimeout(()=>{this.paused?w():Ke()},Z):Ke()},C=()=>{let O;for(;O=L.nextChunk($);)$=O,st(O);let ie=L.nextChunk(H);if(ie){if(H&&ie.discontinuity){E("Detected discontinuity; restarting playback"),this.paused?w():(P(),this._initPlayerWith(e));return}Be(ie)}else w()},B=(O,ie)=>{if(!d()||!this.sourceBuffer)return;let le,Z,Ke,Oe=_e=>{window.setTimeout(()=>{d()&&B(O,ie)},_e)};if(this.sourceBuffer.updating)E("Source buffer is updating; delaying appendBuffer"),Oe(100);else{let _e=re(),nt=y.currentTime;!this.paused&&y.buffered.length>1&&W===nt&&_e-fe>500&&(E("Stall suspected; trying to fix"),this._fixupStall()),W!==nt&&(W=nt,fe=_e);let St=this._getBufferSizeSec();if(St>30)E(`Buffered ${St} seconds; delaying appendBuffer`),Oe(2e3);else try{this.sourceBuffer.appendBuffer(O),this.videoPlayStarted?(this.bufferStates.push({ts:_e,buf:St}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ie&&ie()}catch(ot){if(ot.name==="QuotaExceededError")E("QuotaExceededError; delaying appendBuffer"),Ke=this.sourceBuffer.buffered.length,Ke!==0&&(le=this.sourceBuffer.buffered.start(0),Z=nt,Z-le>4&&this.sourceBuffer.remove(le,Z-3)),Oe(1e3);else throw ot}}},A=()=>{q&&U&&(E([`Appending chunk, sz=${q.byteLength}:`,JSON.stringify(H)]),B(q,function(){q=null,C()}))},j=O=>e.fragUrlTemplate.replace("%%id%%",O.chunkIdx),Be=O=>{d()&&h(j(O),(ie,le)=>{if(d()){if(le/=1e3,q=ie,H=O,n=O.startTS,le){let Z=Math.min(10,O.dur/le);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Z:Z}A()}},()=>this._handleNetworkError())},st=O=>{d()&&($i(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(j(O),!1)))},ze=O=>{d()&&(e.cachedHeader=O,B(O,()=>{U=!0,A()}))};s=!0,L.seek(O=>{if(d()){if(k=re(),!O){w();return}$=O,!zA(R)||O.startTS>R?Be(O):(H=O,C())}},R),e.cachedHeader?ze(e.cachedHeader):p(e.headerUrl,ze,()=>this._handleNetworkError())},stop:P,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),$s(a)&&(a+=.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,$i(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return $s(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),f=d/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let f=re();if(this.chunkRateEstimator.addInterval(p,f,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&ku(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=re();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=_r(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Ls).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;Te(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:a}=this.params,s=n=>{let o=[];return n?.length?(n.forEach((u,l)=>{u.video&&a.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({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))},XA))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Cb=V(xr(),1);import{debounce as tR,filter as Mb,fromEvent as rR,interval as iR,isHigher as aR,isInvariantQuality as sR,isLower as nR,merge as oR,Subject as Db,Subscription as uR}from"@vkontakte/videoplayer-shared";var Ru=class{constructor(){this.onDroopedVideoFramesLimit$=new Db;this.subscription=new uR;this.playing=!1;this.tracks=[];this.forceChecker$=new Db;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&&!sR(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,a=t-this.prevDroppedVideoFrames,s=1-(r-a)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&aR(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(rR(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=iR(this.droppedFramesChecker.checkTime).pipe(Mb(()=>this.playing),Mb(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(tR(this.droppedFramesChecker.checkTime)),r=oR(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),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,Cb.default)(this.limitCounts).filter(([,r])=>r>=this.droppedFramesChecker.countLimit).sort(([r],[a])=>nR(r,a)?-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}},Ms=Ru;import{map as lR,Observable as cR}from"@vkontakte/videoplayer-shared";import{fromEvent as dR}from"@vkontakte/videoplayer-shared";var Mi=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var pR=(i,e)=>new cR(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Mi()))},{...r,...e});a.observe(i);let s=dR(document,"visibilitychange").pipe(lR(n=>!document.hidden||Mi())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),Ve=pR;var TR=["paused","playing","ready"],IR=["paused","playing","ready"],Di=class{constructor(e){this.subscription=new SR;this.videoState=new M("stopped");this.representations$=new Lu([]);this.droppedFramesManager=new Ms;this.maxSeekBackTime$=new Lu(1/0);this.zeroTime$=new Lu(void 0);this.liveOffset=new pt;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:Ob.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,r=[];for(let a of t){let s=a.name??a.index.toString(10),n=At(a.name)??yR(a.video),o=a.bitrate/1e3,u={...a.video};if(!n)continue;let l={id:s,quality:n,bitrate:o,size:u};r.push({track:l,representation:a})}this.representations$.next(r),this.params.output.availableVideoTracks$.next(r.map(({track:a})=>a)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,r=this.representations$.getValue().find(({representation:a})=>a===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),$u(r)&&this.params.output.currentVideoTrack$.next(r);break}case"bandwidth":{let{size:t,duration:r}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,r);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(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,Mu.default)(IR,e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&(0,Mu.default)(TR,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ne(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=a?.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(ne(this.params.source.url,u))}return;default:return Vb(e)}};this.textTracksManager=new De(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:Ob.WTF,message:"DashLiveProvider internal logic error",thrown:a})};Nb(this.videoState.stateChangeStarted$.pipe(Ds(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Ds(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=ge(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(te(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=ye(this.video);this.subscription.add(this.representations$.pipe(Ds(a=>a.map(({track:s})=>s)),_b(a=>!!a.length),gR()).subscribe(a=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:a}))),this.subscription.add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(fR(),Ds(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(hR({zeroTime:this.zeroTime$.pipe(_b($u)),position:r.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(tt(this.video,this.params.desiredState.isLooped,t)).add(ve(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Me(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ve(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&vR(a);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:a})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.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 Vb(a.to)}},t)).add(Nb(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,bR(["init"])).pipe(mR(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),Se(this.video)}createLiveDashPlayer(){let e=new Li({videoElement:this.video,videoState:this.videoState,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(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),a=!r&&$u(t)?t:$t(e.map(({track:l})=>l),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},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=a?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),u&&this.setAutoQuality(r),n||u||s!==o){let l=e.find(({track:c})=>c.id===s)?.representation;Bb(l,"Representations missing"),this.dash.startPlay(l,r)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:r})=>r.id===e.id)?.representation;Bb(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(),r=this.videoState.getState(),a=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ne(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var Fb=Di;var mv=V(je(),1);var it=(i,e)=>{let t=0;for(let r=0;r<i.length;r++){let a=i.start(r)*1e3,s=i.end(r)*1e3;a<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as lM,assertNonNullable as cM,debounce as dM,ErrorCategory as Sl,filter as dv,filterChanged as Ea,fromEvent as pM,isNonNullable as pv,map as vl,merge as en,observableFrom as yl,once as hv,Subscription as hM}from"@vkontakte/videoplayer-shared";var Cs=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let a=0,s=r.length;a<s;a++)if(r[a].callback===t){r.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let a=0,s=r.length;a<s;a++){let n=r[a];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Nr=class extends Cs{constructor(){super(),this.listeners||Cs.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)}},Ci=class{constructor(){Object.defineProperty(this,"signal",{value:new Nr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document>"u")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch{r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(Ci.prototype[Symbol.toStringTag]="AbortController",Nr.prototype[Symbol.toStringTag]="AbortSignal");function Vs(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function Du(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!Vs({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||a)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch{d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var Vi=Vs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),qb=Vi?Du({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Qe=Vi?qb.fetch:window.fetch,O_=Vi?qb.Request:window.Request,oe=Vi?Ci:window.AbortController,__=Vi?Nr:window.AbortSignal;var ml=V(Vu(),1);var _s=V(Or(),1);var mt=()=>window.ManagedMediaSource||window.MediaSource,Bs=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),og=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),ug=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as qs,clientChecker as Ns}from"@vkontakte/videoplayer-shared";var Fs=document.createElement("video"),WR='video/mp4; codecs="avc1.42000a,mp4a.40.2"',YR='video/mp4; codecs="hev1.1.6.L93.B0"',lg='video/webm; codecs="vp09.00.10.08"',cg='video/webm; codecs="av01.0.00M.08"',zR='audio/mp4; codecs="mp4a.40.2"',KR='audio/webm; codecs="opus"',Bi={mms:Bs(),mse:og(),hls:!!(Fs.canPlayType?.("application/x-mpegurl")||Fs.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Ie={mp4:!!Fs.canPlayType?.("video/mp4"),webm:!!Fs.canPlayType?.("video/webm"),cmaf:!0},Ee={h264:!!mt()?.isTypeSupported?.(WR),h265:!!mt()?.isTypeSupported?.(YR),vp9:!!mt()?.isTypeSupported?.(lg),av1:!!mt()?.isTypeSupported?.(cg),aac:!!mt()?.isTypeSupported?.(zR),opus:!!mt()?.isTypeSupported?.(KR)},Fr=(Ee.h264||Ee.h265)&&Ee.aac,tr,XR=async()=>{if(!window.navigator.mediaCapabilities)return;let i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:cg}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:lg}})]);tr={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{XR()}catch(i){console.error(i)}var qr=Bi.hls&&Ie.mp4,dg=()=>Object.keys(Ee).filter(i=>Ee[i]),pg=(i,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let a=Bi.mse&&(!r||!!window.MediaStreamTrack)||Bi.mms&&t;return i.filter(s=>{switch(s){case"DASH_SEP":return a&&Ie.mp4&&Fr;case"DASH_WEBM":return a&&Ie.webm&&Ee.vp9&&Ee.opus;case"DASH_WEBM_AV1":return a&&Ie.webm&&Ee.av1&&Ee.opus;case"DASH_STREAMS":return a&&(Ie.mp4&&Fr||Ie.webm&&(Ee.vp9||Ee.av1)&&(Ee.opus||Ee.aac));case"DASH_LIVE":return a&&Ie.mp4&&Fr;case"DASH_LIVE_CMAF":return a&&Ie.mp4&&Fr&&Ie.cmaf;case"DASH_ONDEMAND":return a&&Ie.mp4&&Fr;case"HLS":case"HLS_ONDEMAND":return qr||e&&a&&Ie.mp4&&Fr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return qr;case"MPEG":return Ie.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Bi.webrtc&&Bi.ws&&Ee.h264&&(Ie.mp4||Ie.webm);default:return qs(s)}})},Os=i=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(i){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return tr?tr[t].smooth?[t,e]:tr[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return tr?tr[t].powerEfficient?[t,e]:tr[e].powerEfficient?[e,t]:[t,e]:[e,t];default:qs(i)}return[e,t]},hg=({webmCodec:i,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...Os(i),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],a=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Ns.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[...a,"MPEG",...Os(i),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Os(i),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Os(i),...a,"HLS","HLS_ONDEMAND"];default:qs(e)}return qr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},mg=({androidPreferredFormat:i,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],a=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...a],n=[...a,...r],o,u=Ns.isMac&&Ns.isSafari;if(Ns.isAndroid)switch(i){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:qs(i)}else qr&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Bu=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],fg=i=>{if(i.size===0)return;if(i.size===1){let t=i.values().next();return(0,_s.default)(t.value.split("."),0)}for(let t of i){let r=(0,_s.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=i.values().next();return(0,_s.default)(e.value.split("."),0)};var Bg=V(Vg(),1);import{ErrorCategory as _i}from"@vkontakte/videoplayer-shared";var Og=i=>{if(!i)return{id:"EmptyResponse",category:_i.PARSER,message:"Empty response"};if(i.length<=2&&i.match(/^\d+$/))return{id:`UVError#${i}`,category:_i.NETWORK,message:`UV Error ${i}`};let e=(0,Bg.default)(i).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:_i.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(i,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:_i.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:_i.PARSER,message:"Response is valid XML, but parser failed"}};var Lt=(i,e,t=0)=>{for(let r=0;r<i.length;r++)if(i.start(r)*1e3-t<=e&&i.end(r)*1e3+t>e)return!0;return!1};import{abortable as pl,assertNonNullable as or,clientChecker as jL,combine as Wr,ErrorCategory as Bt,filter as va,filterChanged as ya,flattenObject as Ta,fromEvent as Ot,getTraceSubscriptionMethod as GL,interval as hl,isNonNullable as rv,map as Yr,merge as ur,now as QL,Subject as iv,Subscription as av,tap as sv,throttle as WL,ValueSubject as K}from"@vkontakte/videoplayer-shared";var Hs=V(je(),1),Gr=V(Or(),1),js=V(Vu(),1);var m$=(i,e={})=>{let r=e.timeout||1,a=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-a-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-a))}})},1)},f$=i=>window.clearTimeout(i),_g=i=>typeof i=="function"&&i?.toString().endsWith("{ [native code] }"),Ng=!_g(window.requestIdleCallback)||!_g(window.cancelIdleCallback),qu=Ng?m$:window.requestIdleCallback,Ni=Ng?f$:window.cancelIdleCallback;var YS=V(Es(),1);import{assertNever as b$,ErrorCategory as Fg,clientChecker as Uu,Subject as qg}from"@vkontakte/videoplayer-shared";var g$=18,Ug=!1;try{Ug=Uu.isSafari&&!!Uu.macVersion&&Uu.macVersion<=g$}catch(i){console.error(i)}var Hu=class{constructor(e){this.bufferFull$=new qg;this.error$=new qg;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:Fg.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(r=>{let a={operation:"append",data:e,signal:t,callback:r};this.queue.push(a),this.pull()})}async remove(e,t,r){return r&&r.aborted?!1:new Promise(a=>{let s={operation:"remove",from:e,to:t,signal:r,callback:a};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let r,a=s=>{this.abortRequested=!1,t(s)};Ug&&e?r={operation:"safariAbort",init:e,callback:a}:r={operation:"abort",callback:a};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,r&&(this.queue=[r]),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(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Fg.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),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:b$(t)}}},Hg=Hu;var ju=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};import{abortable as Dt,assertNonNullable as xe,clientChecker as DL,ErrorCategory as Ct,fromEvent as ol,getExponentialDelay as ul,isNonNullable as jr,isNullable as ue,now as Us,once as CL,Subject as VL,Subscription as BL,ValueSubject as ar}from"@vkontakte/videoplayer-shared";var _=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let a=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,a)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let a=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,a}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 Ur=class extends _{};var Fi=class extends _{constructor(t,r){super(t,r);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let a=this.content.byteOffset,s=a+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(a,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var qi=class extends _{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let a=this.readString(4);this.compatibleBrands.push(a),r-=4}}};var Ui=class extends _{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Q=class extends _{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Hi=class extends Q{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var ji=class extends _{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Gi=class extends _{constructor(e,t){super(e,t),this.data=this.content}};var rr=class extends Q{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let a=this.readUint32(),s=a>>>31,n=a<<1>>>1,o=this.readUint32();a=this.readUint32();let u=a>>>28,l=a<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var Qi=class extends _{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Wi=class extends _{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Yi=class extends Q{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var zi=class extends Q{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Ki=class extends Q{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Xi=class extends _{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ji=class extends Q{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 Zi=class extends _{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ea=class extends _{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ta=class extends Q{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ra=class extends _{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ia=class extends Q{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 aa=class extends Q{constructor(t,r){super(t,r);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 sa=class extends Q{constructor(t,r){super(t,r);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 a=0;a<this.sampleCount;a++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var na=class extends _{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var oa=class extends Q{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var ua=class extends _{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var v$={ftyp:qi,moov:Ui,mvhd:Hi,moof:ji,mdat:Gi,sidx:rr,trak:Qi,mdia:Xi,mfhd:ta,tkhd:Ji,traf:ra,tfhd:ia,tfdt:aa,trun:sa,minf:Zi,sv3d:Wi,st3d:Yi,prhd:zi,proj:ea,equi:Ki,uuid:Fi,stbl:na,stsd:oa,avc1:ua,unknown:Ur},ft=class i{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch{break}return t}createBox(e,t){let r=v$[e];return r?new r(t,new i):new Ur(t,new i)}};var Mt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var T$=new TextDecoder("ascii"),I$=i=>T$.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",E$=i=>{let e=new rr(i,new ft),t=e.earliestPresentationTime/e.timescale*1e3,r=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},x$=(i,e)=>{let r=new ft().parse(i),a=new Mt(r),s=a.findAll("moof"),n=e?a.findAll("uuid"):a.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(i.buffer,l,d)},P$=i=>{let t=new ft().parse(i),r=new Mt(t),a={},s=r.findAll("uuid");return s.length?s[s.length-1]:a},k$=i=>{let t=new ft().parse(i);return new Mt(t).find("sidx")?.timescale},w$=(i,e)=>{let r=new ft().parse(i),s=new Mt(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},A$=i=>{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}}},r=new ft().parse(i),a=new Mt(r);if(a.find("sv3d")){e.is3dVideo=!0;let n=a.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=a.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=a.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},jg={validateData:I$,parseInit:A$,getIndexRange:()=>{},parseSegments:E$,parseFeedableSegmentChunk:x$,getChunkEndTime:w$,getServerLatencyTimestamps:P$,getTimescaleFromIndex:k$};var ca=V(je(),1);import{assertNonNullable as Qu,isNonNullable as Yg,isNullable as $$}from"@vkontakte/videoplayer-shared";import{assertNever as R$}from"@vkontakte/videoplayer-shared";var Gg={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"}},Qg=i=>{let e=i.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=la(i,t),a=r in Gg,s=a?Gg[r].type:"binary",n=i.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(i.buffer,i.byteOffset+t+1,o-1),l=n&255>>o,c=la(u),d=l*2**((o-1)*8)+c,p=t+o,h;return p+d>i.byteLength?h=new DataView(i.buffer,i.byteOffset+p):h=new DataView(i.buffer,i.byteOffset+p,d),{tag:a?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},la=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*2**16+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*2**32+i.getUint32(1);case 6:return i.getUint16(0)*2**32+i.getUint32(2);case 7:{let t=i.getUint8(0)*281474976710656+i.getUint16(1)*4294967296+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},We=(i,e)=>{switch(e){case"int":return i.getInt8(0);case"uint":return la(i);case"float":return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case"string":return new TextDecoder("ascii").decode(i);case"utf8":return new TextDecoder("utf-8").decode(i);case"date":return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case"master":return i;case"binary":return i;default:R$(e)}},ir=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=Qg(r);if(!e(a))return;a.type==="master"&&ir(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},Wg=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=Qg(i);return ir(a.value,({tag:s,type:n,value:o})=>(s===17143?e=We(o,n):s===17026?t=We(o,n):s===17029&&(r=We(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var zg=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],L$=[231,22612,22743,167,171,163,160,175],M$=i=>{let e,t,r,a,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return ir(i,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=We(f,h);l=la(g)}else p!==21420&&(l=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=We(f,h):p===17545?a=We(f,h):p===21420&&l===475249515?u=We(f,h):p===374648427?ir(f,({tag:g,type:S,value:P})=>g===30321?(c=We(P,S)===1,!1):!0):s&&n&&(0,ca.default)(zg,p)&&(o=!0),!o}),Qu(e,"Failed to parse webm Segment start"),Qu(t,"Failed to parse webm Segment end"),Qu(a,"Failed to parse webm Segment duration"),r=r??1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(a/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},D$=i=>{if($$(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},C$=(i,e)=>{let t=!1,r=!1,a=o=>Yg(o.time)&&Yg(o.position),s=[],n;return ir(i,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&a(n)&&s.push(n),n={};break;case 179:n&&(n.time=We(l,u));break;case 183:break;case 241:n&&(n.position=We(l,u));break;default:t&&(0,ca.default)(zg,o)&&(r=!0)}return!(t&&r)}),n&&a(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},V$=i=>{let e=0,t=!1;try{ir(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,ca.default)(L$,r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||=(0,ca.default)([163,160,175],r.tag)),!0):!1)}catch{}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},Kg={validateData:Wg,parseInit:M$,getIndexRange:D$,parseSegments:C$,parseFeedableSegmentChunk:V$};var da=i=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(i);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return Kg;case"mp4":return jg}}throw new ReferenceError(`Unsupported mime type ${i}`)};var al=V(bS(),1),US=V(xr(),1),HS=V(MS(),1),jS=V(Or(),1),sl=V(Vr(),1);var DS=V(je(),1),Ju=i=>{let e=i.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[a,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[a,s,n]=r;return!!(a&&parseInt(a,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let a=r[0];if(!a||a.length!==6)return!1;let[s,n]=a.toUpperCase(),o=s+n;return(0,DS.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as ML,isNullable as FS}from"@vkontakte/videoplayer-shared";var CS=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var VS=i=>{try{let e=$L(),t=i.match(e),{groups:r}=t??{};if(r){let a={};if(r.extensions){let o=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(o||[]).forEach(u=>{a[u[0]]=u.slice(2)})}let s=r.variants?.split(/-/).filter(o=>o!==""),n={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:a,variants:s};return Object.keys(n).forEach(o=>{let u=n[o];(typeof u>"u"||u==="")&&delete n[o]}),n}return null}catch{return null}};function $L(){let i="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
|
|
64
|
+
(?<language>${`(?:[a-z]{2,3}(?:-${i})?|[a-z]{4}|[a-z]{5,8})`})
|
|
65
65
|
(-(?<script>[a-z]{4}))?
|
|
66
66
|
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
67
67
|
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
68
68
|
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
69
69
|
(?:-(?<privateuse>(?:${e})))?
|
|
70
|
-
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var el=D(Or(),1);import{videoSizeToQuality as L$}from"@vkontakte/videoplayer-shared";var Bv=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s,streamId:n})=>{let o=(s?kt(s):void 0)??L$({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},Ov=({id:a,bitrate:e})=>({id:a,bitrate:e}),_v=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Nv=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),tl=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,el.default)(r.split("."),0),isDefault:i}),rl=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,el.default)(i.split("."),0)}),il=a=>"url"in a,de=a=>a.type==="template",da=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var qv=a=>{if(!a?.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?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),i=r?.[1]==="-"?-1:1,s={days:e(r?.[5],i),hours:e(r?.[6],i),minutes:e(r?.[7],i),seconds:e(r?.[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},ft=(a,e)=>{let t=a;t=(0,al.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of(0,Uv.default)(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,al.default)(t,n,(o,u)=>Fv(s)?o:Fv(u)?s:(0,Hv.default)(s,parseInt(u,10),"0"))}return t},Gv=(a,e)=>{let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(y=>y.textContent?.trim()??""),o=(0,jv.default)(n,0)??"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),d=l?new Date(l).getTime():void 0,c,p=s.getAttribute("mediaPresentationDuration"),f=s.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,b=[...s.getElementsByTagName("Period")],g=b.reduce((y,I)=>({...y,[I.id]:I.children}),{}),v=b.reduce((y,I)=>({...y,[I.id]:I.getAttribute("duration")}),{});p?c=qv(p):(0,sl.default)(v).filter(y=>y).length&&!u?c=(0,sl.default)(v).reduce((y,I)=>y+(qv(I)??0),0):f&&(c=parseInt(f,10));let w=0,P=s.getAttribute("profiles")?.split(",")??[];for(let y of b.map(I=>I.id))for(let I of g[y]){let R=I.getAttribute("id")??"id"+(w++).toString(10),Q=I.getAttribute("mimeType")??"",F=I.getAttribute("codecs")??"",U=I.getAttribute("contentType")??Q?.split("/")[0],S=I.getAttribute("profiles")?.split(",")??[],x=Vv(I.getAttribute("lang")??"")??{},q=I.querySelector("Label")?.textContent?.trim()??void 0,xe=I.querySelectorAll("Representation"),Ve=I.querySelector("SegmentTemplate"),k=I.querySelector("Role")?.getAttribute("value")??void 0,C=U,O={id:R,language:x.language,isDefault:k==="main",label:q,codecs:F,hdr:C==="video"&&Ju(F),mime:Q,representations:[]};for(let A of xe){let H=A.getAttribute("lang")??void 0,at=q??I.getAttribute("label")??A.getAttribute("label")??void 0,lr=A.querySelector("BaseURL")?.textContent?.trim()??"",Ye=new URL(lr||o,e).toString(),V=A.getAttribute("mimeType")??Q,re=A.getAttribute("codecs")??F??"",ue;if(U==="text"){let X=A.getAttribute("id")||"",ze=x.privateuse?.includes("x-auto")||X.includes("_auto"),Be=A.querySelector("SegmentTemplate");if(Be){let Oe={representationId:A.getAttribute("id")??void 0,bandwidth:A.getAttribute("bandwidth")??void 0},st=parseInt(A.getAttribute("bandwidth")??"",10)/1e3,gt=parseInt(Be.getAttribute("startNumber")??"",10)??1,nt=parseInt(Be.getAttribute("timescale")??"",10),bn=Be.querySelectorAll("SegmentTimeline S")??[],cr=Be.getAttribute("media");if(!cr)continue;let Ba=[],Oa=0,_a="",dr=0,Kr=gt,le=0;for(let _e of bn){let Nt=parseInt(_e.getAttribute("d")??"",10),Le=parseInt(_e.getAttribute("r")??"",10)||0,vt=parseInt(_e.getAttribute("t")??"",10);le=Number.isFinite(vt)?vt:le;let Ft=Nt/nt*1e3,pr=le/nt*1e3;for(let Ke=0;Ke<Le+1;Ke++){let St=ft(cr,{...Oe,segmentNumber:Kr.toString(10),segmentTime:(le+Ke*Nt).toString(10)}),hr=(pr??0)+Ke*Ft,Jr=hr+Ft;Kr++,Ba.push({time:{from:hr,to:Jr},url:St})}le+=(Le+1)*Nt,Oa+=(Le+1)*Ft}dr=le/nt*1e3,_a=ft(cr,{...Oe,segmentNumber:Kr.toString(10),segmentTime:le.toString(10)});let Xr={time:{from:dr,to:1/0},url:_a},ot={type:"template",baseUrl:Ye,segmentTemplateUrl:cr,initUrl:"",totalSegmentsDurationMs:Oa,segments:Ba,nextSegmentBeyondManifest:Xr,timescale:nt};ue={id:X,kind:"text",segmentReference:ot,profiles:[],duration:c,bitrate:st,mime:"",codecs:"",width:0,height:0,isAuto:ze}}else ue={id:X,isAuto:ze,kind:"text",url:Ye}}else{let X=A.getAttribute("contentType")??V?.split("/")[0]??U,ze=I.getAttribute("profiles")?.split(",")??[],Be=parseInt(A.getAttribute("width")??"",10),Oe=parseInt(A.getAttribute("height")??"",10),st=parseInt(A.getAttribute("bandwidth")??"",10)/1e3,gt=A.getAttribute("frameRate")??"",nt=A.getAttribute("quality")??void 0,bn=gt?Cv(gt):void 0,cr=A.getAttribute("id")??"id"+(w++).toString(10),Ba=X==="video"?`${Oe}p`:X==="audio"?`${st}Kbps`:re,Oa=`${cr}@${Ba}`,_a=[...P,...S,...ze],dr,Kr=A.querySelector("SegmentBase"),le=A.querySelector("SegmentTemplate")??Ve;if(Kr){let ot=A.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[_e,Nt]=ot.split("-").map(St=>parseInt(St,10)),Le={from:_e,to:Nt},vt=A.querySelector("SegmentBase")?.getAttribute("indexRange"),[Ft,pr]=vt?vt.split("-").map(St=>parseInt(St,10)):[],Ke=vt?{from:Ft,to:pr}:void 0;dr={type:"byteRange",url:Ye,initRange:Le,indexRange:Ke}}else if(le){let ot={representationId:A.getAttribute("id")??void 0,bandwidth:A.getAttribute("bandwidth")??void 0},_e=parseInt(le.getAttribute("timescale")??"",10),Nt=le.getAttribute("initialization")??"",Le=le.getAttribute("media"),vt=parseInt(le.getAttribute("startNumber")??"",10)??1,Ft=ft(Nt,ot);if(!Le)throw new ReferenceError("No media attribute in SegmentTemplate");let pr=le.querySelectorAll("SegmentTimeline S")??[],Ke=[],St=0,hr="",Jr=0;if(pr.length){let Na=vt,Ne=0;for(let mr of pr){let Xe=parseInt(mr.getAttribute("d")??"",10),qt=parseInt(mr.getAttribute("r")??"",10)||0,Fa=parseInt(mr.getAttribute("t")??"",10);Ne=Number.isFinite(Fa)?Fa:Ne;let gn=Xe/_e*1e3,dy=Ne/_e*1e3;for(let qa=0;qa<qt+1;qa++){let py=ft(Le,{...ot,segmentNumber:Na.toString(10),segmentTime:(Ne+qa*Xe).toString(10)}),Bl=(dy??0)+qa*gn,hy=Bl+gn;Na++,Ke.push({time:{from:Bl,to:hy},url:py})}Ne+=(qt+1)*Xe,St+=(qt+1)*gn}Jr=Ne/_e*1e3,hr=ft(Le,{...ot,segmentNumber:Na.toString(10),segmentTime:Ne.toString(10)})}else if($$(c)){let Ne=parseInt(le.getAttribute("duration")??"",10)/_e*1e3,mr=Math.ceil(c/Ne),Xe=0;for(let qt=1;qt<mr;qt++){let Fa=ft(Le,{...ot,segmentNumber:qt.toString(10),segmentTime:Xe.toString(10)});Ke.push({time:{from:Xe,to:Xe+Ne},url:Fa}),Xe+=Ne}Jr=Xe,hr=ft(Le,{...ot,segmentNumber:mr.toString(10),segmentTime:Xe.toString(10)})}let cy={time:{from:Jr,to:1/0},url:hr};dr={type:"template",baseUrl:Ye,segmentTemplateUrl:Le,initUrl:Ft,totalSegmentsDurationMs:St,segments:Ke,nextSegmentBeyondManifest:cy,timescale:_e}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!X||!V)continue;let Xr={video:"video",audio:"audio",text:"text"}[X];if(!Xr)continue;C||=Xr,ue={id:Oa,kind:Xr,segmentReference:dr,profiles:_a,duration:c,bitrate:st,mime:V,codecs:re,width:Be,height:Oe,fps:bn,quality:nt}}O.language||=H,O.label||=at,O.mime||=V,O.codecs||=re,O.hdr||=C==="video"&&Ju(re),O.representations.push(ue)}if(C){let A=i[C].find(H=>H.id===O.id);if(A&&O.representations.every(H=>de(H.segmentReference)))for(let H of A.representations){let lr=O.representations.find(V=>V.id===H.id)?.segmentReference,Ye=H.segmentReference;Ye.segments.push(...lr.segments),Ye.nextSegmentBeyondManifest=lr.nextSegmentBeyondManifest}else i[C].push(O)}}return{dynamic:u,liveAvailabilityStartTime:d,duration:c,streams:i,baseUrls:n}};var Wv=D(He(),1);import{isNonNullable as Qv}from"@vkontakte/videoplayer-shared";var pe=(a,e)=>Qv(a)&&Qv(e)&&a.readyState==="open"&&(0,Wv.default)([...a.activeSourceBuffers],e);var pa=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new rr(0);this.currentLowLatencySegmentLength$=new rr(0);this.currentSegmentLength$=new rr(0);this.onLastSegment$=new rr(!1);this.fullyBuffered$=new rr(!1);this.playingRepresentation$=new rr(void 0);this.playingRepresentationInit$=new rr(void 0);this.error$=new C$;this.gaps=[];this.subscription=new V$;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ne;this.switchAbortController=new ne;this.destroyAbortController=new ne;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=Mt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Ie(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Hg(this.sourceBuffer),this.subscription.add(ol(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Dt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:Dt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add(ol(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Dt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!pe(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,ju(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=rt(this.sourceBuffer.buffered,o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Ie(r,"No init buffer for starting representation"),Ie(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=Mt(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);Ie(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(oe(s)||oe(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),Ie(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!pe(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();jr(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=Mt(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);Ie(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(oe(s)||oe(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),Ie(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!pe(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();jr(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=Mt(this.destroyAbortController.signal,async function*(e){let t=(0,Hs.default)(e,u=>u.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let u of this.representations.keys()){let l=t.find(p=>p.id===u);l&&this.representations.set(u,l);let d=this.representations.get(u);if(!d||!de(d.segmentReference))return;let c=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,c)}let r=this.switchingToRepresentationId??this.downloadingRepresentationId,i=this.representations.get(r);Ie(i);let s=this.segments.get(r);Ie(s,"No segments for starting representation");let n=this.initData.get(r);if(Ie(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!l?.dynamic,this.baseUrls=l?.baseUrls??[],this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ne,Mt(this.switchAbortController.signal,async function*(r,i=!1){this.switchingToRepresentationId=r;let s=this.representations.get(r);Ie(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if(oe(o)||oe(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),Ie(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!pe(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),i)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=r,yield this.dropBuffer();else{let u=this.getCurrentPosition();jr(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=r,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!oe(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 ne,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(oe(e)||oe(this.downloadingRepresentationId)||oe(this.playingRepresentationId)||oe(this.sourceBuffer)||!pe(this.mediaSource,this.sourceBuffer)||jr(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(Ie(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(l=>e>=l.time.from&&e<l.time.to);jr(i)&&isFinite(i.time.from)&&isFinite(i.time.to)&&this.currentSegmentLength$.next(i?.time.to-i.time.from);let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=rt(this.sourceBuffer.buffered,e),c=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=i.time.to-e+100&&(s=c)}if(isFinite(this.bufferLimit)&&ju(this.sourceBuffer.buffered)>=this.bufferLimit){let l=rt(this.sourceBuffer.buffered,e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<d);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if((0,Us.default)(o,i))l="high";else{let d=(0,Gr.default)(o,0);d&&d.time.from-i.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&rt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Gr.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let r=0,i=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+i}),r=s.time.to;jr(t.duration)&&t.duration-r>0&&!this.isLive&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=(0,Hs.default)(e?.streams[this.kind],i=>i.representations).find(i=>i.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){let t=(0,Hs.default)(e?.streams[this.kind],r=>r.representations)??[];if(![...this.segments.values()].every(r=>!r.length))for(let r of t){if(!r||!de(r.segmentReference))return;let i=r.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,n=this.segments.get(r.id)??[],o=(0,Gr.default)(n,-1)?.time.to??0,u=i?.findIndex(l=>o>=l.time.from+s&&o<=l.time.to+s);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(r.segmentReference);this.segments.set(r.id,l)}else{let l=i.slice(u+1);this.segments.set(r.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Ie(e);let t=this.segments.get(e);if(t?.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let r of this.representations.values()){let i=r.segmentReference;if(!de(i))return;let s=this.segments.get(r.id)??[],n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*i.timescale/1e3).toString(10),l=ft(i.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);return r?r.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&&_i&&_i(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&_i&&_i(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,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:c,time:{from:p,to:m}},f)=>{let b=p<=r&&m>=r,g=p>r||b||f===0&&r===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),w=this.preloadOnly&&p<=r+v||m<=r+v;return(c==="none"||c==="partially_ejected"&&g&&w&&this.sourceBuffer&&pe(this.mediaSource,this.sourceBuffer)&&!(Lt(this.sourceBuffer.buffered,p)&&Lt(this.sourceBuffer.buffered,m)))&&g&&w});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=i;c<s.length&&(n<=l||o<=d);c++){let p=s[c];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,r="auto"){de(t.segmentReference)?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Mt(o,async function*(){let d=ul(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=qs(),!d)return;let c=new DataView(d),p=ca(t.mime);if(!isFinite(i.segment.time.to)){let b=t.segmentReference.timescale;i.segment.time.to=p.getChunkEndTime(c,b)}u&&i.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:m,serverDataPreparedTime:f}=p.getServerLatencyTimestamps(c);m&&f&&this.currentLiveSegmentServerLatency$.next(f-m),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),da(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())de(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,r="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Mt(n,async function*(){let u=ul(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),ol(window,"online").pipe(D$()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=qs(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),da(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(de(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,Gr.default)(e,0).byte.from,to:(0,Gr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=qs(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Dt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!de(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=qs();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:Dt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Us.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){i();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=ca(n.mime).parseFeedableSegmentChunk(l,this.isLive);d?.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){await n();continue}let d=l.byte.from-r,c=l.byte.to-r,p=c-d+1,m=d<i,f=c<=i;if(!m)continue;let b=ca(o.mime);if(l.status==="downloading"&&f){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+d,p);await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,i-d),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),v=u.loadedBytes===p?g:b.parseFeedableSegmentChunk(g);v?.byteLength&&(l.status="partially_fed",u.feedingBytes+=v.byteLength,await this.sourceBufferTaskQueue.append(v,s)&&!s.aborted?(u.fedBytes+=v.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){if(!(oe(this.sourceBuffer)||!pe(this.mediaSource,this.sourceBuffer))){!this.isLive&&M$.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Lt(this.sourceBuffer.buffered,e.segment.time.from,100)&&Lt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Dt.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",il(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let i of this.segments.get(r.id)??[])i.status==="fed"&&Math.round(i.time.from)===Math.round(e.segment.time.from)&&Math.round(i.time.to)===Math.round(e.segment.time.to)&&(i.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[i,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=qu(()=>(0,Yv.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",r=!1){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?Mt(this.destroyAbortController.signal,async function*(){let o=ul(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,ca(e.mime),i)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let p=d;this.isLive&&de(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:Dt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,r=!1){if(!this.sourceBuffer||!pe(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||oe(e))return!1;let i=[],s=0,n=u=>{u.sort((d,c)=>d.from-c.from);let l=[u[0]];for(let d=1;d<u.length;d++){let{from:c,to:p}=u[d],m=l[l.length-1];m.to>=c?m.to=Math.max(m.to,p):l.push(u[d])}return l},o=u=>{if(s>=t)return i;i.push({...u.time}),i=n(i);let l=il(u)?u.size??0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let d=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let p of this.segments.values())for(let m of p)(0,Us.default)(["none","partially_ejected"],m.status)&&Math.round(m.time.from)<=Math.round(l)&&Math.round(m.time.to)>=Math.round(d)&&c++;if(c===this.segments.size){let p={time:{from:l,to:d},url:"",status:"none"};o(p)}}if(i.length&&r){let u=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+u&&d.status==="fed"&&o(d)}return i.length?(await Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,d)=>l||d,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!pe(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||!pe(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(){let e=this.getCurrentPosition();return!this.sourceBuffer||!pe(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||oe(e)?0:rt(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!pe(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!pe(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=qu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Dt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(oe(this.sourceBuffer)||!pe(this.mediaSource,this.sourceBuffer)||oe(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=100;for(let r of this.segments.values())for(let i of r){let{status:s}=i;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(i.time.from),o=Math.ceil(i.time.to),u=e.some(d=>d.from-t<=n&&d.to+t>=o),l=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(l.length===1?i.status="partially_ejected":this.gaps.some(d=>d.from===i.time.from||d.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var ha=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var zv=a=>{let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),r=e===null?"http1":e??void 0,i=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:r,reused:i}};import{abortable as ma,assertNever as Xv,fromEvent as Jv,merge as B$,now as fa,Subscription as O$,ValueSubject as ll,flattenObject as Qr}from"@vkontakte/videoplayer-shared";var Kv=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var js=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new ll(void 0);this.lastConnectionReused$=new ll(void 0);this.lastRequestFirstBytes$=new ll(void 0);this.abortAllController=new ne;this.subscription=new O$;this.fetchManifest=ma(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=ha(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=Kv(r));let i=yield Ge(r,{signal:this.abortAllController.signal}).catch(ba);return i?(t.log("success",Qr({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",Qr({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=ma(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){let l=e,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let S=new URL(l,location.href);S.searchParams.append("bytes",`${r.from}-${r.to}`),l=S.toString();break}default:Xv(t)}this.requestQuic&&(l=ha(l));let p=this.abortAllController.signal,m;if(n){let S=new ne;if(m=B$(Jv(this.abortAllController.signal,"abort"),Jv(n,"abort")).subscribe(()=>{try{S.abort()}catch(x){ba(x)}}),this.abortAllController.signal.aborted||n.aborted)try{S.abort()}catch(x){ba(x)}p=S.signal}let f=fa();c.log("startRequest",Qr({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:f}));let b=yield Ge(l,{priority:s,headers:d,signal:p}).catch(ba),g=fa();if(!b)return c.error("error",{message:"No response in request"}),c.end(),m?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(g-f),!b.ok||!b.body){m?.unsubscribe();let S=`Fetch error ${b.status}: ${b.statusText}`;return c.error("error",{message:S}),c.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!i&&!o){m?.unsubscribe();let S=fa(),x={requestStartedAt:f,requestEndedAt:S,duration:S-f};return c.log("endRequest",Qr(x)),c.end(),b.arrayBuffer()}let[v,w]=b.body.tee(),P=v.getReader();o&&this.throughputEstimator?.trackStream(w,u);let L=0,y=new Uint8Array(0),I=!1,R=S=>{m?.unsubscribe(),I=!0,ba(S)},Q=ma(p,async function*({done:S,value:x}){if(L===0&&this.lastRequestFirstBytes$.next(fa()-f),p.aborted){m?.unsubscribe();return}if(!S&&x){let q=new Uint8Array(y.length+x.length);q.set(y),q.set(x,y.length),y=q,L+=x.byteLength,i?.(new DataView(y.buffer),L),yield P?.read().then(Q,R)}}.bind(this));yield P?.read().then(Q,R),m?.unsubscribe();let F=fa(),U={failed:I,requestStartedAt:f,requestEndedAt:F,duration:F-f};return I?(c.error("endRequest",Qr(U)),c.end(),null):(c.log("endRequest",Qr(U)),c.end(),y.buffer)}.bind(this));this.fetchByteRangeRepresentation=ma(this.abortAllController.signal,async function*(e,t,r){if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(d,s))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!c)return null;let p=new DataView(c,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let m=t.parseInit(p),f=e.indexRange??t.getIndexRange(m);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(c,f.from-n,f.to-f.from+1);else{let v=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!v)return null;b=new DataView(v)}let g=t.parseSegments(b,m,f);return{init:m,dataView:new DataView(c),segments:g}}.bind(this));this.fetchTemplateRepresentation=ma(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(i)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:r}=zv(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){let{type:i}=e;switch(i){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,r)??null;case"template":return await this.fetchTemplateRepresentation(e,r)??null;default:Xv(i)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},ba=a=>{if(!da(a))throw a};var ir=(a,e,t)=>t*e+(1-t)*a,cl=(a,e)=>a.reduce((t,r)=>t+r,0)/e,Zv=(a,e,t,r)=>{let i=0,s=t,n=cl(a,e),o=e<r?e:r;for(let u=0;u<o;u++)a[s]>n?i++:i--,s=(a.length+s-1)%a.length;return Math.abs(i)===o};import{isNullable as _$,ValueSubject as eS}from"@vkontakte/videoplayer-shared";var Ct=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 eS(e.initial),this.debounced$=new eS(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ce(`raw_${t}`),this.smoothedSeries$=new ce(`smoothed_${t}`),this.reportedSeries$=new ce(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,r++);this.takenMeasures=r,t/=r;let i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;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)&&(_$(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 Gs=class extends Ct{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ir(this.slow,e,this.params.emaAlphaSlow),this.fast=ir(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Qs=class extends Ct{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=cl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ir(this.emaSmoothed,e,this.params.emaAlpha);let r=Zv(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Ws=class extends Ct{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?ir(this.smoothed,t,this.params.emaAlpha):t}};var ar=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new Gs({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new Qs({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new Ws({initial:e,label:"liveEdgeDelay",...t})}};var dl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as N$,ValueSubject as F$}from"@vkontakte/videoplayer-shared";var ga=class a{constructor(e,t){this.currentRepresentation$=new F$(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(!N$(e))for(let t of this.representations)for(let r of t){let i=r.segmentReference,s=i.segments.length,n=i.segments[0].time.from,o=i.segments[s-1].time.to;if(e<n||e>o)continue;let u=i.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,i.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let r=a.filterRepresentations(t.representations);if(r){this.representations[this.representationsCursor]=r,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&&de(t.segmentReference))}};var Y$=["timeupdate","progress","play","seeked","stalled","waiting"],z$=["timeupdate","progress","loadeddata","playing","seeked"];var zs=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new aS;this.representationSubscription=new aS;this.state$=new $("none");this.currentVideoRepresentation$=new z(void 0);this.currentVideoRepresentationInit$=new z(void 0);this.currentAudioRepresentation$=new z(void 0);this.currentVideoSegmentLength$=new z(0);this.currentAudioSegmentLength$=new z(0);this.error$=new iS;this.lastConnectionType$=new z(void 0);this.lastConnectionReused$=new z(void 0);this.lastRequestFirstBytes$=new z(void 0);this.currentLiveTextRepresentation$=new z(null);this.isLive$=new z(!1);this.liveDuration$=new z(0);this.liveAvailabilityStartTime$=new z(void 0);this.bufferLength$=new z(0);this.liveLatency$=new z(void 0);this.liveLoadBufferLength$=new z(0);this.livePositionFromPlayer$=new z(0);this.isLowLatency$=new z(!1);this.isActiveLowLatency$=new z(!1);this.currentStallDuration$=new z(0);this.videoLastDataObtainedTimestamp$=new z(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new iS;this.gapWatchdogActive=!1;this.destroyController=new ne;this.initManifest=pl(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=se(t,r,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:Vt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=pl(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Vt.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=Gv(e??"",this.manifestUrlString)}catch(n){let o=Og(e)??{id:"ManifestParsing",category:Vt.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(o)}if(!t)return null;let r=(n,o,u)=>!!(this.element?.canPlayType?.(o)&&ht()?.isTypeSupported?.(`${o}; codecs="${u}"`)||n==="text");if(t.dynamic){this.isLive$.next(t.dynamic),this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime);let n=(t.duration??0)/1e3;this.liveDuration$.next(-1*n)}let i={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let u=t.streams[n].filter(({mime:c,codecs:p})=>r(n,c,p)),l=new Set(u.map(({codecs:c})=>c)),d=fg(l);if(d&&(i[n]=u.filter(({codecs:c})=>c.startsWith(d))),n==="video"){let c=this.tuning.preferHDR,p=i.video.some(f=>f.hdr),m=i.video.some(f=>!f.hdr);H$.isHDR&&c&&p?i.video=i.video.filter(f=>f.hdr):m&&(i.video=i.video.filter(f=>!f.hdr))}}let s={...t,streams:i};return this.tracer.log("updateManifestEnd",Sa(s)),s}.bind(this));this.initRepresentations=pl(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initRepresentationsStart",Sa({initialVideo:e,initialAudio:t,sourceHls:r})),sr(this.manifest),sr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=c=>{this.representationSubscription.add(nr(c,"error").pipe(va(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:Vt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=this.tuning.useManagedMediaSource?ug():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Vs())if(r){let c=document.createElement("source");i(c),c.type="application/x-mpegurl",c.src=r.url,this.element.appendChild(c)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.isLowLatency$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((c,p)=>[...c,...p.representations],[]);if(this.videoBufferManager=new pa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],rS(t)){let c=this.manifest.streams.audio.reduce((p,m)=>[...p,...m.representations],[]);this.audioBufferManager=new pa("audio",this.source,c,n),this.bufferManagers.push(this.audioBufferManager)}ga.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new ga(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(hl(1e3).subscribe(c=>{if(this.element?.paused){let p=Es(this.manifestUrlString,2);this.manifestUrlString=se(this.manifestUrlString,p+1e3,2)}}));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(or(...z$.map(c=>nr(this.element,c))).pipe(ya(c=>this.element?rt(this.element.buffered,this.element.currentTime*1e3):0),Ys(),Q$(c=>{c>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(or(nr(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Ys()).subscribe(p=>{this.isManualDecreasePlaybackInLive()||dl(this.element,1)})),this.representationSubscription.add(Wr({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(va(({bufferLength:p,isActiveLowLatency:m})=>m&&!!p)).subscribe(({bufferLength:p})=>this.liveBuffer.next(p))),this.representationSubscription.add(Wr({isActiveLowLatency:this.isActiveLowLatency$.pipe(Ys()),currentLowLatencySegmentLength:this.videoBufferManager.currentLowLatencySegmentLength$}).pipe(va(({isActiveLowLatency:p,currentLowLatencySegmentLength:m})=>p&&!!m)).subscribe(({currentLowLatencySegmentLength:p})=>{let m=this.liveDuration$.getValue()-p/1e3;this.liveDuration$.next(Math.min(m,this.tuning.dashCmafLive.maxLiveDuration))})),this.representationSubscription.add(Wr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(va(({isLive:p})=>p),ya(p=>({...p})),Ys((p,m)=>m.bufferLength<p.bufferLength),ya(({rtt:p,bufferLength:m,segmentServerLatency:f})=>{let b=Es(this.manifestUrlString,2);return(p/2+m+f+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Wr({liveBuffer:this.liveBuffer.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveBuffer:p,isActiveLowLatency:m})=>{if(!m)return;let f=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,b=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,g=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,v=p-f;if(this.isManualDecreasePlaybackInLive())return;let w=1;Math.abs(v)>b&&(w=1+Math.sign(v)*g),dl(this.element,w)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let m=0;if(p){let f=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let c=0;this.representationSubscription.add(Wr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(W$(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:m})=>{if(sr(this.element),this.isUpdatingLive)return;let f=this.element.playbackRate,b=Es(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),w=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,P=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,L=isFinite(p)?p:m,y=this.isActiveLowLatency$.getValue(),I=g<=this.tuning.live.activeLiveDelay&&b===0;this.isActiveLowLatency$.next(y&&I);let R="none";if(y?R="active_low_latency":this.isLowLatency$.getValue()&&I?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(Q=>Q.proceedLowLatencyLive()),R="active_low_latency"):b!==0&&L<v?R="live_forward_buffering":L<v+P&&(R="live_with_target_offset"),isFinite(p)&&(c=p>c?p:c),R==="live_forward_buffering"||R==="live_with_target_offset"){let Q=c-(v+w),F=this.normolizeLiveOffset(Math.trunc(b+Q/f)),U=Math.abs(F-b),S;!p||U<=this.tuning.dashCmafLive.offsetCalculationError?S=b:F>0&&U>this.tuning.dashCmafLive.offsetCalculationError?S=F:S=0,this.manifestUrlString=se(this.manifestUrlString,S,2)}R!=="none"&&R!=="active_low_latency"&&(c=0,this.updateLive())}))}let l=or(...this.bufferManagers.map(c=>c.fullyBuffered$)).pipe(ya(()=>this.bufferManagers.every(c=>c.fullyBuffered$.getValue()))),d=or(...this.bufferManagers.map(c=>c.onLastSegment$)).pipe(ya(()=>this.bufferManagers.some(c=>c.onLastSegment$.getValue())));if(this.representationSubscription.add(or(this.forceEnded$,Wr({allBuffersFull:l,someBufferEnded:d}).pipe(va(({allBuffersFull:c,someBufferEnded:p})=>c&&p))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(c=>!c.updating))try{this.source?.endOfStream(),this.bufferManagers.forEach(c=>c.warmUpMediaSource())}catch(c){this.error$.next({id:"EndOfStream",category:Vt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:c})}})),this.representationSubscription.add(or(...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"&&(yield new Promise(c=>this.source?.addEventListener("sourceopen",c))),!this.isLive$.getValue()){let c=[this.manifest.duration??0,...(0,ml.default)((0,ml.default)([...this.manifest.streams.audio,...this.manifest.streams.video],p=>p.representations),p=>{let m=[];return p.duration&&m.push(p.duration),de(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&m.push(p.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...c)/1e3}this.audioBufferManager&&rS(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)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=hl(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Vt.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new js({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=ar.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){sr(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=se(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){sr(this.element),this.state$.setState("running"),this.subscription.add(or(...Y$.map(e=>nr(this.element,e)),nr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Vt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(nr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(nr(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Lt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element)return;let t=this.currentStallDuration$.getValue();t+=50,this.currentStallDuration$.next(t);let r={timeInWaiting:t},i=G$(),s=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardBufferDuration()??0,l=this.audioBufferManager?.getForwardBufferDuration()??0,d=u<s&&i-n>this.tuning.dash.crashOnStallTWithoutDataTimeout,c=this.audioBufferManager&&l<s&&i-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||c)&&t>this.tuning.dash.crashOnStallTWithoutDataTimeout||t>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${t} ms`);if(this.isLive$.getValue()&&t%5e3===0)this.seekLive(this.liveLastSeekOffset),r.liveLastSeekOffset=this.liveLastSeekOffset;else{let p=this.element.currentTime*1e3;this.videoBufferManager?.maintain(p),this.audioBufferManager?.maintain(p),r.position=p}this.tracer.log("stallIntervalCallback",Sa(r))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=hl(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:Vt.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?i?.switchToWithPreviousAbort(t,r):i?.switchTo(t,r):i?.switchToOld(t,r)}async seek(e,t){sr(this.element),sr(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),Lt(this.element.buffered,r)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),this.videoBufferManager.maintain(r),this.audioBufferManager?.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",Sa({requestedPosition:e,forcePrecise:t,position:r}))}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.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=j$(this.tracer.error.bind(this.tracer));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.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,i=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?i.push(1/0):i.push(o.to));if(i.length){let n=Math.max(...i)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t={...t,gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Sa(t)))}}};var Ks=class{constructor(e,t){this.fov=e,this.orientation=t}};var Xs=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,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=r??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,r){this.setRotationSpeed(e,t,r),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,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var sS=`attribute vec2 a_vertex;
|
|
70
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var el=V(Or(),1);import{videoSizeToQuality as LL}from"@vkontakte/videoplayer-shared";var BS=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s,streamId:n})=>{let o=(s?At(s):void 0)??LL({width:e,height:t});return o&&{id:i,quality:o,bitrate:r,size:{width:e,height:t},fps:a,streamId:n}},OS=({id:i,bitrate:e})=>({id:i,bitrate:e}),_S=({language:i,label:e},{id:t,url:r,isAuto:a})=>({id:t,url:r,isAuto:a,type:"internal",language:i,label:e}),NS=({language:i,label:e,id:t,url:r,isAuto:a})=>({id:t,url:r,isAuto:a,type:"internal",language:i,label:e}),tl=({id:i,language:e,label:t,codecs:r,isDefault:a})=>({id:i,language:e,label:t,codec:(0,el.default)(r.split("."),0),isDefault:a}),rl=({id:i,language:e,label:t,hdr:r,codecs:a})=>({id:i,language:e,hdr:r,label:t,codec:(0,el.default)(a.split("."),0)}),il=i=>"url"in i,pe=i=>i.type==="template",pa=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var qS=i=>{if(!i?.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),a=r?.[1]==="-"?-1:1,s={days:e(r?.[5],a),hours:e(r?.[6],a),minutes:e(r?.[7],a),seconds:e(r?.[8],a)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},bt=(i,e)=>{let t=i;t=(0,al.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[a,s]of(0,US.default)(r)){let n=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=(0,al.default)(t,n,(o,u)=>FS(s)?o:FS(u)?s:(0,HS.default)(s,parseInt(u,10),"0"))}return t},GS=(i,e)=>{let r=new DOMParser().parseFromString(i,"application/xml"),a={video:[],audio:[],text:[]},s=r.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(y=>y.textContent?.trim()??""),o=(0,jS.default)(n,0)??"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=l?new Date(l).getTime():void 0,d,p=s.getAttribute("mediaPresentationDuration"),f=s.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,b=[...s.getElementsByTagName("Period")],g=b.reduce((y,E)=>({...y,[E.id]:E.children}),{}),S=b.reduce((y,E)=>({...y,[E.id]:E.getAttribute("duration")}),{});p?d=qS(p):(0,sl.default)(S).filter(y=>y).length&&!u?d=(0,sl.default)(S).reduce((y,E)=>y+(qS(E)??0),0):f&&(d=parseInt(f,10));let P=0,v=s.getAttribute("profiles")?.split(",")??[];for(let y of b.map(E=>E.id))for(let E of g[y]){let L=E.getAttribute("id")??"id"+(P++).toString(10),U=E.getAttribute("mimeType")??"",q=E.getAttribute("codecs")??"",H=E.getAttribute("contentType")??U?.split("/")[0],$=E.getAttribute("profiles")?.split(",")??[],k=VS(E.getAttribute("lang")??"")??{},T=E.querySelector("Label")?.textContent?.trim()??void 0,W=E.querySelectorAll("Representation"),fe=E.querySelector("SegmentTemplate"),w=E.querySelector("Role")?.getAttribute("value")??void 0,C=H,B={id:L,language:k.language,isDefault:w==="main",label:T,codecs:q,hdr:C==="video"&&Ju(q),mime:U,representations:[]};for(let A of W){let j=A.getAttribute("lang")??void 0,Be=T??E.getAttribute("label")??A.getAttribute("label")??void 0,st=A.querySelector("BaseURL")?.textContent?.trim()??"",ze=new URL(st||o,e).toString(),O=A.getAttribute("mimeType")??U,ie=A.getAttribute("codecs")??q??"",le;if(H==="text"){let Z=A.getAttribute("id")||"",Ke=k.privateuse?.includes("x-auto")||Z.includes("_auto"),Oe=A.querySelector("SegmentTemplate");if(Oe){let _e={representationId:A.getAttribute("id")??void 0,bandwidth:A.getAttribute("bandwidth")??void 0},nt=parseInt(A.getAttribute("bandwidth")??"",10)/1e3,St=parseInt(Oe.getAttribute("startNumber")??"",10)??1,ot=parseInt(Oe.getAttribute("timescale")??"",10),bn=Oe.querySelectorAll("SegmentTimeline S")??[],cr=Oe.getAttribute("media");if(!cr)continue;let Oa=[],_a=0,Na="",dr=0,Xr=St,ce=0;for(let Ne of bn){let qt=parseInt(Ne.getAttribute("d")??"",10),Le=parseInt(Ne.getAttribute("r")??"",10)||0,vt=parseInt(Ne.getAttribute("t")??"",10);ce=Number.isFinite(vt)?vt:ce;let Ut=qt/ot*1e3,pr=ce/ot*1e3;for(let Xe=0;Xe<Le+1;Xe++){let yt=bt(cr,{..._e,segmentNumber:Xr.toString(10),segmentTime:(ce+Xe*qt).toString(10)}),hr=(pr??0)+Xe*Ut,Zr=hr+Ut;Xr++,Oa.push({time:{from:hr,to:Zr},url:yt})}ce+=(Le+1)*qt,_a+=(Le+1)*Ut}dr=ce/ot*1e3,Na=bt(cr,{..._e,segmentNumber:Xr.toString(10),segmentTime:ce.toString(10)});let Jr={time:{from:dr,to:1/0},url:Na},ut={type:"template",baseUrl:ze,segmentTemplateUrl:cr,initUrl:"",totalSegmentsDurationMs:_a,segments:Oa,nextSegmentBeyondManifest:Jr,timescale:ot};le={id:Z,kind:"text",segmentReference:ut,profiles:[],duration:d,bitrate:nt,mime:"",codecs:"",width:0,height:0,isAuto:Ke}}else le={id:Z,isAuto:Ke,kind:"text",url:ze}}else{let Z=A.getAttribute("contentType")??O?.split("/")[0]??H,Ke=E.getAttribute("profiles")?.split(",")??[],Oe=parseInt(A.getAttribute("width")??"",10),_e=parseInt(A.getAttribute("height")??"",10),nt=parseInt(A.getAttribute("bandwidth")??"",10)/1e3,St=A.getAttribute("frameRate")??"",ot=A.getAttribute("quality")??void 0,bn=St?CS(St):void 0,cr=A.getAttribute("id")??"id"+(P++).toString(10),Oa=Z==="video"?`${_e}p`:Z==="audio"?`${nt}Kbps`:ie,_a=`${cr}@${Oa}`,Na=[...v,...$,...Ke],dr,Xr=A.querySelector("SegmentBase"),ce=A.querySelector("SegmentTemplate")??fe;if(Xr){let ut=A.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ne,qt]=ut.split("-").map(yt=>parseInt(yt,10)),Le={from:Ne,to:qt},vt=A.querySelector("SegmentBase")?.getAttribute("indexRange"),[Ut,pr]=vt?vt.split("-").map(yt=>parseInt(yt,10)):[],Xe=vt?{from:Ut,to:pr}:void 0;dr={type:"byteRange",url:ze,initRange:Le,indexRange:Xe}}else if(ce){let ut={representationId:A.getAttribute("id")??void 0,bandwidth:A.getAttribute("bandwidth")??void 0},Ne=parseInt(ce.getAttribute("timescale")??"",10),qt=ce.getAttribute("initialization")??"",Le=ce.getAttribute("media"),vt=parseInt(ce.getAttribute("startNumber")??"",10)??1,Ut=bt(qt,ut);if(!Le)throw new ReferenceError("No media attribute in SegmentTemplate");let pr=ce.querySelectorAll("SegmentTimeline S")??[],Xe=[],yt=0,hr="",Zr=0;if(pr.length){let Fa=vt,Fe=0;for(let mr of pr){let Je=parseInt(mr.getAttribute("d")??"",10),Ht=parseInt(mr.getAttribute("r")??"",10)||0,qa=parseInt(mr.getAttribute("t")??"",10);Fe=Number.isFinite(qa)?qa:Fe;let gn=Je/Ne*1e3,py=Fe/Ne*1e3;for(let Ua=0;Ua<Ht+1;Ua++){let hy=bt(Le,{...ut,segmentNumber:Fa.toString(10),segmentTime:(Fe+Ua*Je).toString(10)}),Bl=(py??0)+Ua*gn,my=Bl+gn;Fa++,Xe.push({time:{from:Bl,to:my},url:hy})}Fe+=(Ht+1)*Je,yt+=(Ht+1)*gn}Zr=Fe/Ne*1e3,hr=bt(Le,{...ut,segmentNumber:Fa.toString(10),segmentTime:Fe.toString(10)})}else if(ML(d)){let Fe=parseInt(ce.getAttribute("duration")??"",10)/Ne*1e3,mr=Math.ceil(d/Fe),Je=0;for(let Ht=1;Ht<mr;Ht++){let qa=bt(Le,{...ut,segmentNumber:Ht.toString(10),segmentTime:Je.toString(10)});Xe.push({time:{from:Je,to:Je+Fe},url:qa}),Je+=Fe}Zr=Je,hr=bt(Le,{...ut,segmentNumber:mr.toString(10),segmentTime:Je.toString(10)})}let dy={time:{from:Zr,to:1/0},url:hr};dr={type:"template",baseUrl:ze,segmentTemplateUrl:Le,initUrl:Ut,totalSegmentsDurationMs:yt,segments:Xe,nextSegmentBeyondManifest:dy,timescale:Ne}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Z||!O)continue;let Jr={video:"video",audio:"audio",text:"text"}[Z];if(!Jr)continue;C||=Jr,le={id:_a,kind:Jr,segmentReference:dr,profiles:Na,duration:d,bitrate:nt,mime:O,codecs:ie,width:Oe,height:_e,fps:bn,quality:ot}}B.language||=j,B.label||=Be,B.mime||=O,B.codecs||=ie,B.hdr||=C==="video"&&Ju(ie),B.representations.push(le)}if(C){let A=a[C].find(j=>j.id===B.id);if(A&&B.representations.every(j=>pe(j.segmentReference)))for(let j of A.representations){let st=B.representations.find(O=>O.id===j.id)?.segmentReference,ze=j.segmentReference;ze.segments.push(...st.segments),ze.nextSegmentBeyondManifest=st.nextSegmentBeyondManifest}else a[C].push(B)}}return{dynamic:u,liveAvailabilityStartTime:c,duration:d,streams:a,baseUrls:n}};var WS=V(je(),1);import{isNonNullable as QS}from"@vkontakte/videoplayer-shared";var he=(i,e)=>QS(i)&&QS(e)&&i.readyState==="open"&&(0,WS.default)([...i.activeSourceBuffers],e);var ha=class{constructor(e,t,r,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new ar(0);this.currentLowLatencySegmentLength$=new ar(0);this.currentSegmentLength$=new ar(0);this.onLastSegment$=new ar(!1);this.fullyBuffered$=new ar(!1);this.playingRepresentation$=new ar(void 0);this.playingRepresentationInit$=new ar(void 0);this.error$=new VL;this.gaps=[];this.subscription=new BL;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new oe;this.switchAbortController=new oe;this.destroyAbortController=new oe;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=Dt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);xe(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Hg(this.sourceBuffer),this.subscription.add(ol(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Ct.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:Ct.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add(ol(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Ct.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!he(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,ju(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=it(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),a=this.segments.get(t.id),s=this.parsedInitData.get(t.id);xe(r,"No init buffer for starting representation"),xe(a,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(a,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=Dt(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);xe(r,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if(ue(s)||ue(a)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),xe(a,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!he(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();jr(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=Dt(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);xe(r,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if(ue(s)||ue(a)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),xe(a,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!he(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();jr(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=Dt(this.destroyAbortController.signal,async function*(e){let t=(0,js.default)(e,u=>u.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let u of this.representations.keys()){let l=t.find(p=>p.id===u);l&&this.representations.set(u,l);let c=this.representations.get(u);if(!c||!pe(c.segmentReference))return;let d=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,d)}let r=this.switchingToRepresentationId??this.downloadingRepresentationId,a=this.representations.get(r);xe(a);let s=this.segments.get(r);xe(s,"No segments for starting representation");let n=this.initData.get(r);if(xe(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,a),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=a,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!l?.dynamic,this.baseUrls=l?.baseUrls??[],this.initData=new Map(r.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new oe,Dt(this.switchAbortController.signal,async function*(r,a=!1){this.switchingToRepresentationId=r;let s=this.representations.get(r);xe(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if(ue(o)||ue(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),xe(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!he(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),a)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=r,yield this.dropBuffer();else{let u=this.getCurrentPosition();jr(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=r,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!ue(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 oe,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(ue(e)||ue(this.downloadingRepresentationId)||ue(this.playingRepresentationId)||ue(this.sourceBuffer)||!he(this.mediaSource,this.sourceBuffer)||jr(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(xe(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let a=r.find(d=>e>=d.time.from&&e<d.time.to);jr(a)&&isFinite(a.time.from)&&isFinite(a.time.to)&&this.currentSegmentLength$.next(a?.time.to-a.time.from);let s=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=it(this.sourceBuffer.buffered,e),p=a?a.time.to+n:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=a.time.to-e+n&&(s=p)}if(isFinite(this.bufferLimit)&&ju(this.sourceBuffer.buffered)>=this.bufferLimit){let d=it(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<p);return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(r,t.segmentReference.type,s),u.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if((0,Hs.default)(u,a))d="high";else{let p=(0,Gr.default)(u,0);p&&p.time.from-a.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(u,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!u.length&&it(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Gr.default)(r,-1),c=this.getDebugBufferState()?.to??0;!this.isLive&&l&&c&&(this.fullyBuffered$.next(Math.abs(l.time.to-c*1e3)<n),this.onLastSegment$.next(Math.abs(e-l.time.to)<n*2))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let r=0,a=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+a}),r=s.time.to;jr(t.duration)&&t.duration-r>0&&!this.isLive&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,a=[],s=0,n=t.length-1;do a.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[a[0]]:a}getLiveSegmentsToLoadState(e){let t=(0,js.default)(e?.streams[this.kind],a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){let t=(0,js.default)(e?.streams[this.kind],r=>r.representations)??[];if(![...this.segments.values()].every(r=>!r.length))for(let r of t){if(!r||!pe(r.segmentReference))return;let a=r.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,n=this.segments.get(r.id)??[],o=(0,Gr.default)(n,-1)?.time.to??0,u=a?.findIndex(l=>o>=l.time.from+s&&o<=l.time.to+s);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(r.segmentReference);this.segments.set(r.id,l)}else{let l=a.slice(u+1);this.segments.set(r.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;xe(e);let t=this.segments.get(e);if(t?.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let r of this.representations.values()){let a=r.segmentReference;if(!pe(a))return;let s=this.segments.get(r.id)??[],n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*a.timescale/1e3).toString(10),l=bt(a.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);return r?r.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&&Ni&&Ni(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Ni&&Ni(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,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(a=>t>=a.time.from&&t<a.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let a=e.findIndex(({status:d,time:{from:p,to:h}},f)=>{let b=p<=r&&h>=r,g=p>r||b||f===0&&r===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),P=this.preloadOnly&&p<=r+S||h<=r+S;return(d==="none"||d==="partially_ejected"&&g&&P&&this.sourceBuffer&&he(this.mediaSource,this.sourceBuffer)&&!(Lt(this.sourceBuffer.buffered,p)&&Lt(this.sourceBuffer.buffered,h)))&&g&&P});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<s.length&&(n<=l||o<=c);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,r="auto"){pe(t.segmentReference)?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){e.status="downloading";let a={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(a);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Dt(o,async function*(){let c=ul(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=Us(),!c)return;let d=new DataView(c),p=da(t.mime);if(!isFinite(a.segment.time.to)){let b=t.segmentReference.timescale;a.segment.time.to=p.getChunkEndTime(d,b)}u&&a.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=p.getServerLatencyTimestamps(d);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),pa(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())pe(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,r="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:a,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Dt(n,async function*(){let u=ul(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),ol(window,"online").pipe(CL()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:a,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=Us(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),pa(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(pe(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,Gr.default)(e,0).byte.from,to:(0,Gr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:a,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Us(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:a?a.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Ct.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!pe(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let a=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Us();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Ct.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:a,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Hs.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:a,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){a();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=da(n.mime).parseFeedableSegmentChunk(l,this.isLive);c?.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){await n();continue}let c=l.byte.from-r,d=l.byte.to-r,p=d-c+1,h=c<a,f=d<=a;if(!h)continue;let b=da(o.mime);if(l.status==="downloading"&&f){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+c,p);await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,a-c),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===p?g:b.parseFeedableSegmentChunk(g);S?.byteLength&&(l.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){if(!(ue(this.sourceBuffer)||!he(this.mediaSource,this.sourceBuffer))){!this.isLive&&DL.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Lt(this.sourceBuffer.buffered,e.segment.time.from,100)&&Lt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Ct.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",il(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let a of this.segments.get(r.id)??[])a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.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[a,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=qu(()=>(0,YS.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",r=!1){let a=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?Dt(this.destroyAbortController.signal,async function*(){let o=ul(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,da(e.mime),a)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&pe(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:Ct.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,r=!1){if(!this.sourceBuffer||!he(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ue(e))return!1;let a=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:p}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,p):l.push(u[c])}return l},o=u=>{if(s>=t)return a;a.push({...u.time}),a=n(a);let l=il(u)?u.size??0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)(0,Hs.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(a.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return a.length?(await Promise.all(a.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!he(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||!he(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(){let e=this.getCurrentPosition();return!this.sourceBuffer||!he(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ue(e)?0:it(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!he(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(a=>this.sourceBuffer&&(Math.round(a.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(a.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));for(let r of t){let a={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){a=void 0;break}o>r.time.from&&o<r.time.to&&(a.from=o),n<r.time.to&&n>r.time.from&&(a.to=n)}}a&&a.to-a.from>1&&!this.gaps.some(s=>a&&s.from===a.from&&s.to===a.to)&&this.gaps.push(a)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!he(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(a=>this.sourceBuffer&&(Math.round(a.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(a.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=qu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Ct.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(ue(this.sourceBuffer)||!he(this.mediaSource,this.sourceBuffer)||ue(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let a=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:a,to:s})}let t=100;for(let r of this.segments.values())for(let a of r){let{status:s}=a;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(a.time.from),o=Math.ceil(a.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?a.status="partially_ejected":this.gaps.some(c=>c.from===a.time.from||c.to===a.time.to)?a.status="partially_ejected":a.status="none")}}};var ma=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var zS=i=>{let e=i.get("X-Delivery-Type"),t=i.get("X-Reused"),r=e===null?"http1":e??void 0,a=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:r,reused:a}};import{abortable as fa,assertNever as XS,fromEvent as JS,merge as OL,now as ba,Subscription as _L,ValueSubject as ll,flattenObject as Qr}from"@vkontakte/videoplayer-shared";var KS=i=>{let e=new URL(i);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Gs=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:a=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new ll(void 0);this.lastConnectionReused$=new ll(void 0);this.lastRequestFirstBytes$=new ll(void 0);this.abortAllController=new oe;this.subscription=new _L;this.fetchManifest=fa(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=ma(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=KS(r));let a=yield Qe(r,{signal:this.abortAllController.signal}).catch(ga);return a?(t.log("success",Qr({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(a.headers),a.text()):(t.error("error",Qr({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=fa(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:a,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){let l=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{c.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let $=new URL(l,location.href);$.searchParams.append("bytes",`${r.from}-${r.to}`),l=$.toString();break}default:XS(t)}this.requestQuic&&(l=ma(l));let p=this.abortAllController.signal,h;if(n){let $=new oe;if(h=OL(JS(this.abortAllController.signal,"abort"),JS(n,"abort")).subscribe(()=>{try{$.abort()}catch(k){ga(k)}}),this.abortAllController.signal.aborted||n.aborted)try{$.abort()}catch(k){ga(k)}p=$.signal}let f=ba();d.log("startRequest",Qr({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:f}));let b=yield Qe(l,{priority:s,headers:c,signal:p}).catch(ga),g=ba();if(!b)return d.error("error",{message:"No response in request"}),d.end(),h?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(g-f),!b.ok||!b.body){h?.unsubscribe();let $=`Fetch error ${b.status}: ${b.statusText}`;return d.error("error",{message:$}),d.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!a&&!o){h?.unsubscribe();let $=ba(),k={requestStartedAt:f,requestEndedAt:$,duration:$-f};return d.log("endRequest",Qr(k)),d.end(),b.arrayBuffer()}let[S,P]=b.body.tee(),v=S.getReader();o&&this.throughputEstimator?.trackStream(P,u);let R=0,y=new Uint8Array(0),E=!1,L=$=>{h?.unsubscribe(),E=!0,ga($)},U=fa(p,async function*({done:$,value:k}){if(R===0&&this.lastRequestFirstBytes$.next(ba()-f),p.aborted){h?.unsubscribe();return}if(!$&&k){let T=new Uint8Array(y.length+k.length);T.set(y),T.set(k,y.length),y=T,R+=k.byteLength,a?.(new DataView(y.buffer),R),yield v?.read().then(U,L)}}.bind(this));yield v?.read().then(U,L),h?.unsubscribe();let q=ba(),H={failed:E,requestStartedAt:f,requestEndedAt:q,duration:q-f};return E?(d.error("endRequest",Qr(H)),d.end(),null):(d.log("endRequest",Qr(H)),d.end(),y.buffer)}.bind(this));this.fetchByteRangeRepresentation=fa(this.abortAllController.signal,async function*(e,t,r){if(e.type!=="byteRange")return null;let{from:a,to:s}=e.initRange,n=a,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,a),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,a-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=e.indexRange??t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,f.from-n,f.to-f.from+1);else{let S=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=fa(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),a=yield this.fetch(r,{priority:t,measureThroughput:!1});return a?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(a)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=a,this.tracer=r.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:r}=zS(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){let{type:a}=e;switch(a){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,r)??null;case"template":return await this.fetchTemplateRepresentation(e,r)??null;default:XS(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},ga=i=>{if(!pa(i))throw i};var sr=(i,e,t)=>t*e+(1-t)*i,cl=(i,e)=>i.reduce((t,r)=>t+r,0)/e,ZS=(i,e,t,r)=>{let a=0,s=t,n=cl(i,e),o=e<r?e:r;for(let u=0;u<o;u++)i[s]>n?a++:a--,s=(i.length+s-1)%i.length;return Math.abs(a)===o};import{isNullable as NL,ValueSubject as ev}from"@vkontakte/videoplayer-shared";var Vt=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 ev(e.initial),this.debounced$=new ev(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new de(`raw_${t}`),this.smoothedSeries$=new de(`smoothed_${t}`),this.reportedSeries$=new de(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,r++);this.takenMeasures=r,t/=r;let a=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*a,n=this.smoothed-this.params.deviationFactor*a;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)&&(NL(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 Qs=class extends Vt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=sr(this.slow,e,this.params.emaAlphaSlow),this.fast=sr(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Ws=class extends Vt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=cl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=sr(this.emaSmoothed,e,this.params.emaAlpha);let r=ZS(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Ys=class extends Vt{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?sr(this.smoothed,t,this.params.emaAlpha):t}};var nr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new Qs({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new Ws({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new Ys({initial:e,label:"liveEdgeDelay",...t})}};var dl=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};import{isNullable as FL,ValueSubject as qL}from"@vkontakte/videoplayer-shared";var Sa=class i{constructor(e,t){this.currentRepresentation$=new qL(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(!FL(e))for(let t of this.representations)for(let r of t){let a=r.segmentReference,s=a.segments.length,n=a.segments[0].time.from,o=a.segments[s-1].time.to;if(e<n||e>o)continue;let u=a.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,a.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let r=i.filterRepresentations(t.representations);if(r){this.representations[this.representationsCursor]=r,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>i.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&pe(t.segmentReference))}};var YL=["timeupdate","progress","play","seeked","stalled","waiting"],zL=["timeupdate","progress","loadeddata","playing","seeked"];var zs=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new av;this.representationSubscription=new av;this.state$=new M("none");this.currentVideoRepresentation$=new K(void 0);this.currentVideoRepresentationInit$=new K(void 0);this.currentAudioRepresentation$=new K(void 0);this.currentVideoSegmentLength$=new K(0);this.currentAudioSegmentLength$=new K(0);this.error$=new iv;this.lastConnectionType$=new K(void 0);this.lastConnectionReused$=new K(void 0);this.lastRequestFirstBytes$=new K(void 0);this.currentLiveTextRepresentation$=new K(null);this.isLive$=new K(!1);this.liveDuration$=new K(0);this.liveAvailabilityStartTime$=new K(void 0);this.bufferLength$=new K(0);this.liveLatency$=new K(void 0);this.liveLoadBufferLength$=new K(0);this.livePositionFromPlayer$=new K(0);this.isLowLatency$=new K(!1);this.isActiveLowLatency$=new K(!1);this.currentStallDuration$=new K(0);this.videoLastDataObtainedTimestamp$=new K(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.streamEnded=!1;this.liveLastSeekOffset=0;this.forceEnded$=new iv;this.gapWatchdogActive=!1;this.destroyController=new oe;this.initManifest=pl(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ne(t,r,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:Bt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=pl(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Bt.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=GS(e??"",this.manifestUrlString)}catch(n){let o=Og(e)??{id:"ManifestParsing",category:Bt.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(o)}if(!t)return null;let r=(n,o,u)=>!!(this.element?.canPlayType?.(o)&&mt()?.isTypeSupported?.(`${o}; codecs="${u}"`)||n==="text");if(t.dynamic){this.isLive$.next(t.dynamic),this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime);let n=(t.duration??0)/1e3;this.liveDuration$.next(-1*n)}let a={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let u=t.streams[n].filter(({mime:d,codecs:p})=>r(n,d,p)),l=new Set(u.map(({codecs:d})=>d)),c=fg(l);if(c&&(a[n]=u.filter(({codecs:d})=>d.startsWith(c))),n==="video"){let d=this.tuning.preferHDR,p=a.video.some(f=>f.hdr),h=a.video.some(f=>!f.hdr);jL.isHDR&&d&&p?a.video=a.video.filter(f=>f.hdr):h&&(a.video=a.video.filter(f=>!f.hdr))}}let s={...t,streams:a};return this.tracer.log("updateManifestEnd",Ta(s)),s}.bind(this));this.initRepresentations=pl(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initRepresentationsStart",Ta({initialVideo:e,initialAudio:t,sourceHls:r})),or(this.manifest),or(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=p=>{this.representationSubscription.add(Ot(p,"error").pipe(va(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:Bt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?ug():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Bs())if(r){let p=document.createElement("source");a(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.isLowLatency$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new ha("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],rv(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new ha("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Sa.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Sa(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(hl(1e3).subscribe(p=>{if(this.element?.paused){let h=xs(this.manifestUrlString,2);this.manifestUrlString=ne(this.manifestUrlString,h+1e3,2)}}));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(ur(...zL.map(p=>Ot(this.element,p))).pipe(Yr(p=>this.element?it(this.element.buffered,this.element.currentTime*1e3):0),ya(),sv(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(ur(Ot(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(ya()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||dl(this.element,1)})),this.representationSubscription.add(Wr({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(va(({bufferLength:h,isActiveLowLatency:f})=>f&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(Wr({isActiveLowLatency:this.isActiveLowLatency$.pipe(ya()),currentLowLatencySegmentLength:this.videoBufferManager.currentLowLatencySegmentLength$}).pipe(va(({isActiveLowLatency:h,currentLowLatencySegmentLength:f})=>h&&!!f)).subscribe(({currentLowLatencySegmentLength:h})=>{let f=this.liveDuration$.getValue()-h/1e3;this.liveDuration$.next(Math.min(f,this.tuning.dashCmafLive.maxLiveDuration))})),this.representationSubscription.add(Wr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(va(({isLive:h})=>h),Yr(h=>({...h})),ya((h,f)=>f.bufferLength<h.bufferLength),Yr(({rtt:h,bufferLength:f,segmentServerLatency:b})=>{let g=xs(this.manifestUrlString,2);return(h/2+f+b+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Wr({liveBuffer:this.liveBuffer.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveBuffer:h,isActiveLowLatency:f})=>{if(!f)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,P=h-b;if(this.isManualDecreasePlaybackInLive())return;let v=1;Math.abs(P)>g&&(v=1+Math.sign(P)*S),dl(this.element,v)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let f=0;if(h){let b=(this.element?.currentTime??0)*1e3;f=Math.min(...this.bufferManagers.map(S=>S.getLiveSegmentsToLoadState(this.manifest)?.to??b))-b}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add(Wr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(WL(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(or(this.element),this.isUpdatingLive)return;let b=this.element.playbackRate,g=xs(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,P=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),v=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,R=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,y=isFinite(h)?h:f,E=this.isActiveLowLatency$.getValue(),L=S<=this.tuning.live.activeLiveDelay&&g===0;this.isActiveLowLatency$.next(E&&L);let U="none";if(E?U="active_low_latency":this.isLowLatency$.getValue()&&L?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(q=>q.proceedLowLatencyLive()),U="active_low_latency"):g!==0&&y<P?U="live_forward_buffering":y<P+R&&(U="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),U==="live_forward_buffering"||U==="live_with_target_offset"){let q=p-(P+v),H=this.normolizeLiveOffset(Math.trunc(g+q/b)),$=Math.abs(H-g),k;!h||$<=this.tuning.dashCmafLive.offsetCalculationError?k=g:H>0&&$>this.tuning.dashCmafLive.offsetCalculationError?k=H:k=0,this.manifestUrlString=ne(this.manifestUrlString,k,2)}U!=="none"&&U!=="active_low_latency"&&(p=0,this.updateLive())}))}let l=ur(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Yr(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=ur(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Yr(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=Wr({allBuffersFull:l,someBufferEnded:c}).pipe(ya(),Yr(({allBuffersFull:p,someBufferEnded:h})=>p&&h),sv(p=>this.streamEnded=p),va(p=>p));if(this.representationSubscription.add(Ot(this.source,"sourceended").subscribe(p=>{this.bufferManagers.forEach(h=>h.warmUpMediaSource())})),this.representationSubscription.add(ur(this.forceEnded$,d).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(p=>!p.updating))try{this.source?.endOfStream()}catch(p){this.error$.next({id:"EndOfStream",category:Bt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:p})}})),this.representationSubscription.add(ur(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>this.source?.addEventListener("sourceopen",p))),!this.isLive$.getValue()){let p=[this.manifest.duration??0,...(0,ml.default)((0,ml.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),pe(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&rv(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)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=hl(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Bt.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Gs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=nr.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){or(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=ne(this.manifestUrlString,t,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(){or(this.element),this.state$.setState("running"),this.subscription.add(ur(...YL.map(e=>Ot(this.element,e)),Ot(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Bt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Ot(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Ot(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Lt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element||this.streamEnded)return;let t=this.currentStallDuration$.getValue();t+=50,this.currentStallDuration$.next(t);let r={timeInWaiting:t},a=QL(),s=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardBufferDuration()??0,l=this.audioBufferManager?.getForwardBufferDuration()??0,c=u<s&&a-n>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&l<s&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||d)&&t>this.tuning.dash.crashOnStallTWithoutDataTimeout||t>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${t} ms`);if(this.isLive$.getValue()&&t%5e3===0)this.seekLive(this.liveLastSeekOffset),r.liveLastSeekOffset=this.liveLastSeekOffset;else{let p=this.element.currentTime*1e3;this.videoBufferManager?.maintain(p),this.audioBufferManager?.maintain(p),r.position=p}this.tracer.log("stallIntervalCallback",Ta(r))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=hl(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:Bt.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){let a={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?a?.switchToWithPreviousAbort(t,r):a?.switchTo(t,r):a?.switchToOld(t,r)}async seek(e,t){or(this.element),or(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),Lt(this.element.buffered,r)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),this.videoBufferManager.maintain(r),this.audioBufferManager?.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",Ta({requestedPosition:e,forcePrecise:t,position:r}))}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.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=GL(this.tracer.error.bind(this.tracer));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.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,a=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?a.push(1/0):a.push(o.to));if(a.length){let n=Math.max(...a)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t={...t,gapEnds:a,jumpTo:n,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Ta(t)))}}};var Ks=class{constructor(e,t){this.fov=e,this.orientation=t}};var Xs=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,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let a=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:a,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=r??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,r){this.setRotationSpeed(e,t,r),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,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let a=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*a,this.fadeStartSpeed.y*a,this.fadeStartSpeed.z*a),a>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var nv=`attribute vec2 a_vertex;
|
|
71
71
|
attribute vec2 a_texel;
|
|
72
72
|
|
|
73
73
|
varying vec2 v_texel;
|
|
@@ -78,7 +78,7 @@ void main(void) {
|
|
|
78
78
|
// save texel vector to pass to fragment shader
|
|
79
79
|
v_texel = a_texel;
|
|
80
80
|
}
|
|
81
|
-
`;var
|
|
81
|
+
`;var ov=`#ifdef GL_ES
|
|
82
82
|
precision highp float;
|
|
83
83
|
precision highp int;
|
|
84
84
|
#else
|
|
@@ -121,6 +121,6 @@ void main(void) {
|
|
|
121
121
|
// sample using new coordinates
|
|
122
122
|
gl_FragColor = texture2D(u_texture, tc);
|
|
123
123
|
}
|
|
124
|
-
`;var Js=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let i=this.canvas.getContext("webgl");if(!i)throw new Error("Could not initialize WebGL context");this.gl=i,this.container.appendChild(this.canvas),this.camera=new Ks(this.params.fov,this.params.orientation),this.cameraRotationManager=new Xs(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"),r=this.gl.getAttribLocation(this.program,"a_texel"),i=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),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(r,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(i,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(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(sS,this.gl.VERTEX_SHADER),r=this.createShader(nS,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),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,r=1,i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:r=i/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),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,r=this.camera.fov.x/360/2,i=this.camera.fov.y/180/2,s=e-r,n=t-i,o=e+r,u=t-i,l=e+r,d=t+i,c=e-r,p=t+i;return[s,n,o,u,l,d,c,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as J$,now as oS,Subscription as Z$,filter as eM,combine as uS,ValueSubject as fl,isNonNullable as tM}from"@vkontakte/videoplayer-shared";var bl=class{constructor(){this.isSeeked$=new fl(!1);this.isBuffering$=new fl(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new Z$;this.severeStallOccurred$=new fl(!1)}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(uS({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(eM(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(uS({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{if(J$(this.lastUniqueVideoTrackSelected))return;let{stallDurationNoDataBeforeQualityDecrease:r,stallCountBeforeQualityDecrease:i,resetQualityRestrictionTimeout:s}=this.qualityLimitsOnStall,n=this.rtt$.getValue(),o=this.throughput$.getValue(),u=this.videoLastDataObtainedTimestamp$.getValue(),l=oS(),d=i&&this.currentStallsCount>=i,c=r&&l-this.lastUniqueVideoTrackSelectedTimestamp>=r+n&&l-u>=r+n&&t>=r;(d||c)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,tM(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}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()}},lS=bl;import{combine as rM,map as iM,observeElementSize as aM,Subscription as sM,ValueSubject as gl,noop as nM}from"@vkontakte/videoplayer-shared";var Zs=class{constructor(){this.subscription=new sM;this.pipSize$=new gl(void 0);this.videoSize$=new gl(void 0);this.elementSize$=new gl(void 0);this.pictureInPictureWindowRemoveEventListener=nM}connect({observableVideo:e,video:t}){let r=i=>{let s=i.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(aM(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:i})=>{this.pipSize$.next({width:i.width,height:i.height}),i.addEventListener("resize",r),this.pictureInPictureWindowRemoveEventListener=()=>{i.removeEventListener("resize",r)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(rM({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(iM(({videoSize:i,inPip:s,pipSize:n})=>s?n:i)).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 ur=class{constructor(e){this.subscription=new hM;this.videoState=new $("stopped");this.droppedFramesManager=new $s;this.stallsManager=new lS;this.elementSizeManager=new Zs;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new wi;this.audioTrackSwitchHistory=new wi;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.state==="requested"&&r?.to!=="paused"&&e!=="stopped"&&t!=="stopped"){let n=this.liveOffset?.getTotalPausedTime()??0;this.seek(i.position-n,i.forcePrecise)}if(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"),T(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"),T(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="ready"&&T(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset?.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):r?.to==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return lM(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Js(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 Me(e.source.url),this.params=e,this.video=fe(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(ee(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 zs({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=ve(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:vl.WTF,message:`${i} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(cS(d=>!!d.length),pS()).subscribe(d=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:d})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(Sl(d=>d.to.state!=="none"),Ia());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(Ia()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:r.isBuffering$}),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.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(cS(dS),pS()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(Sl(d=>d.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(et(this.video,t.isLooped,i)),this.subscription.add(ge(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add($e(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(Ce(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),T(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if(cM(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let f of c.audio){m.push(tl(f));let b=[];for(let g of f.representations){let v=Ov(g);b.push(v),this.audioTracksMap.set(v,{stream:f,representation:g})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(m)}let p=[];for(let m of c.video){p.push(rl(m));let f=[];for(let b of m.representations){let g=Bv({...b,streamId:m.id});g&&(f.push(g),this.videoTracksMap.set(g,{stream:m,representation:b}))}this.videoStreamsMap.set(m,f)}this.params.output.availableVideoStreams$.next(p);for(let m of c.text)for(let f of m.representations){let b=_v(m,f);this.textTracksMap.set(b,{stream:m,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),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let o=d=>e.error$.next({id:"RepresentationSwitch",category:vl.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(en(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,pM(this.video,"progress")).subscribe(()=>{let d=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,hS.default)(["manifest_ready","running"],d)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[m,f]=p,b=[...this.videoTracksMap.keys()].find(v=>this.videoTracksMap.get(v)?.representation.id===m.id);dS(b)&&(this.stallsManager.lastVideoTrackSelected=b);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),d==="manifest_ready")this.player.initRepresentations(m.id,f?.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",m.id).catch(o),f){let v=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",f.id,v).catch(o)}},i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSizeManager.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Ia()).subscribe(d=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===d);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:m}]=c,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(rl(m))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Ia()).subscribe(d=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===d);if(!c){e.currentAudioStream$.next(void 0);return}let[p,{stream:m}]=c,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(tl(m))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{if(d?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(c){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${c}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),this.textTracksManager.connect(this.video,t,e);let u=t.playbackState.stateChangeStarted$.pipe(Sl(({to:d})=>d==="ready"),Ia());this.subscription.add(en(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,yl(["init"])).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(en(u,this.player.state$.stateChangeEnded$,yl(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=en(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,yl(["init"])).pipe(dM(0));this.subscription.add(l.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=e.videoTrack.getState()?.id,n=[...this.videoTracksMap.keys()].find(({id:R})=>R===i),o=t.currentVideoTrack$.getValue(),u=e.videoStream.getState()??(n&&this.videoTracksMap.get(n)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:R})=>R===u.id),d=l&&this.videoStreamsMap.get(l);if(!d)return;let c=rt(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,f=Math.min(c/Math.min(p,m||1/0),1),b=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),g=[...this.audioStreamsMap.keys()].find(({id:R})=>R===b?.id)??this.audioStreamsMap.keys().next().value,v=0;if(g){if(n&&!r){let R=ks(n,d,this.audioStreamsMap.get(g)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,R?.bitrate??-1/0)}if(o){let R=ks(o,d,this.audioStreamsMap.get(g)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,R?.bitrate??-1/0)}}let w=Rt(d,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:f,current:o,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}),P=r?w??n:n??w,L=g&&Pb(P,d,this.audioStreamsMap.get(g)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:f,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),y=this.videoTracksMap.get(P)?.representation,I=L&&this.audioTracksMap.get(L)?.representation;if(y&&I)return[y,I];if(y&&!I&&this.audioTracksMap.size===0)return[y,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Se(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:vl.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),be(this.video),this.tracer.end()}};var Ea=class extends ur{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as mS,interval as mM,map as fS}from"@vkontakte/videoplayer-shared";var xa=class extends ur{constructor(e){super(e),this.liveOffset=new dt,this.textTracksManager.destroy()}subscribe(){super.subscribe();let{output:e,observableVideo:t,desiredState:r,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),i(this.player.liveLatency$,e.liveLatency$),this.subscription.add(r.isLowLatency.stateChangeEnded$.pipe(fS(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(mS({interval:mM(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{if(this.videoState.getState()==="playing"){let n=e.position$.getValue()+(s-1);n<=0&&e.position$.next(n),this.liveOffset?.resetTo(-n*1e3)}})).add(mS({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(fS(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=Nv(s);this.params.output.availableTextTracks$.next([n])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(n,i)})}};var gS=D(Is(),1);import{assertNever as Pa,assertNonNullable as bS,debounce as fM,ErrorCategory as tn,filter as bM,isNonNullable as gM,isNullable as vM,map as rn,merge as SM,Observable as yM,observableFrom as TM,Subscription as IM,videoSizeToQuality as EM}from"@vkontakte/videoplayer-shared";var We={};var Yr=(a,e)=>new yM(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),wa=class{constructor(e){this.subscription=new IM;this.videoState=new $("initializing");this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!=="initializing")switch(r?.to!=="paused"&&i.state==="requested"&&this.seek(i.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:Pa(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Pa(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Pa(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Pa(e)}break;default:Pa(t)}};this.textTracksManager=new Me(e.source.url),this.video=fe(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),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(ee(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),be(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:tn.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,gS.default)(import("hls.js").then(i=>{e||(We.Hls=i.default,We.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){bS(We.Hls,"hls.js not loaded"),this.hls=new We.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){bS(We.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:tn.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=ve(this.video),s=(l,d)=>this.subscription.add(l.subscribe(d,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(et(this.video,e.isLooped,r)),this.subscription.add(ge(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add($e(this.video,e.playbackRate,i.playbackRateState$,r)),s(Ce(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(rn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Yr(this.hls,We.Events.ERROR).subscribe(l=>{l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:tn.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${l.err?.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),T(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),T(e.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(Yr(this.hls,We.Events.MANIFEST_PARSED).pipe(rn(({levels:l})=>l.reduce((d,c)=>{let p=c.name||c.height.toString(10),{width:m,height:f}=c,b=kt(c.attrs.QUALITY??"")??EM({width:m,height:f});if(!b)return d;let g=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:b,bitrate:c.bitrate/1e3,size:{width:m,height:f},fps:g};return this.trackLevels.set(p,{track:v,level:c}),d.push(v),d},[]))),t.availableVideoTracks$),s(Yr(this.hls,We.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let d=[];for(let c of l.subtitleTracks){let p=c.name,m=c.attrs.URI||"",f=c.lang;d.push({id:p,url:m,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(d)}}),s(Yr(this.hls,We.Events.LEVEL_LOADING).pipe(rn(({url:l})=>ee(l))),t.hostname$),s(Yr(this.hls,We.Events.FRAG_CHANGED),l=>{let{video:d,audio:c}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??0))*1e3)}),this.subscription.add(xt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>Array.from(this.trackLevels.values()).find(({level:d})=>d===l)?.track,o=Yr(this.hls,We.Events.LEVEL_SWITCHED).pipe(rn(({level:l})=>n(this.hls.levels[l])));o.pipe(bM(gM)).subscribe(t.currentVideoTrack$,r),this.subscription.add(xt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{if(vM(l))return;let d=this.trackLevels.get(l.id)?.level;if(!d)return;let c=this.hls.levels.indexOf(d),p=this.hls.currentLevel,m=this.hls.levels[p];!m||d.bitrate>m.bitrate?this.hls.nextLevel=c:(this.hls.loadLevel=c,this.hls.loadLevel=c)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=SM(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,TM(["init"])).pipe(fM(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await Se(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:tn.DOM,thrown:t}))||(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){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.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),T(this.params.desiredState.playbackState,"stopped",!0)}};var vS="X-Playback-Duration",Tl=async a=>{let e=await Ge(a),t=await e.text(),r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return r?parseInt(r,10):e.headers.has(vS)?parseInt(e.headers.get(vS),10):void 0};import{assertNever as CM,combine as VM,debounce as BM,ErrorCategory as nn,filter as OM,filterChanged as _M,isNonNullable as TS,isNullable as on,map as IS,merge as NM,observableFrom as FM,Subscription as qM,ValueSubject as xl,VideoQuality as UM}from"@vkontakte/videoplayer-shared";var El=D(wo(),1);import{videoSizeToQuality as xM,getExponentialDelay as PM}from"@vkontakte/videoplayer-shared";var wM=a=>{let e=null;if(a.QUALITY&&(e=kt(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=xM({width:t,height:r})}return e??null},kM=(a,e)=>{let t=a.split(`
|
|
125
|
-
`),r=[],
|
|
126
|
-
`),s=0;for(let n=0;n<i.length;++n){let o=i[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=i[++n],l=new URL(u,t).toString(),d=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(r.segments.push({time:{from:s,to:s+d},url:l}),s=s+d,!r.segmentStartTime){let c=new Date(r.vkStartTime).valueOf(),p=new Date(r.programDateTime).valueOf();r.segmentStartTime=p-c}break}case o.startsWith("#EXT-X-TARGETDURATION:"):r.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):r.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):r.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);r.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):r.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return r}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(RM(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:r}=t[0].time,{to:i}=t[t.length-1].time;if(e<r||e>i)return;i-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 ne;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:DM.WTF,thrown:t,message:e})}};var ka=class{constructor(e){this.subscription=new qM;this.videoState=new $("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new xl([]);this.liveOffset=new dt;this.manifestStartTime$=new xl(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="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"),T(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(i?.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":r==="ready"?T(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),T(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="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 i?.to==="paused"&&(T(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return CM(t)}};this.params=e,this.video=fe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:UM.INVARIANT,url:this.params.source.url};let t=(r,i)=>an(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},i);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new sn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Me(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:i})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:nn.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(i,this.params.source.url),this.manifests$.next([this.masterManifest,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:nn.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ee(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new xl(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=i?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:nn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=ve(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.ended$,e.endedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(ge(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add($e(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ce(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(i.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),T(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(_M(),IS(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(i.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&TS(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(m=>m.id===c);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(ee(p.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(i.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(VM({startTime:this.manifestStartTime$.pipe(OM(TS)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(IS(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,r));let n=NM(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,FM(["init"])).pipe(BM(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),be(this.video)}prepare(){let e=this.selectManifest();if(on(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=t?.to??r??{};for(let[l,d]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));d&&l&&i.searchParams.set(d,c)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=se(i.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(n),this.video.setAttribute("src",n),this.video.load(),Tl(n).then(o=>{if(!on(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(on(u)||!isFinite(u))&&Ge(n).then(l=>l.text()).then(l=>{let d=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(d){let c=new URL(d,n).toString();Tl(c).then(p=>{on(p)||this.maxSeekBackTime$.next(p)})}}).catch(()=>{})}})}playIfAllowed(){Se(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:nn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/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 HM,debounce as jM,ErrorCategory as Pl,fromEvent as wl,isNonNullable as GM,isNullable as QM,map as ES,merge as xS,observableFrom as PS,Subscription as WM,ValueSubject as YM,VideoQuality as zM,clientChecker as KM}from"@vkontakte/videoplayer-shared";var Aa=class{constructor(e){this.subscription=new WM;this.videoState=new $("stopped");this.manifests$=new YM([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="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"),T(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?T(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&T(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return HM(t)}};this.textTracksManager=new Me(e.source.url),this.params=e,this.video=fe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:zM.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(ee(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),an(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:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Pl.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=i?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:Pl.WTF,message:"HlsProvider internal logic error",thrown:o})},i=ve(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),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.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(ES(o=>o.to)),this.params.output.playbackState$),this.subscription.add(et(this.video,t.isLooped,r)),this.subscription.add(ge(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add($e(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),T(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(i.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&GM(l.to)){let m=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(b=>b.id===m);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ee(f.url)))}let c=this.params.desiredState.playbackRate.getState(),p=this.params.output.element$.getValue()?.playbackRate;if(c!==p){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(c),m.playbackRate=c)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(ES(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,r)),!KM.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(xS(wl(o,"addtrack"),wl(o,"removetrack"),wl(o,"change"),PS(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=xS(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,PS(["init"])).pipe(jM(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),be(this.video)}prepare(){let e=this.selectManifest();if(QM(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:s,min:n}=t?.to??r??{};for(let[o,u]of[[s,"mq"],[n,"lq"]]){let l=String(parseFloat(o||""));u&&o&&i.searchParams.set(u,l)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){Se(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Pl.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var RS=D(xr(),1),Ra=D(Vr(),1);import{assertNever as XM,assertNonNullable as wS,debounce as JM,ErrorCategory as kS,isHigher as ZM,isHigherOrEqual as eD,isInvariantQuality as AS,isLowerOrEqual as tD,isNonNullable as rD,merge as iD,observableFrom as aD,Subscription as sD,map as nD}from"@vkontakte/videoplayer-shared";var La=class{constructor(e){this.subscription=new sD;this.videoState=new $("stopped");this.trackUrls={};this.textTracksManager=new Me;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=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"),T(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0}),n.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[n.to.id]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(r?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?T(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),T(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()):r?.to==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return XM(e)}};this.params=e,this.video=fe(e.container,e.tuning),this.params.output.element$.next(this.video),(0,RS.default)(this.params.source).reverse().forEach(([t,r],i)=>{let s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Ra.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,r=o=>{e.error$.next({id:"MpegProvider",category:kS.WTF,message:"MpegProvider internal logic error",thrown:o})},i=ve(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),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.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(nD(o=>o.to)),this.params.output.playbackState$),this.subscription.add(et(this.video,t.isLooped,r)),this.subscription.add(ge(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add($e(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ce(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),T(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&rD(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let u=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(u!==l){let d=this.params.output.element$.getValue();d&&(this.params.desiredState.playbackRate.setState(u),d.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=iD(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,aD(["init"])).pipe(JM(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),be(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;wS(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];wS(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ha(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ee(t))}playIfAllowed(){Se(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:kS.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){let t,r=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){let i=(0,Ra.default)(this.trackUrls).find(o=>!AS(o.track.quality)&&tD(o.track.quality,e))?.track,s=this.params.desiredState.videoTrack.getState()?.id,n=this.trackUrls[s??"0"]?.track;if(i&&n&&eD(n.quality,i.quality)&&(t=i),!t){let o=(0,Ra.default)(this.trackUrls).filter(l=>!AS(l.track.quality)&&ZM(l.track.quality,e)),u=o.length;u&&(t=o[u-1].track)}t&&(r=t.quality)}else if(!e){let i=(0,Ra.default)(this.trackUrls).map(s=>s.track);t=Rt(i,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};import{assertNever as $S,debounce as cD,merge as MS,observableFrom as dD,Subscription as pD,map as DS,ValueSubject as hD,ErrorCategory as Al,VideoQuality as mD}from"@vkontakte/videoplayer-shared";import{ErrorCategory as oD}from"@vkontakte/videoplayer-shared";var LS=["stun:videostun.mycdn.me:80"],uD=1e3,lD=3,kl=()=>null,un=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=kl;this.externalStopCallback=kl;this.externalErrorCallback=kl;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.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:LS}]};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:oD.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),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))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),uD)}normalizeOptions(e={}){let t={stunServerList:LS,maxRetryNumber:lD,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var $a=class{constructor(e){this.videoState=new $("stopped");this.maxSeekBackTime$=new hD(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=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"),T(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"),T(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()):r?.to==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return $S(e)}};this.subscription=new pD,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=fe(e.container,e.tuning),this.liveStreamClient=new un(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),be(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Al.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};MS(this.videoState.stateChangeStarted$.pipe(DS(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(DS(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=ve(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(i.timeUpdate$,e.liveTime$),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(Ce(this.video),this.params.output.elementVisible$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(i.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(ge(this.video,t.volume,i.volumeState$,r)).add(i.volumeState$.subscribe(e.volume$,r)).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 $S(n.to)}},r)).add(MS(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,dD(["init"])).pipe(cD(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}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(ee(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:mD.INVARIANT}),this.video.srcObject=e,T(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:Al.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Se(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Al.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ma=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as Da,assertNonNullable as Bt,ErrorCategory as ln,filter as NS,isNonNullable as FS,isNullable as ID,map as ED,merge as xD,once as PD,Subject as Ee,Subscription as qS,ValueSubject as M,flattenObject as US}from"@vkontakte/videoplayer-shared";import{Observable as fD,map as CS,Subscription as bD,Subject as gD}from"@vkontakte/videoplayer-shared";var VS=a=>new fD(e=>{let t=new bD,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(CS(({from:l,to:d})=>`${l}-${d}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(CS(({type:l})=>l!==void 0)),n=new gD,o=0,u="unknown";return t.add(r.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(i.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as vD,Subscription as SD,combine as yD,filter as OS,once as _S}from"@vkontakte/videoplayer-shared";function BS(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as TD}from"@vkontakte/videoplayer-shared";var zr=class a{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new ne;this.subscriptions=new SD;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(OS(s=>!!s.type),_S()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){TD.isSafari&&e!=="MPEG"||this.subscriptions.add(yD({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(OS(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),_S()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(r=>{r||this.destroy()}).catch(r=>{this.handleError(r),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,r=BS();this.audioContext=r;let i=r.createGain();if(this.gainNode=i,i.gain.value=t,i.connect(r.destination),r.state==="suspended"&&(await r.resume(),this.destroyController.signal.aborted))return!1;let s=r.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(i),!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:vD.VIDEO_PIPELINE,message:e?.message??`${a.errorId} exception`,thrown:e})}};var wD={chunkDuration:5e3,maxParallelRequests:5},Ca=class{constructor(e){this.current$=new M({type:void 0});this.providerError$=new Ee;this.noAvailableProvidersError$=new Ee;this.volumeMultiplierError$=new Ee;this.providerOutput={position$:new M(0),duration$:new M(1/0),volume$:new M({muted:!1,volume:1}),availableVideoStreams$:new M([]),currentVideoStream$:new M(void 0),availableVideoTracks$:new M([]),currentVideoTrack$:new M(void 0),availableAudioStreams$:new M([]),currentAudioStream$:new M(void 0),availableAudioTracks$:new M([]),currentVideoSegmentLength$:new M(0),currentAudioSegmentLength$:new M(0),isAudioAvailable$:new M(!0),autoVideoTrackLimitingAvailable$:new M(!1),autoVideoTrackLimits$:new M(void 0),currentBuffer$:new M(void 0),isBuffering$:new M(!0),error$:new Ee,warning$:new Ee,willSeekEvent$:new Ee,soundProhibitedEvent$:new Ee,seekedEvent$:new Ee,loopedEvent$:new Ee,endedEvent$:new Ee,firstBytesEvent$:new Ee,loadedMetadataEvent$:new Ee,firstFrameEvent$:new Ee,canplay$:new Ee,isLive$:new M(void 0),isLowLatency$:new M(!1),canChangePlaybackSpeed$:new M(!0),liveTime$:new M(void 0),liveBufferTime$:new M(void 0),liveLatency$:new M(void 0),availableTextTracks$:new M([]),currentTextTrack$:new M(void 0),hostname$:new M(void 0),httpConnectionType$:new M(void 0),httpConnectionReused$:new M(void 0),inPiP$:new M(!1),inFullscreen$:new M(!1),element$:new M(void 0),elementVisible$:new M(!0),availableSources$:new M(void 0),is3DVideo$:new M(!1),playbackState$:new M(""),getCurrentTime$:new M(null)};this.subscription=new qS;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=pg([...mg(this.params.tuning),...hg(this.params.tuning)],this.params.tuning).filter(l=>FS(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,Rl.default)(i,l)),...t.filter(l=>(0,Rl.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",US(s)),this.screenFormatsIterator=new Ma(s);let n=[...Bu(!0),...Bu(!1)];this.chromecastFormatsIterator=new Ma(n.filter(l=>FS(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&zr.isSupported()&&(this.volumeMultiplierManager=new zr(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(ID(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:ln.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();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 Da(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Bt(o),new Ea({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Bt(o),new xa({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Bt(o),qr||!this.params.tuning.useHlsJs?new Aa({...n,source:o}):new wa({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Bt(o),new ka({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Bt(o),new La({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Bt(o),new Fb({...n,source:o,config:{...wD,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Bt(o),new $a({container:r,source:o,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Da(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Bt(o),new Ii({connection:o,meta:s,container:r,source:t,format:e,desiredState:i,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 Da(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Da(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 Da(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);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:r(e.url)}}return(0,jS.default)((0,HS.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new qS,t=!1,r=0;return e.add(xD(this.providerOutput.error$.pipe(NS(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),VS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(ED(i=>({id:`ProviderHangup:${i}`,category:ln.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let i=this.params.desiredState.playbackState.transitionEnded$.pipe(NS(({to:s})=>s==="playing"),PD()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination,n={error:i,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=i.category===ln.NETWORK,u=i.category===ln.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=r<this.params.tuning.providerErrorLimit&&!u,c=l&&!u&&(o&&t||!d);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:c,canReinitProvider:d},d?(r++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s??"SCREEN")}this.tracer.error("providerError",US(n))})),e}};import{fromEvent as cn,once as kD,combine as AD,Subscription as GS,ValueSubject as Ll,map as RD,filter as LD,isNonNullable as dn,now as Re,safeStorage as $l}from"@vkontakte/videoplayer-shared";var $D=5e3,QS="one_video_throughput",WS="one_video_rtt",Va=window.navigator.connection,YS=()=>{let a=Va?.downlink;if(dn(a)&&a!==10)return a*1e3},zS=()=>{let a=Va?.rtt;if(dn(a)&&a!==3e3)return a},KS=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},Ml=class a{constructor(e){this.subscription=new GS;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=a.load(QS)||(e.useBrowserEstimation?YS():void 0)||$D,r=a.load(WS)??(e.useBrowserEstimation?zS():void 0)??0;if(this.throughput$=new Ll(t),this.rtt$=new Ll(r),this.rttAdjustedThroughput$=new Ll(KS(t,r,e.rttPenaltyRequestSize)),this.throughput=ar.getSmoothedValue(t,-1,e),this.rtt=ar.getSmoothedValue(r,1,e),e.useBrowserEstimation){let i=()=>{let n=YS();n&&this.throughput.next(n);let o=zS();dn(o)&&this.rtt.next(o)};Va&&"onchange"in Va&&this.subscription.add(cn(Va,"change").subscribe(i)),i()}this.subscription.add(this.throughput.smoothed$.subscribe(i=>{$l.set(QS,i.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(i=>{$l.set(WS,i.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(AD({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(RD(({throughput:i,rtt:s})=>KS(i,s,e.rttPenaltyRequestSize)),LD(i=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(i-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=Re(),i=new GS;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(cn(e,"progress").pipe(kD()).subscribe(s=>{t=s.loaded,r=Re()}));break;case 1:case 0:i.add(cn(e,"loadstart").subscribe(()=>{t=0,r=Re()}));break}i.add(cn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Re(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=Re(),n=0,o=Re(),u=d=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=async({done:d,value:c})=>{if(d)!t&&this.addRawSpeed(i,Re()-s,1),this.concurrentDownloads.delete(e);else if(c){if(t){let p=Re();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=c.byteLength,s=Re()}else n+=c.byteLength;o=Re()}else i+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Re()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Re()-o,this.concurrentDownloads.size),n=0,o=Re());await r?.read().then(l,u)}};this.concurrentDownloads.add(e),r?.read().then(l,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){let t=$l.get(e);if(dn(t))return parseInt(t,10)??void 0}},XS=Ml;import{fillWithDefault as MD,VideoQuality as JS}from"@vkontakte/videoplayer-shared";var ZS={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:{bitrateFactorAtEmptyBuffer:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:JS.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:JS.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationNoDataBeforeQualityDecrease:500,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:72e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3},ey=a=>({...MD(a,ZS),configName:[...a.configName??[],...ZS.configName]});import{assertNonNullable as pn,combine as bt,ErrorCategory as hn,filter as he,filterChanged as N,fromEvent as Cl,isNonNullable as ND,isNullable as FD,Logger as qD,map as _,mapTo as ay,merge as Ot,now as mn,once as it,Subject as j,Subscription as sy,tap as ny,ValueSubject as E,isHigher as UD,isInvariantQuality as oy,flattenObject as _t,throttle as Vl,getTraceSubscriptionMethod as uy,Tracer as HD,InternalsExposure as jD}from"@vkontakte/videoplayer-shared";import{merge as DD,map as CD,filter as ty,isNonNullable as VD}from"@vkontakte/videoplayer-shared";var Dl=({seekState:a,position$:e})=>DD(a.stateChangeEnded$.pipe(CD(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),ty(VD)),e.pipe(ty(()=>a.getState().state==="none")));import{assertNonNullable as BD}from"@vkontakte/videoplayer-shared";var ry=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return BD(e,`Wrong container or containerId {${a.container}}`),e};import{filter as OD,once as _D}from"@vkontakte/videoplayer-shared";var iy=(a,e,t,r)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(OD(i=>i.length>0),_D()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t?.getValue().find(r))&&e.startTransitionTo(a)};var fn=class{constructor(e={configName:[]},t=HD.createRootTracer(!1)){this.subscription=new sy;this.logger=new qD;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new E(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new $("stopped"),seekState:new $({state:"none"}),volume:new $({volume:1,muted:!1}),videoTrack:new $(void 0),videoStream:new $(void 0),audioStream:new $(void 0),autoVideoTrackSwitching:new $(!0),autoVideoTrackLimits:new $({}),isLooped:new $(!1),isLowLatency:new $(!1),playbackRate:new $(1),externalTextTracks:new $([]),internalTextTracks:new $([]),currentTextTrack:new $(void 0),textTrackCuesSettings:new $({}),cameraOrientation:new $({x:0,y:0})};this.info={playbackState$:new E("stopped"),position$:new E(0),duration$:new E(1/0),muted$:new E(!1),volume$:new E(1),availableVideoStreams$:new E([]),currentVideoStream$:new E(void 0),availableQualities$:new E([]),availableQualitiesFps$:new E({}),currentQuality$:new E(void 0),isAutoQualityEnabled$:new E(!0),autoQualityLimitingAvailable$:new E(!1),autoQualityLimits$:new E({}),availableAudioStreams$:new E([]),currentAudioStream$:new E(void 0),availableAudioTracks$:new E([]),isAudioAvailable$:new E(!0),currentPlaybackRate$:new E(1),currentBuffer$:new E({start:0,end:0}),isBuffering$:new E(!0),isStalled$:new E(!1),isEnded$:new E(!1),isLooped$:new E(!1),isLive$:new E(void 0),canChangePlaybackSpeed$:new E(void 0),atLiveEdge$:new E(void 0),atLiveDurationEdge$:new E(void 0),liveTime$:new E(void 0),liveBufferTime$:new E(void 0),liveLatency$:new E(void 0),currentFormat$:new E(void 0),availableTextTracks$:new E([]),currentTextTrack$:new E(void 0),throughputEstimation$:new E(void 0),rttEstimation$:new E(void 0),videoBitrate$:new E(void 0),hostname$:new E(void 0),httpConnectionType$:new E(void 0),httpConnectionReused$:new E(void 0),surface$:new E("none"),chromecastState$:new E("NOT_AVAILABLE"),chromecastDeviceName$:new E(void 0),intrinsicVideoSize$:new E(void 0),availableSources$:new E(void 0),is3DVideo$:new E(!1),currentVideoSegmentLength$:new E(0),currentAudioSegmentLength$:new E(0)};this.events={inited$:new j,ready$:new j,started$:new j,playing$:new j,paused$:new j,stopped$:new j,willStart$:new j,willResume$:new j,willPause$:new j,willStop$:new j,willDestruct$:new j,watchCoverageRecord$:new j,watchCoverageLive$:new j,managedError$:new j,fatalError$:new j,ended$:new j,looped$:new j,seeked$:new j,willSeek$:new j,autoplaySoundProhibited$:new j,firstBytes$:new j,loadedMetadata$:new j,firstFrame$:new j,canplay$:new j,log$:new j};this.experimental={element$:new E(void 0),tuningConfigName$:new E([]),enableDebugTelemetry$:new E(!1),dumpTelemetry:fb,getCurrentTime$:new E(null)};if(this.initLogs(),this.tuning=ey(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ya({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new XS(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new jD("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,i,s)=>{let n=Reflect.get(r,i,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(m,f)=>{let b=typeof f;return(0,ly.default)(["number","string","boolean"],b)?f:f===null?null:`<${b}>`})),d=`Player.${String(i)}`,c=`Exception calling ${d} (${l.join(", ")})`;throw this.events.fatalError$.next({id:d,category:hn.WTF,message:c,thrown:u}),u}}}})}initVideo(e){this.config=e;let{container:t,...r}=e;return this.tracer.log("initVideo",_t(r)),this.domContainer=ry(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Ca({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}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),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(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!$i()?(this.tracer.log("request play from hidden tab"),Cl(document,"visibilitychange").pipe(it()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue(),s=e;return e>=r&&!i&&(s=r-.2),this.tracer.log("seekTime",{duration:r,isLive:i,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){pn(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return 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(he(r=>r.length>0),it()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",_t(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){pn(this.providerContainer);let t=this.providerContainer?.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",_t(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return iy(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),r=this.desiredState.isLowLatency.getState();return!t||r===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let i=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:i.x+s.x,y:i.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(FD(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return ND(r)?r/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((r,{width:i})=>r||i||0,0),height:e.reduce((r,{height:i})=>r||i||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Ot(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(_(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(he(({from:e})=>e==="stopped"),it()).subscribe(()=>{this.initedAt=mn(),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"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",_t(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:hn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(it()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",_t(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(_(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(_(n=>n.destination),N()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(bt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(_(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>oy(u)?1:oy(l)?-1:UD(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(N()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(N((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(N((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(N()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(N()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(N()).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(_(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.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(bt({hasLiveOffsetByPaused:Ot(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(_(n=>n.to),N(),_(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(bt({atLiveEdge:bt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Dl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(_(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),N(),ny(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(_(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(bt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(_(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),N(),ny(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(_(n=>n.muted),N()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(_(n=>n.volume),N()).subscribe(this.info.volume$)).add(Dl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Ot(e.providerOutput.endedEvent$.pipe(ay(!0)),e.providerOutput.seekedEvent$.pipe(ay(!1))).pipe(N()).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.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(_(n=>({id:n?`No${n}`:"NoProviders",category:hn.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe(it(),_(n=>n??mn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(it(),_(()=>mn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(it(),_(()=>mn()-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 E(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new E(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(he(({to:n})=>n==="playing"),it()).subscribe(()=>r.next(!1)));let i=0,s=Ot(e.providerOutput.isBuffering$,t,r).pipe(_(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),N());this.subscription.add(s.subscribe(n=>{n?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))})),this.subscription.add(Ot(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Ot(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue(),c;d==="CONNECTED"?c="second_screen":u?l?n?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(_(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new sy;this.subscription.add(t),this.subscription.add(e.current$.pipe(N((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(he(r=>r.length>0),it()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let r=this.explicitInitialQuality??this.desiredState.videoTrack.getState()?.quality;r&&(t=e.find(({quality:i})=>i===r),t||this.setAutoQuality(!0)),t||(t=Rt(e,{container:this.domContainer.getBoundingClientRect(),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(Ot(this.desiredState.videoTrack.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(_(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;pn(this.providerContainer),pn(e),mb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>hb(t)),this.providerContainer.current$.subscribe(({type:t})=>Pi("provider",t)),e.duration$.subscribe(t=>Pi("duration",t)),e.availableVideoTracks$.pipe(he(t=>!!t.length),it()).subscribe(t=>Pi("tracks",t)),this.events.fatalError$.subscribe(new ce("fatalError")),this.events.managedError$.subscribe(new ce("managedError")),e.position$.subscribe(new ce("position")),e.currentVideoTrack$.pipe(_(t=>t?.quality)).subscribe(new ce("quality")),this.info.currentBuffer$.subscribe(new ce("buffer")),e.isBuffering$.subscribe(new ce("isBuffering"))].forEach(t=>this.subscription.add(t)),Pi("codecs",dg())}initTracerSubscription(){let e=uy(this.tracer.log.bind(this.tracer)),t=uy(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(N()).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(bt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(he(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),N((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(he(r=>r>0),N()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(he(r=>r>0),N()).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(bt({currentBuffer:this.info.currentBuffer$.pipe(he(r=>r.end>0),N((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(N())}).pipe(Vl(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(N()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(N()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(N()).subscribe(e("canChangePlaybackSpeed"))).add(bt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(he(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),Vl(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(N(),he(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(N(),he(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(N()).subscribe(e("muted"))).add(this.info.volume$.pipe(N()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(N(),he(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(bt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(he(({throughputEstimation:r,rtt:i})=>!!r&&!!i),Vl(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(N(),he(r=>r===!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},r=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:hn.DOM,message:String(i)})})};this.subscription.add(Ot(Cl(document,"visibilitychange"),Cl(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!e?.released;i&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(i=>i.quality===t);this.tracer.log("setVideoTrackIdByQuality",_t({quality:t,availableTracks:_t(e),track:_t(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as DY,Observable as CY,Subject as VY,ValueSubject as BY,VideoQuality as OY}from"@vkontakte/videoplayer-shared";var _Y=`@vkontakte/videoplayer-core@${_l}`;export{Ua as ChromecastState,vn as HttpConnectionType,CY as Observable,me as PlaybackState,fn as Player,_Y as SDK_VERSION,VY as Subject,DY as Subscription,Sn as Surface,_l as VERSION,BY as ValueSubject,yt as VideoFormat,OY as VideoQuality};
|
|
124
|
+
`;var Js=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let a=this.canvas.getContext("webgl");if(!a)throw new Error("Could not initialize WebGL context");this.gl=a,this.container.appendChild(this.canvas),this.camera=new Ks(this.params.fov,this.params.orientation),this.cameraRotationManager=new Xs(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"),r=this.gl.getAttribLocation(this.program,"a_texel"),a=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),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(r,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(a,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(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(nv,this.gl.VERTEX_SHADER),r=this.createShader(ov,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),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,r=1,a=this.frameHeight/(this.frameWidth/this.viewportWidth);return a>this.viewportHeight?t=this.viewportHeight/a:r=a/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),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,r=this.camera.fov.x/360/2,a=this.camera.fov.y/180/2,s=e-r,n=t-a,o=e+r,u=t-a,l=e+r,c=t+a,d=e-r,p=t+a;return[s,n,o,u,l,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as JL,now as uv,Subscription as ZL,filter as eM,combine as lv,ValueSubject as fl,isNonNullable as tM}from"@vkontakte/videoplayer-shared";var bl=class{constructor(){this.isSeeked$=new fl(!1);this.isBuffering$=new fl(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new ZL;this.severeStallOccurred$=new fl(!1)}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,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(lv({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(eM(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(lv({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{let{stallDurationNoDataBeforeQualityDecrease:r,stallCountBeforeQualityDecrease:a,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.qualityLimitsOnStall;if(JL(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),c=uv(),d=a&&this.currentStallsCount>=a,p=r&&c-this.lastUniqueVideoTrackSelectedTimestamp>=r+o&&c-l>=r+o&&t>=r;(d||p)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,tM(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=uv(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},cv=bl;import{combine as rM,map as iM,observeElementSize as aM,Subscription as sM,ValueSubject as gl,noop as nM}from"@vkontakte/videoplayer-shared";var Zs=class{constructor(){this.subscription=new sM;this.pipSize$=new gl(void 0);this.videoSize$=new gl(void 0);this.elementSize$=new gl(void 0);this.pictureInPictureWindowRemoveEventListener=nM}connect({observableVideo:e,video:t}){let r=a=>{let s=a.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(aM(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:a})=>{this.pipSize$.next({width:a.width,height:a.height}),a.addEventListener("resize",r),this.pictureInPictureWindowRemoveEventListener=()=>{a.removeEventListener("resize",r)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(rM({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(iM(({videoSize:a,inPip:s,pipSize:n})=>s?n:a)).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 lr=class{constructor(e){this.subscription=new hM;this.videoState=new M("stopped");this.droppedFramesManager=new Ms;this.stallsManager=new cv;this.elementSizeManager=new Zs;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new wi;this.audioTrackSwitchHistory=new wi;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state==="requested"&&r?.to!=="paused"&&e!=="stopped"&&t!=="stopped"){let n=this.liveOffset?.getTotalPausedTime()??0;this.seek(a.position-n,a.forcePrecise)}if(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"),I(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"),I(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="ready"&&I(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset?.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):r?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;default:return lM(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Js(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 De(e.source.url),this.params=e,this.video=ge(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(te(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new zs({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=ye(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:Sl.WTF,message:`${a} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:a,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(dv(c=>!!c.length),hv()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(vl(c=>c.to.state!=="none"),Ea());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(Ea()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:r.isBuffering$,looped$:r.looped$}),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.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(dv(pv),hv()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(vl(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(tt(this.video,t.isLooped,a)),this.subscription.add(ve(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Me(this.video,t.playbackRate,r.playbackRateState$,a)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(Ve(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},a)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(cM(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let f of d.audio){h.push(tl(f));let b=[];for(let g of f.representations){let S=OS(g);b.push(S),this.audioTracksMap.set(S,{stream:f,representation:g})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(h)}let p=[];for(let h of d.video){p.push(rl(h));let f=[];for(let b of h.representations){let g=BS({...b,streamId:h.id});g&&(f.push(g),this.videoTracksMap.set(g,{stream:h,representation:b}))}this.videoStreamsMap.set(h,f)}this.params.output.availableVideoStreams$.next(p);for(let h of d.text)for(let f of h.representations){let b=_S(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),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a));let o=c=>e.error$.next({id:"RepresentationSwitch",category:Sl.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(en(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,pM(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,mv.default)(["manifest_ready","running"],c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[h,f]=p,b=[...this.videoTracksMap.keys()].find(S=>this.videoTracksMap.get(S)?.representation.id===h.id);pv(b)&&(this.stallsManager.lastVideoTrackSelected=b);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")this.player.initRepresentations(h.id,f?.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",h.id).catch(o),f){let S=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",f.id,S).catch(o)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Ea()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=d,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===h.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(rl(h))},a)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Ea()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=d,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===h.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(tl(h))},a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),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)},a)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,a)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,a)),this.textTracksManager.connect(this.video,t,e);let u=t.playbackState.stateChangeStarted$.pipe(vl(({to:c})=>c==="ready"),Ea());this.subscription.add(en(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,yl(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(en(u,this.player.state$.stateChangeEnded$,yl(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=en(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,yl(["init"])).pipe(dM(0));this.subscription.add(l.subscribe(this.syncPlayback,a))}selectVideoAudioRepresentations(){let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),a=e.videoTrack.getState()?.id,n=[...this.videoTracksMap.keys()].find(({id:L})=>L===a),o=t.currentVideoTrack$.getValue(),u=e.videoStream.getState()??(n&&this.videoTracksMap.get(n)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:L})=>L===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=it(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,f=Math.min(d/Math.min(p,h||1/0),1),b=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),g=[...this.audioStreamsMap.keys()].find(({id:L})=>L===b?.id)??this.audioStreamsMap.keys().next().value,S=0;if(g){if(n&&!r){let L=As(n,c,this.audioStreamsMap.get(g)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);S=Math.max(S,L?.bitrate??-1/0)}if(o){let L=As(o,c,this.audioStreamsMap.get(g)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);S=Math.max(S,L?.bitrate??-1/0)}}let P=$t(c,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:S,forwardBufferHealth:f,current:o,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}),v=r?P??n:n??P,R=g&&Pb(v,c,this.audioStreamsMap.get(g)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:f,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),y=this.videoTracksMap.get(v)?.representation,E=R&&this.audioTracksMap.get(R)?.representation;if(y&&E)return[y,E];if(y&&!E&&this.audioTracksMap.size===0)return[y,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Te(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Sl.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),Se(this.video),this.tracer.end()}};var xa=class extends lr{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as fv,interval as mM,map as bv}from"@vkontakte/videoplayer-shared";var Pa=class extends lr{constructor(e){super(e),this.liveOffset=new pt,this.textTracksManager.destroy()}subscribe(){super.subscribe();let{output:e,observableVideo:t,desiredState:r,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),a(t.timeUpdate$,e.liveBufferTime$),a(this.player.liveDuration$,e.duration$),a(this.player.liveLatency$,e.liveLatency$),this.subscription.add(r.isLowLatency.stateChangeEnded$.pipe(bv(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(fv({interval:mM(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{if(this.videoState.getState()==="playing"){let n=e.position$.getValue()+(s-1);n<=0&&e.position$.next(n),this.liveOffset?.resetTo(-n*1e3)}})).add(fv({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(bv(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=NS(s);this.params.output.availableTextTracks$.next([n])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),a=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(n,a)})}};var Sv=V(Es(),1);import{assertNever as ka,assertNonNullable as gv,debounce as fM,ErrorCategory as tn,filter as bM,isNonNullable as gM,isNullable as SM,map as rn,merge as vM,Observable as yM,observableFrom as TM,Subscription as IM,videoSizeToQuality as EM}from"@vkontakte/videoplayer-shared";var Ye={};var zr=(i,e)=>new yM(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),wa=class{constructor(e){this.subscription=new IM;this.videoState=new M("initializing");this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(e!=="initializing")switch(r?.to!=="paused"&&a.state==="requested"&&this.seek(a.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:ka(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:ka(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:ka(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:ka(e)}break;default:ka(t)}};this.textTracksManager=new De(e.source.url),this.video=ge(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(te(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),Se(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:tn.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Sv.default)(import("hls.js").then(a=>{e||(Ye.Hls=a.default,Ye.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){gv(Ye.Hls,"hls.js not loaded"),this.hls=new Ye.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){gv(Ye.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:tn.WTF,message:"HlsJsProvider internal logic error",thrown:l})},a=ye(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,r));s(a.timeUpdate$,t.position$),s(a.durationChange$,t.duration$),s(a.ended$,t.endedEvent$),s(a.looped$,t.loopedEvent$),s(a.error$,t.error$),s(a.isBuffering$,t.isBuffering$),s(a.currentBuffer$,t.currentBuffer$),s(a.loadStart$,t.firstBytesEvent$),s(a.loadedMetadata$,t.loadedMetadataEvent$),s(a.playing$,t.firstFrameEvent$),s(a.canplay$,t.canplay$),s(a.seeked$,t.seekedEvent$),s(a.inPiP$,t.inPiP$),s(a.inFullscreen$,t.inFullscreen$),this.subscription.add(tt(this.video,e.isLooped,r)),this.subscription.add(ve(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Me(this.video,e.playbackRate,a.playbackRateState$,r)),s(Ve(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(rn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(zr(this.hls,Ye.Events.ERROR).subscribe(l=>{l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:tn.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${l.err?.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(e.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(e.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(zr(this.hls,Ye.Events.MANIFEST_PARSED).pipe(rn(({levels:l})=>l.reduce((c,d)=>{let p=d.name||d.height.toString(10),{width:h,height:f}=d,b=At(d.attrs.QUALITY??"")??EM({width:h,height:f});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,S={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:f},fps:g};return this.trackLevels.set(p,{track:S,level:d}),c.push(S),c},[]))),t.availableVideoTracks$),s(zr(this.hls,Ye.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",f=d.lang;c.push({id:p,url:h,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(zr(this.hls,Ye.Events.LEVEL_LOADING).pipe(rn(({url:l})=>te(l))),t.hostname$),s(zr(this.hls,Ye.Events.FRAG_CHANGED),l=>{let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3)}),this.subscription.add(Pt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>Array.from(this.trackLevels.values()).find(({level:c})=>c===l)?.track,o=zr(this.hls,Ye.Events.LEVEL_SWITCHED).pipe(rn(({level:l})=>n(this.hls.levels[l])));o.pipe(bM(gM)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Pt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{if(SM(l))return;let c=this.trackLevels.get(l.id)?.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=vM(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,TM(["init"])).pipe(fM(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await Te(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:tn.DOM,thrown:t}))||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){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.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0)}};var vv="X-Playback-Duration",Tl=async i=>{let e=await Qe(i),t=await e.text(),r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return r?parseInt(r,10):e.headers.has(vv)?parseInt(e.headers.get(vv),10):void 0};import{assertNever as CM,combine as VM,debounce as BM,ErrorCategory as nn,filter as OM,filterChanged as _M,isNonNullable as Iv,isNullable as on,map as Ev,merge as NM,observableFrom as FM,Subscription as qM,ValueSubject as xl,VideoQuality as UM}from"@vkontakte/videoplayer-shared";var El=V(ko(),1);import{videoSizeToQuality as xM,getExponentialDelay as PM}from"@vkontakte/videoplayer-shared";var kM=i=>{let e=null;if(i.QUALITY&&(e=At(i.QUALITY)),!e&&i.RESOLUTION){let[t,r]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=xM({width:t,height:r})}return e??null},wM=(i,e)=>{let t=i.split(`
|
|
125
|
+
`),r=[],a=[];for(let s=0;s<t.length;s++){let n=t[s],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),u=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!u)){if(o){let l=(0,El.default)(o[1].split(",").map(g=>g.split("="))),c=l.QUALITY??`stream-${l.BANDWIDTH}`,d=kM(l),p;l.BANDWIDTH&&(p=parseInt(l.BANDWIDTH,10)/1e3||void 0),!p&&l["AVERAGE-BANDWIDTH"]&&(p=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,f;if(l.RESOLUTION){let[g,S]=l.RESOLUTION.split("x").map(P=>parseInt(P,10));g&&S&&(f={width:g,height:S})}let b=new URL(t[++s],e).toString();d&&r.push({id:c,quality:d,url:b,bandwidth:p,size:f,fps:h})}if(u){let l=(0,El.default)(u[1].split(",").map(h=>{let f=h.indexOf("=");return[h.substring(0,f),h.substring(f+1)]}).map(([h,f])=>[h,f.replace(/^"|"$/g,"")])),c=l.URI?.replace(/playlist$/,"subtitles.vtt"),d=l.LANGUAGE,p=l.NAME;c&&d&&a.push({type:"internal",id:d,label:p,language:d,url:c,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:a}},AM=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),Il=0,yv=async(i,e=i,t,r)=>{let s=await(await Qe(i,r)).text();Il+=1;try{let{qualityManifests:n,textTracks:o}=wM(s,e);return{qualityManifests:n,textTracks:o}}catch{if(Il<=t.manifestRetryMaxCount)return await AM(PM(Il-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),yv(i,e,t)}return{qualityManifests:[],textTracks:[]}},an=yv;import{isNonNullable as RM,Subscription as $M,throttle as LM,ValueSubject as Tv,Subject as MM,ErrorCategory as DM}from"@vkontakte/videoplayer-shared";var sn=class{constructor(e,t,r,a,s){this.subscription=new $M;this.abortControllers={destroy:new oe,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new Tv(null);this.getCurrentTime$=new Tv(null);this.error$=new MM;this.params={fetchManifestData:r,sourceUrl:a,downloadThreshold:s},this.subscription.add(e.pipe(LM(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:r}=await this.fetchManifestData();await this.processTextTracks(r,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let r=await this.parseTextTracks(e,t);r&&(this.currentTextTrackData=r)}catch(r){this.error("processTextTracks",r)}}async parseTextTracks(e,t){for(let r of e){let a=new URL(r.url,t).toString(),n=await(await Qe(a,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,a);return{textTrack:r,playlist:o}}}parsePlaylist(e,t){let r={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},a=e.split(`
|
|
126
|
+
`),s=0;for(let n=0;n<a.length;++n){let o=a[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=a[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(r.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!r.segmentStartTime){let d=new Date(r.vkStartTime).valueOf(),p=new Date(r.programDateTime).valueOf();r.segmentStartTime=p-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):r.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):r.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):r.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);r.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):r.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return r}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(RM(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:r}=t[0].time,{to:a}=t[t.length-1].time;if(e<r||e>a)return;a-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 oe;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:DM.WTF,thrown:t,message:e})}};var Aa=class{constructor(e){this.subscription=new qM;this.videoState=new M("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new xl([]);this.liveOffset=new pt;this.manifestStartTime$=new xl(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="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"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(a?.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":r==="ready"?I(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),I(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):a?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="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 a?.to==="paused"&&(I(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return CM(t)}};this.params=e,this.video=ge(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:UM.INVARIANT,url:this.params.source.url};let t=(r,a)=>an(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},a);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new sn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new De(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:a})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:nn.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(a,this.params.source.url),this.manifests$.next([this.masterManifest,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:nn.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(te(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new xl(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:nn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=ye(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(a.ended$,e.endedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(ve(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Me(this.video,t.playbackRate,a.playbackRateState$,r)),s(Ve(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(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(_M(),Ev(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&Iv(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(te(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(a.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(VM({startTime:this.manifestStartTime$.pipe(OM(Iv)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(Ev(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=NM(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,FM(["init"])).pipe(BM(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),Se(this.video)}prepare(){let e=this.selectManifest();if(on(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=t?.to??r??{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&a.searchParams.set(c,d)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ne(a.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(n),this.video.setAttribute("src",n),this.video.load(),Tl(n).then(o=>{if(!on(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(on(u)||!isFinite(u))&&Qe(n).then(l=>l.text()).then(l=>{let c=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(c){let d=new URL(c,n).toString();Tl(d).then(p=>{on(p)||this.maxSeekBackTime$.next(p)})}}).catch(()=>{})}})}playIfAllowed(){Te(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:nn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=ne(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 HM,debounce as jM,ErrorCategory as Pl,fromEvent as kl,isNonNullable as GM,isNullable as QM,map as xv,merge as Pv,observableFrom as kv,Subscription as WM,ValueSubject as YM,VideoQuality as zM,clientChecker as KM}from"@vkontakte/videoplayer-shared";var Ra=class{constructor(e){this.subscription=new WM;this.videoState=new M("stopped");this.manifests$=new YM([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="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"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch(a?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?I(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):a?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):a?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return HM(t)}};this.textTracksManager=new De(e.source.url),this.params=e,this.video=ge(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:zM.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(te(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),an(ne(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:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Pl.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:Pl.WTF,message:"HlsProvider internal logic error",thrown:o})},a=ye(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(xv(o=>o.to)),this.params.output.playbackState$),this.subscription.add(tt(this.video,t.isLooped,r)),this.subscription.add(ve(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Me(this.video,t.playbackRate,a.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&GM(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(te(f.url)))}let d=this.params.desiredState.playbackRate.getState(),p=this.params.output.element$.getValue()?.playbackRate;if(d!==p){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(d),h.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(xv(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!KM.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Pv(kl(o,"addtrack"),kl(o,"removetrack"),kl(o,"change"),kv(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=Pv(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,kv(["init"])).pipe(jM(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Se(this.video)}prepare(){let e=this.selectManifest();if(QM(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:s,min:n}=t?.to??r??{};for(let[o,u]of[[s,"mq"],[n,"lq"]]){let l=String(parseFloat(o||""));u&&o&&a.searchParams.set(u,l)}}this.video.setAttribute("src",a.toString()),this.video.load()}playIfAllowed(){Te(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Pl.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var $v=V(xr(),1),$a=V(Vr(),1);import{assertNever as XM,assertNonNullable as wv,debounce as JM,ErrorCategory as Av,isHigher as ZM,isHigherOrEqual as eD,isInvariantQuality as Rv,isLowerOrEqual as tD,isNonNullable as rD,merge as iD,observableFrom as aD,Subscription as sD,map as nD}from"@vkontakte/videoplayer-shared";var La=class{constructor(e){this.subscription=new sD;this.videoState=new M("stopped");this.trackUrls={};this.textTracksManager=new De;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=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"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0}),n.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[n.to.id]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(r?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?I(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),I(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()):r?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;default:return XM(e)}};this.params=e,this.video=ge(e.container,e.tuning),this.params.output.element$.next(this.video),(0,$v.default)(this.params.source).reverse().forEach(([t,r],a)=>{let s=a.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,$a.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,r=o=>{e.error$.next({id:"MpegProvider",category:Av.WTF,message:"MpegProvider internal logic error",thrown:o})},a=ye(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(nD(o=>o.to)),this.params.output.playbackState$),this.subscription.add(tt(this.video,t.isLooped,r)),this.subscription.add(ve(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Me(this.video,t.playbackRate,a.playbackRateState$,r)),s(Ve(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&rD(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let u=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(u!==l){let c=this.params.output.element$.getValue();c&&(this.params.desiredState.playbackRate.setState(u),c.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=iD(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,aD(["init"])).pipe(JM(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Se(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;wv(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];wv(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ma(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(te(t))}playIfAllowed(){Te(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Av.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){let t,r=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){let a=(0,$a.default)(this.trackUrls).find(o=>!Rv(o.track.quality)&&tD(o.track.quality,e))?.track,s=this.params.desiredState.videoTrack.getState()?.id,n=this.trackUrls[s??"0"]?.track;if(a&&n&&eD(n.quality,a.quality)&&(t=a),!t){let o=(0,$a.default)(this.trackUrls).filter(l=>!Rv(l.track.quality)&&ZM(l.track.quality,e)),u=o.length;u&&(t=o[u-1].track)}t&&(r=t.quality)}else if(!e){let a=(0,$a.default)(this.trackUrls).map(s=>s.track);t=$t(a,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};import{assertNever as Mv,debounce as cD,merge as Dv,observableFrom as dD,Subscription as pD,map as Cv,ValueSubject as hD,ErrorCategory as Al,VideoQuality as mD}from"@vkontakte/videoplayer-shared";import{ErrorCategory as oD}from"@vkontakte/videoplayer-shared";var Lv=["stun:videostun.mycdn.me:80"],uD=1e3,lD=3,wl=()=>null,un=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=wl;this.externalStopCallback=wl;this.externalErrorCallback=wl;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.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:Lv}]};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:oD.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),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))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),uD)}normalizeOptions(e={}){let t={stunServerList:Lv,maxRetryNumber:lD,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ma=class{constructor(e){this.videoState=new M("stopped");this.maxSeekBackTime$=new hD(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=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"),I(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"),I(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()):r?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;default:return Mv(e)}};this.subscription=new pD,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ge(e.container,e.tuning),this.liveStreamClient=new un(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),Se(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Al.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};Dv(this.videoState.stateChangeStarted$.pipe(Cv(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Cv(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=ye(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(a.timeUpdate$,e.liveTime$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(Ve(this.video),this.params.output.elementVisible$),this.subscription.add(a.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(a.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(ve(this.video,t.volume,a.volumeState$,r)).add(a.volumeState$.subscribe(e.volume$,r)).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 Mv(n.to)}},r)).add(Dv(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,dD(["init"])).pipe(cD(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(te(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:mD.INVARIANT}),this.video.srcObject=e,I(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:Al.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Te(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Al.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Da=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as Ca,assertNonNullable as _t,ErrorCategory as ln,filter as Fv,isNonNullable as qv,isNullable as ID,map as ED,merge as xD,once as PD,Subject as Pe,Subscription as Uv,ValueSubject as D,flattenObject as Hv}from"@vkontakte/videoplayer-shared";import{Observable as fD,map as Vv,Subscription as bD,Subject as gD}from"@vkontakte/videoplayer-shared";var Bv=i=>new fD(e=>{let t=new bD,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(Vv(({from:l,to:c})=>`${l}-${c}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe(Vv(({type:l})=>l!==void 0)),n=new gD,o=0,u="unknown";return t.add(r.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),i.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),i.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as SD,Subscription as vD,combine as yD,filter as _v,once as Nv}from"@vkontakte/videoplayer-shared";function Ov(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as TD}from"@vkontakte/videoplayer-shared";var Kr=class i{constructor(e,t,r,a){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=a;this.destroyController=new oe;this.subscriptions=new vD;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(_v(s=>!!s.type),Nv()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){TD.isSafari&&e!=="MPEG"||this.subscriptions.add(yD({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(_v(({playbackState:t,video:r,volume:{muted:a,volume:s}})=>t==="playing"&&!!r&&!a&&!!s),Nv()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(r=>{r||this.destroy()}).catch(r=>{this.handleError(r),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,r=Ov();this.audioContext=r;let a=r.createGain();if(this.gainNode=a,a.gain.value=t,a.connect(r.destination),r.state==="suspended"&&(await r.resume(),this.destroyController.signal.aborted))return!1;let s=r.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(a),!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:i.errorId,category:SD.VIDEO_PIPELINE,message:e?.message??`${i.errorId} exception`,thrown:e})}};var kD={chunkDuration:5e3,maxParallelRequests:5},Va=class{constructor(e){this.current$=new D({type:void 0});this.providerError$=new Pe;this.noAvailableProvidersError$=new Pe;this.volumeMultiplierError$=new Pe;this.providerOutput={position$:new D(0),duration$:new D(1/0),volume$:new D({muted:!1,volume:1}),availableVideoStreams$:new D([]),currentVideoStream$:new D(void 0),availableVideoTracks$:new D([]),currentVideoTrack$:new D(void 0),availableAudioStreams$:new D([]),currentAudioStream$:new D(void 0),availableAudioTracks$:new D([]),currentVideoSegmentLength$:new D(0),currentAudioSegmentLength$:new D(0),isAudioAvailable$:new D(!0),autoVideoTrackLimitingAvailable$:new D(!1),autoVideoTrackLimits$:new D(void 0),currentBuffer$:new D(void 0),isBuffering$:new D(!0),error$:new Pe,warning$:new Pe,willSeekEvent$:new Pe,soundProhibitedEvent$:new Pe,seekedEvent$:new Pe,loopedEvent$:new Pe,endedEvent$:new Pe,firstBytesEvent$:new Pe,loadedMetadataEvent$:new Pe,firstFrameEvent$:new Pe,canplay$:new Pe,isLive$:new D(void 0),isLowLatency$:new D(!1),canChangePlaybackSpeed$:new D(!0),liveTime$:new D(void 0),liveBufferTime$:new D(void 0),liveLatency$:new D(void 0),availableTextTracks$:new D([]),currentTextTrack$:new D(void 0),hostname$:new D(void 0),httpConnectionType$:new D(void 0),httpConnectionReused$:new D(void 0),inPiP$:new D(!1),inFullscreen$:new D(!1),element$:new D(void 0),elementVisible$:new D(!0),availableSources$:new D(void 0),is3DVideo$:new D(!1),playbackState$:new D(""),getCurrentTime$:new D(null)};this.subscription=new Uv;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=pg([...mg(this.params.tuning),...hg(this.params.tuning)],this.params.tuning).filter(l=>qv(e.sources[l])),{forceFormat:r,formatsToAvoid:a}=this.params.tuning,s=[];r?s=[r]:a.length?s=[...t.filter(l=>!(0,Rl.default)(a,l)),...t.filter(l=>(0,Rl.default)(a,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",Hv(s)),this.screenFormatsIterator=new Da(s);let n=[...Bu(!0),...Bu(!1)];this.chromecastFormatsIterator=new Da(n.filter(l=>qv(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Kr.isSupported()&&(this.volumeMultiplierManager=new Kr(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(ID(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:ln.WTF,message:"Failed to create provider",thrown:a})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),a=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:a?r.position:t,forcePrecise:a?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();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 Ca(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:a}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return _t(o),new xa({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return _t(o),new Pa({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return _t(o),qr||!this.params.tuning.useHlsJs?new Ra({...n,source:o}):new wa({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return _t(o),new Aa({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return _t(o),new La({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return _t(o),new Fb({...n,source:o,config:{...kD,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return _t(o),new Ma({container:r,source:o,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Ca(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:a,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return _t(o),new Ei({connection:o,meta:s,container:r,source:t,format:e,desiredState:a,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 Ca(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Ca(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 Ca(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=a=>{let s=new URL(a);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:r(e.url)}}return(0,Gv.default)((0,jv.default)(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new Uv,t=!1,r=0;return e.add(xD(this.providerOutput.error$.pipe(Fv(a=>!this.params.tuning.ignoreAudioRendererError||!a.message||!/AUDIO_RENDERER_ERROR/ig.test(a.message))),Bv({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(ED(a=>({id:`ProviderHangup:${a}`,category:ln.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let a=this.params.desiredState.playbackState.transitionEnded$.pipe(Fv(({to:s})=>s==="playing"),PD()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{let s=this.current$.getValue().destination,n={error:a,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=a.category===ln.NETWORK,u=a.category===ln.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=r<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c},c?(r++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s??"SCREEN")}this.tracer.error("providerError",Hv(n))})),e}};import{fromEvent as cn,once as wD,combine as AD,Subscription as Qv,ValueSubject as $l,map as RD,filter as $D,isNonNullable as dn,now as $e,safeStorage as Ll}from"@vkontakte/videoplayer-shared";var LD=5e3,Wv="one_video_throughput",Yv="one_video_rtt",Ba=window.navigator.connection,zv=()=>{let i=Ba?.downlink;if(dn(i)&&i!==10)return i*1e3},Kv=()=>{let i=Ba?.rtt;if(dn(i)&&i!==3e3)return i},Xv=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},Ml=class i{constructor(e){this.subscription=new Qv;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=i.load(Wv)||(e.useBrowserEstimation?zv():void 0)||LD,r=i.load(Yv)??(e.useBrowserEstimation?Kv():void 0)??0;if(this.throughput$=new $l(t),this.rtt$=new $l(r),this.rttAdjustedThroughput$=new $l(Xv(t,r,e.rttPenaltyRequestSize)),this.throughput=nr.getSmoothedValue(t,-1,e),this.rtt=nr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let a=()=>{let n=zv();n&&this.throughput.next(n);let o=Kv();dn(o)&&this.rtt.next(o)};Ba&&"onchange"in Ba&&this.subscription.add(cn(Ba,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{Ll.set(Wv,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{Ll.set(Yv,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(AD({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(RD(({throughput:a,rtt:s})=>Xv(a,s,e.rttPenaltyRequestSize)),$D(a=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(a-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=$e(),a=new Qv;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(cn(e,"progress").pipe(wD()).subscribe(s=>{t=s.loaded,r=$e()}));break;case 1:case 0:a.add(cn(e,"loadstart").subscribe(()=>{t=0,r=$e()}));break}a.add(cn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=$e(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let a=0,s=$e(),n=0,o=$e(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(a,$e()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=$e();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=d.byteLength,s=$e()}else n+=d.byteLength;o=$e()}else a+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&$e()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,$e()-o,this.concurrentDownloads.size),n=0,o=$e());await r?.read().then(l,u)}};this.concurrentDownloads.add(e),r?.read().then(l,u)}addRawSpeed(e,t,r=1,a=!1){if(i.sanityCheck(e,t,a)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let a=e*8/t;return!(!a||!isFinite(a)||a>1e6||a<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){let t=Ll.get(e);if(dn(t))return parseInt(t,10)??void 0}},Jv=Ml;import{fillWithDefault as MD,VideoQuality as Zv}from"@vkontakte/videoplayer-shared";var ey={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:{bitrateFactorAtEmptyBuffer:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Zv.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Zv.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationNoDataBeforeQualityDecrease:500,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!1},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:72e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3},ty=i=>({...MD(i,ey),configName:[...i.configName??[],...ey.configName]});import{assertNonNullable as pn,combine as gt,ErrorCategory as hn,filter as me,filterChanged as F,fromEvent as Cl,isNonNullable as ND,isNullable as FD,Logger as qD,map as N,mapTo as sy,merge as Nt,now as mn,once as at,Subject as G,Subscription as ny,tap as oy,ValueSubject as x,isHigher as UD,isInvariantQuality as uy,flattenObject as Ft,throttle as Vl,getTraceSubscriptionMethod as ly,Tracer as HD,InternalsExposure as jD}from"@vkontakte/videoplayer-shared";import{merge as DD,map as CD,filter as ry,isNonNullable as VD}from"@vkontakte/videoplayer-shared";var Dl=({seekState:i,position$:e})=>DD(i.stateChangeEnded$.pipe(CD(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),ry(VD)),e.pipe(ry(()=>i.getState().state==="none")));import{assertNonNullable as BD}from"@vkontakte/videoplayer-shared";var iy=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return BD(e,`Wrong container or containerId {${i.container}}`),e};import{filter as OD,once as _D}from"@vkontakte/videoplayer-shared";var ay=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(OD(a=>a.length>0),_D()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t?.getValue().find(r))&&e.startTransitionTo(i)};var fn=class{constructor(e={configName:[]},t=HD.createRootTracer(!1)){this.subscription=new ny;this.logger=new qD;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new x(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new M("stopped"),seekState:new M({state:"none"}),volume:new M({volume:1,muted:!1}),videoTrack:new M(void 0),videoStream:new M(void 0),audioStream:new M(void 0),autoVideoTrackSwitching:new M(!0),autoVideoTrackLimits:new M({}),isLooped:new M(!1),isLowLatency:new M(!1),playbackRate:new M(1),externalTextTracks:new M([]),internalTextTracks:new M([]),currentTextTrack:new M(void 0),textTrackCuesSettings:new M({}),cameraOrientation:new M({x:0,y:0})};this.info={playbackState$:new x("stopped"),position$:new x(0),duration$:new x(1/0),muted$:new x(!1),volume$:new x(1),availableVideoStreams$:new x([]),currentVideoStream$:new x(void 0),availableQualities$:new x([]),availableQualitiesFps$:new x({}),currentQuality$:new x(void 0),isAutoQualityEnabled$:new x(!0),autoQualityLimitingAvailable$:new x(!1),autoQualityLimits$:new x({}),availableAudioStreams$:new x([]),currentAudioStream$:new x(void 0),availableAudioTracks$:new x([]),isAudioAvailable$:new x(!0),currentPlaybackRate$:new x(1),currentBuffer$:new x({start:0,end:0}),isBuffering$:new x(!0),isStalled$:new x(!1),isEnded$:new x(!1),isLooped$:new x(!1),isLive$:new x(void 0),canChangePlaybackSpeed$:new x(void 0),atLiveEdge$:new x(void 0),atLiveDurationEdge$:new x(void 0),liveTime$:new x(void 0),liveBufferTime$:new x(void 0),liveLatency$:new x(void 0),currentFormat$:new x(void 0),availableTextTracks$:new x([]),currentTextTrack$:new x(void 0),throughputEstimation$:new x(void 0),rttEstimation$:new x(void 0),videoBitrate$:new x(void 0),hostname$:new x(void 0),httpConnectionType$:new x(void 0),httpConnectionReused$:new x(void 0),surface$:new x("none"),chromecastState$:new x("NOT_AVAILABLE"),chromecastDeviceName$:new x(void 0),intrinsicVideoSize$:new x(void 0),availableSources$:new x(void 0),is3DVideo$:new x(!1),currentVideoSegmentLength$:new x(0),currentAudioSegmentLength$:new x(0)};this.events={inited$:new G,ready$:new G,started$:new G,playing$:new G,paused$:new G,stopped$: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,ended$:new G,looped$:new G,seeked$:new G,willSeek$:new G,autoplaySoundProhibited$:new G,firstBytes$:new G,loadedMetadata$:new G,firstFrame$:new G,canplay$:new G,log$:new G};this.experimental={element$:new x(void 0),tuningConfigName$:new x([]),enableDebugTelemetry$:new x(!1),dumpTelemetry:fb,getCurrentTime$:new x(null)};if(this.initLogs(),this.tuning=ty(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new za({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Jv(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new jD("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,a,s)=>{let n=Reflect.get(r,a,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(h,f)=>{let b=typeof f;return(0,cy.default)(["number","string","boolean"],b)?f:f===null?null:`<${b}>`})),c=`Player.${String(a)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:hn.WTF,message:d,thrown:u}),u}}}})}initVideo(e){this.config=e;let{container:t,...r}=e;return this.tracer.log("initVideo",Ft(r)),this.domContainer=iy(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Va({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}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),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(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Mi()?(this.tracer.log("request play from hidden tab"),Cl(document,"visibilitychange").pipe(at()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),a=this.info.isLive$.getValue(),s=e;return e>=r&&!a&&(s=r-.2),this.tracer.log("seekTime",{duration:r,isLive:a,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){pn(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return 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(me(r=>r.length>0),at()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",Ft(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){pn(this.providerContainer);let t=this.providerContainer?.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",Ft(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return ay(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),r=this.desiredState.isLowLatency.getState();return!t||r===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let a=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:a.x+s.x,y:a.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(FD(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return ND(r)?r/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((r,{width:a})=>r||a||0,0),height:e.reduce((r,{height:a})=>r||a||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Nt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(N(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(N(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(N(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(N(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(N(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(me(({from:e})=>e==="stopped"),at()).subscribe(()=>{this.initedAt=mn(),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"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",Ft(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:hn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(at()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Ft(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(N(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(N(n=>n.destination),F()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(gt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(N(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>uy(u)?1:uy(l)?-1:UD(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(F()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(F((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(F((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(F()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(F()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(F()).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(N(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.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(gt({hasLiveOffsetByPaused:Nt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(N(n=>n.to),F(),N(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(gt({atLiveEdge:gt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Dl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(N(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),F(),oy(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(N(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(gt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(N(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),F(),oy(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(N(n=>n.muted),F()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(N(n=>n.volume),F()).subscribe(this.info.volume$)).add(Dl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Nt(e.providerOutput.endedEvent$.pipe(sy(!0)),e.providerOutput.seekedEvent$.pipe(sy(!1))).pipe(F()).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.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(N(n=>({id:n?`No${n}`:"NoProviders",category:hn.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe(at(),N(n=>n??mn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(at(),N(()=>mn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(at(),N(()=>mn()-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 x(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new x(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(me(({to:n})=>n==="playing"),at()).subscribe(()=>r.next(!1)));let a=0,s=Nt(e.providerOutput.isBuffering$,t,r).pipe(N(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),F());this.subscription.add(s.subscribe(n=>{n?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})),this.subscription.add(Nt(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Nt(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(N(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new ny;this.subscription.add(t),this.subscription.add(e.current$.pipe(F((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(me(r=>r.length>0),at()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let r=this.explicitInitialQuality??this.desiredState.videoTrack.getState()?.quality;r&&(t=e.find(({quality:a})=>a===r),t||this.setAutoQuality(!0)),t||(t=$t(e,{container:this.domContainer.getBoundingClientRect(),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(Nt(this.desiredState.videoTrack.stateChangeStarted$.pipe(N(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(N(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(N(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(N(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(N(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(N(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(N(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(N(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(N(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;pn(this.providerContainer),pn(e),mb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>hb(t)),this.providerContainer.current$.subscribe(({type:t})=>ki("provider",t)),e.duration$.subscribe(t=>ki("duration",t)),e.availableVideoTracks$.pipe(me(t=>!!t.length),at()).subscribe(t=>ki("tracks",t)),this.events.fatalError$.subscribe(new de("fatalError")),this.events.managedError$.subscribe(new de("managedError")),e.position$.subscribe(new de("position")),e.currentVideoTrack$.pipe(N(t=>t?.quality)).subscribe(new de("quality")),this.info.currentBuffer$.subscribe(new de("buffer")),e.isBuffering$.subscribe(new de("isBuffering"))].forEach(t=>this.subscription.add(t)),ki("codecs",dg())}initTracerSubscription(){let e=ly(this.tracer.log.bind(this.tracer)),t=ly(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(F()).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(gt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(me(({currentQuality:r,videoBitrate:a})=>!!r&&!!a),F((r,a)=>r.currentQuality===a.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(me(r=>r>0),F()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(me(r=>r>0),F()).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(gt({currentBuffer:this.info.currentBuffer$.pipe(me(r=>r.end>0),F((r,a)=>r.end===a.end&&r.start===a.start)),position:this.info.position$.pipe(F())}).pipe(Vl(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(F()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(F()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(F()).subscribe(e("canChangePlaybackSpeed"))).add(gt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(me(({liveTime:r,liveBufferTime:a})=>!!r&&!!a),Vl(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(F(),me(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(F(),me(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(F()).subscribe(e("muted"))).add(this.info.volume$.pipe(F()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(F(),me(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(gt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(me(({throughputEstimation:r,rtt:a})=>!!r&&!!a),Vl(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(F(),me(r=>r===!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},r=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:hn.DOM,message:String(a)})})};this.subscription.add(Nt(Cl(document,"visibilitychange"),Cl(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let a=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!e?.released;a&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(a=>a.quality===t);this.tracer.log("setVideoTrackIdByQuality",Ft({quality:t,availableTracks:Ft(e),track:Ft(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as V3,Observable as B3,Subject as O3,ValueSubject as _3,VideoQuality as N3}from"@vkontakte/videoplayer-shared";var F3=`@vkontakte/videoplayer-core@${_l}`;export{Ha as ChromecastState,Sn as HttpConnectionType,B3 as Observable,be as PlaybackState,fn as Player,F3 as SDK_VERSION,O3 as Subject,V3 as Subscription,vn as Surface,_l as VERSION,_3 as ValueSubject,Tt as VideoFormat,N3 as VideoQuality};
|