@vkontakte/videoplayer-core 2.0.116-dev.48c29cc5.0 → 2.0.116-dev.68a2c5fb.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 +21 -21
- package/es2015.esm.js +21 -21
- package/es2018.cjs.js +24 -24
- package/es2018.esm.js +23 -23
- package/esnext.cjs.js +17 -17
- package/esnext.esm.js +14 -14
- package/evergreen.esm.js +19 -19
- package/package.json +2 -2
- package/types/player/Player.d.ts +2 -0
- package/types/providers/DashProvider/lib/buffer.d.ts +0 -4
- package/types/providers/DashProvider/lib/fetcher.d.ts +3 -1
- package/types/providers/DashProvider/lib/parsers/index.d.ts +2 -1
- package/types/providers/DashProvider/lib/parsers/mpeg/BoxTypeEnum.d.ts +1 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/index.d.ts +1 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/mvhd.d.ts +35 -0
- package/types/providers/DashProvider/lib/types.d.ts +2 -1
- package/types/providers/DashProvider/lib/utils.d.ts +0 -1
- package/types/providers/utils/addSubtitlesParam.d.ts +2 -0
- package/types/utils/VolumeMultiplierManager/VolumeMultiplierManager.d.ts +6 -3
- package/types/utils/VolumeMultiplierManager/audioContext.d.ts +1 -9
- package/types/utils/buffer/isPositionBuffered.d.ts +1 -1
- package/types/utils/tuningConfig.d.ts +8 -4
package/es2018.esm.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.116-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.116-dev.68a2c5fb.0
|
|
3
|
+
* Thu, 07 Nov 2024 09:04:05 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-116/doc/
|
|
5
5
|
*/
|
|
6
|
-
var Sv=Object.create;var ac=Object.defineProperty;var vv=Object.getOwnPropertyDescriptor;var yv=Object.getOwnPropertyNames;var Tv=Object.getPrototypeOf,Iv=Object.prototype.hasOwnProperty;var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var Ev=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of yv(e))!Iv.call(a,r)&&r!==t&&ac(a,r,{get:()=>e[r],enumerable:!(i=vv(e,r))||i.enumerable});return a};var Fe=(a,e,t)=>(t=a!=null?Sv(Tv(a)):{},Ev(e||!a||!a.__esModule?ac(t,"default",{value:a,enumerable:!0}):t,a));var Ee=m((EL,pc)=>{"use strict";pc.exports=function(a){try{return!!a()}catch(e){return!0}}});var tr=m((xL,hc)=>{"use strict";var Lv=Ee();hc.exports=!Lv(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var de=m((PL,bc)=>{"use strict";var fc=tr(),mc=Function.prototype,$n=mc.call,Mv=fc&&mc.bind.bind($n,$n);bc.exports=fc?Mv:function(a){return function(){return $n.apply(a,arguments)}}});var mi=m((AL,Sc)=>{"use strict";var gc=de(),Cv=gc({}.toString),Dv=gc("".slice);Sc.exports=function(a){return Dv(Cv(a),8,-1)}});var yc=m((wL,vc)=>{"use strict";var Bv=de(),Ov=Ee(),Vv=mi(),Ln=Object,_v=Bv("".split);vc.exports=Ov(function(){return!Ln("z").propertyIsEnumerable(0)})?function(a){return Vv(a)==="String"?_v(a,""):Ln(a)}:Ln});var bi=m((kL,Tc)=>{"use strict";Tc.exports=function(a){return a==null}});var ir=m((RL,Ic)=>{"use strict";var Nv=bi(),Fv=TypeError;Ic.exports=function(a){if(Nv(a))throw new Fv("Can't call method on "+a);return a}});var gi=m(($L,Ec)=>{"use strict";var Uv=yc(),qv=ir();Ec.exports=function(a){return Uv(qv(a))}});var Mn=m((LL,xc)=>{"use strict";xc.exports=function(){}});var Nt=m((ML,Pc)=>{"use strict";Pc.exports={}});var Y=m((Cn,Ac)=>{"use strict";var rr=function(a){return a&&a.Math===Math&&a};Ac.exports=rr(typeof globalThis=="object"&&globalThis)||rr(typeof window=="object"&&window)||rr(typeof self=="object"&&self)||rr(typeof global=="object"&&global)||rr(typeof Cn=="object"&&Cn)||function(){return this}()||Function("return this")()});var W=m((CL,wc)=>{"use strict";var Dn=typeof document=="object"&&document.all;wc.exports=typeof Dn=="undefined"&&Dn!==void 0?function(a){return typeof a=="function"||a===Dn}:function(a){return typeof a=="function"}});var $c=m((DL,Rc)=>{"use strict";var Hv=Y(),jv=W(),kc=Hv.WeakMap;Rc.exports=jv(kc)&&/native code/.test(String(kc))});var $e=m((BL,Lc)=>{"use strict";var Gv=W();Lc.exports=function(a){return typeof a=="object"?a!==null:Gv(a)}});var Le=m((OL,Mc)=>{"use strict";var Wv=Ee();Mc.exports=!Wv(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ga=m((VL,Dc)=>{"use strict";var Yv=Y(),Cc=$e(),Bn=Yv.document,Qv=Cc(Bn)&&Cc(Bn.createElement);Dc.exports=function(a){return Qv?Bn.createElement(a):{}}});var On=m((_L,Bc)=>{"use strict";var zv=Le(),Kv=Ee(),Jv=Ga();Bc.exports=!zv&&!Kv(function(){return Object.defineProperty(Jv("div"),"a",{get:function(){return 7}}).a!==7})});var Vn=m((NL,Oc)=>{"use strict";var Xv=Le(),Zv=Ee();Oc.exports=Xv&&Zv(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Ke=m((FL,Vc)=>{"use strict";var ey=$e(),ty=String,iy=TypeError;Vc.exports=function(a){if(ey(a))return a;throw new iy(ty(a)+" is not an object")}});var xe=m((UL,_c)=>{"use strict";var ry=tr(),Wa=Function.prototype.call;_c.exports=ry?Wa.bind(Wa):function(){return Wa.apply(Wa,arguments)}});var Ya=m((qL,Nc)=>{"use strict";Nc.exports={}});var rt=m((HL,Uc)=>{"use strict";var _n=Ya(),Nn=Y(),ay=W(),Fc=function(a){return ay(a)?a:void 0};Uc.exports=function(a,e){return arguments.length<2?Fc(_n[a])||Fc(Nn[a]):_n[a]&&_n[a][e]||Nn[a]&&Nn[a][e]}});var ar=m((jL,qc)=>{"use strict";var sy=de();qc.exports=sy({}.isPrototypeOf)});var Si=m((GL,Gc)=>{"use strict";var ny=Y(),Hc=ny.navigator,jc=Hc&&Hc.userAgent;Gc.exports=jc?String(jc):""});var Un=m((WL,Jc)=>{"use strict";var Kc=Y(),Fn=Si(),Wc=Kc.process,Yc=Kc.Deno,Qc=Wc&&Wc.versions||Yc&&Yc.version,zc=Qc&&Qc.v8,Ue,Qa;zc&&(Ue=zc.split("."),Qa=Ue[0]>0&&Ue[0]<4?1:+(Ue[0]+Ue[1]));!Qa&&Fn&&(Ue=Fn.match(/Edge\/(\d+)/),(!Ue||Ue[1]>=74)&&(Ue=Fn.match(/Chrome\/(\d+)/),Ue&&(Qa=+Ue[1])));Jc.exports=Qa});var qn=m((YL,Zc)=>{"use strict";var Xc=Un(),oy=Ee(),uy=Y(),ly=uy.String;Zc.exports=!!Object.getOwnPropertySymbols&&!oy(function(){var a=Symbol("symbol detection");return!ly(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Xc&&Xc<41})});var Hn=m((QL,ed)=>{"use strict";var cy=qn();ed.exports=cy&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var jn=m((zL,td)=>{"use strict";var dy=rt(),py=W(),hy=ar(),fy=Hn(),my=Object;td.exports=fy?function(a){return typeof a=="symbol"}:function(a){var e=dy("Symbol");return py(e)&&hy(e.prototype,my(a))}});var sr=m((KL,id)=>{"use strict";var by=String;id.exports=function(a){try{return by(a)}catch(e){return"Object"}}});var at=m((JL,rd)=>{"use strict";var gy=W(),Sy=sr(),vy=TypeError;rd.exports=function(a){if(gy(a))return a;throw new vy(Sy(a)+" is not a function")}});var nr=m((XL,ad)=>{"use strict";var yy=at(),Ty=bi();ad.exports=function(a,e){var t=a[e];return Ty(t)?void 0:yy(t)}});var nd=m((ZL,sd)=>{"use strict";var Gn=xe(),Wn=W(),Yn=$e(),Iy=TypeError;sd.exports=function(a,e){var t,i;if(e==="string"&&Wn(t=a.toString)&&!Yn(i=Gn(t,a))||Wn(t=a.valueOf)&&!Yn(i=Gn(t,a))||e!=="string"&&Wn(t=a.toString)&&!Yn(i=Gn(t,a)))return i;throw new Iy("Can't convert object to primitive value")}});var qe=m((eM,od)=>{"use strict";od.exports=!0});var cd=m((tM,ld)=>{"use strict";var ud=Y(),Ey=Object.defineProperty;ld.exports=function(a,e){try{Ey(ud,a,{value:e,configurable:!0,writable:!0})}catch(t){ud[a]=e}return e}});var or=m((iM,hd)=>{"use strict";var xy=qe(),Py=Y(),Ay=cd(),dd="__core-js_shared__",pd=hd.exports=Py[dd]||Ay(dd,{});(pd.versions||(pd.versions=[])).push({version:"3.38.0",mode:xy?"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 Qn=m((rM,md)=>{"use strict";var fd=or();md.exports=function(a,e){return fd[a]||(fd[a]=e||{})}});var ur=m((aM,bd)=>{"use strict";var wy=ir(),ky=Object;bd.exports=function(a){return ky(wy(a))}});var He=m((sM,gd)=>{"use strict";var Ry=de(),$y=ur(),Ly=Ry({}.hasOwnProperty);gd.exports=Object.hasOwn||function(e,t){return Ly($y(e),t)}});var zn=m((nM,Sd)=>{"use strict";var My=de(),Cy=0,Dy=Math.random(),By=My(1 .toString);Sd.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+By(++Cy+Dy,36)}});var se=m((oM,yd)=>{"use strict";var Oy=Y(),Vy=Qn(),vd=He(),_y=zn(),Ny=qn(),Fy=Hn(),vi=Oy.Symbol,Kn=Vy("wks"),Uy=Fy?vi.for||vi:vi&&vi.withoutSetter||_y;yd.exports=function(a){return vd(Kn,a)||(Kn[a]=Ny&&vd(vi,a)?vi[a]:Uy("Symbol."+a)),Kn[a]}});var xd=m((uM,Ed)=>{"use strict";var qy=xe(),Td=$e(),Id=jn(),Hy=nr(),jy=nd(),Gy=se(),Wy=TypeError,Yy=Gy("toPrimitive");Ed.exports=function(a,e){if(!Td(a)||Id(a))return a;var t=Hy(a,Yy),i;if(t){if(e===void 0&&(e="default"),i=qy(t,a,e),!Td(i)||Id(i))return i;throw new Wy("Can't convert object to primitive value")}return e===void 0&&(e="number"),jy(a,e)}});var Jn=m((lM,Pd)=>{"use strict";var Qy=xd(),zy=jn();Pd.exports=function(a){var e=Qy(a,"string");return zy(e)?e:e+""}});var Ft=m(wd=>{"use strict";var Ky=Le(),Jy=On(),Xy=Vn(),za=Ke(),Ad=Jn(),Zy=TypeError,Xn=Object.defineProperty,eT=Object.getOwnPropertyDescriptor,Zn="enumerable",eo="configurable",to="writable";wd.f=Ky?Xy?function(e,t,i){if(za(e),t=Ad(t),za(i),typeof e=="function"&&t==="prototype"&&"value"in i&&to in i&&!i[to]){var r=eT(e,t);r&&r[to]&&(e[t]=i.value,i={configurable:eo in i?i[eo]:r[eo],enumerable:Zn in i?i[Zn]:r[Zn],writable:!1})}return Xn(e,t,i)}:Xn:function(e,t,i){if(za(e),t=Ad(t),za(i),Jy)try{return Xn(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new Zy("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var lr=m((dM,kd)=>{"use strict";kd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var yi=m((pM,Rd)=>{"use strict";var tT=Le(),iT=Ft(),rT=lr();Rd.exports=tT?function(a,e,t){return iT.f(a,e,rT(1,t))}:function(a,e,t){return a[e]=t,a}});var Ka=m((hM,Ld)=>{"use strict";var aT=Qn(),sT=zn(),$d=aT("keys");Ld.exports=function(a){return $d[a]||($d[a]=sT(a))}});var Ja=m((fM,Md)=>{"use strict";Md.exports={}});var so=m((mM,Bd)=>{"use strict";var nT=$c(),Dd=Y(),oT=$e(),uT=yi(),io=He(),ro=or(),lT=Ka(),cT=Ja(),Cd="Object already initialized",ao=Dd.TypeError,dT=Dd.WeakMap,Xa,cr,Za,pT=function(a){return Za(a)?cr(a):Xa(a,{})},hT=function(a){return function(e){var t;if(!oT(e)||(t=cr(e)).type!==a)throw new ao("Incompatible receiver, "+a+" required");return t}};nT||ro.state?(je=ro.state||(ro.state=new dT),je.get=je.get,je.has=je.has,je.set=je.set,Xa=function(a,e){if(je.has(a))throw new ao(Cd);return e.facade=a,je.set(a,e),e},cr=function(a){return je.get(a)||{}},Za=function(a){return je.has(a)}):(Ut=lT("state"),cT[Ut]=!0,Xa=function(a,e){if(io(a,Ut))throw new ao(Cd);return e.facade=a,uT(a,Ut,e),e},cr=function(a){return io(a,Ut)?a[Ut]:{}},Za=function(a){return io(a,Ut)});var je,Ut;Bd.exports={set:Xa,get:cr,has:Za,enforce:pT,getterFor:hT}});var no=m((bM,Nd)=>{"use strict";var fT=tr(),_d=Function.prototype,Od=_d.apply,Vd=_d.call;Nd.exports=typeof Reflect=="object"&&Reflect.apply||(fT?Vd.bind(Od):function(){return Vd.apply(Od,arguments)})});var oo=m((gM,Fd)=>{"use strict";var mT=mi(),bT=de();Fd.exports=function(a){if(mT(a)==="Function")return bT(a)}});var jd=m(Hd=>{"use strict";var Ud={}.propertyIsEnumerable,qd=Object.getOwnPropertyDescriptor,gT=qd&&!Ud.call({1:2},1);Hd.f=gT?function(e){var t=qd(this,e);return!!t&&t.enumerable}:Ud});var Yd=m(Wd=>{"use strict";var ST=Le(),vT=xe(),yT=jd(),TT=lr(),IT=gi(),ET=Jn(),xT=He(),PT=On(),Gd=Object.getOwnPropertyDescriptor;Wd.f=ST?Gd:function(e,t){if(e=IT(e),t=ET(t),PT)try{return Gd(e,t)}catch(i){}if(xT(e,t))return TT(!vT(yT.f,e,t),e[t])}});var uo=m((yM,Qd)=>{"use strict";var AT=Ee(),wT=W(),kT=/#|\.prototype\./,dr=function(a,e){var t=$T[RT(a)];return t===MT?!0:t===LT?!1:wT(e)?AT(e):!!e},RT=dr.normalize=function(a){return String(a).replace(kT,".").toLowerCase()},$T=dr.data={},LT=dr.NATIVE="N",MT=dr.POLYFILL="P";Qd.exports=dr});var pr=m((TM,Kd)=>{"use strict";var zd=oo(),CT=at(),DT=tr(),BT=zd(zd.bind);Kd.exports=function(a,e){return CT(a),e===void 0?a:DT?BT(a,e):function(){return a.apply(e,arguments)}}});var Me=m((IM,Xd)=>{"use strict";var hr=Y(),OT=no(),VT=oo(),_T=W(),NT=Yd().f,FT=uo(),Ti=Ya(),UT=pr(),Ii=yi(),Jd=He();or();var qT=function(a){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,i)}return new a(t,i,r)}return OT(a,this,arguments)};return e.prototype=a.prototype,e};Xd.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?hr:r?hr[t]:hr[t]&&hr[t].prototype,o=i?Ti:Ti[t]||Ii(Ti,t,{})[t],u=o.prototype,l,c,d,h,p,f,b,g,y;for(h in e)l=FT(i?h:t+(r?".":"#")+h,a.forced),c=!l&&n&&Jd(n,h),f=o[h],c&&(a.dontCallGetSet?(y=NT(n,h),b=y&&y.value):b=n[h]),p=c&&b?b:e[h],!(!l&&!s&&typeof f==typeof p)&&(a.bind&&c?g=UT(p,hr):a.wrap&&c?g=qT(p):s&&_T(p)?g=VT(p):g=p,(a.sham||p&&p.sham||f&&f.sham)&&Ii(g,"sham",!0),Ii(o,h,g),s&&(d=t+"Prototype",Jd(Ti,d)||Ii(Ti,d,{}),Ii(Ti[d],h,p),a.real&&u&&(l||!u[h])&&Ii(u,h,p)))}});var tp=m((EM,ep)=>{"use strict";var lo=Le(),HT=He(),Zd=Function.prototype,jT=lo&&Object.getOwnPropertyDescriptor,co=HT(Zd,"name"),GT=co&&function(){}.name==="something",WT=co&&(!lo||lo&&jT(Zd,"name").configurable);ep.exports={EXISTS:co,PROPER:GT,CONFIGURABLE:WT}});var rp=m((xM,ip)=>{"use strict";var YT=Math.ceil,QT=Math.floor;ip.exports=Math.trunc||function(e){var t=+e;return(t>0?QT:YT)(t)}});var es=m((PM,ap)=>{"use strict";var zT=rp();ap.exports=function(a){var e=+a;return e!==e||e===0?0:zT(e)}});var np=m((AM,sp)=>{"use strict";var KT=es(),JT=Math.max,XT=Math.min;sp.exports=function(a,e){var t=KT(a);return t<0?JT(t+e,0):XT(t,e)}});var up=m((wM,op)=>{"use strict";var ZT=es(),eI=Math.min;op.exports=function(a){var e=ZT(a);return e>0?eI(e,9007199254740991):0}});var ts=m((kM,lp)=>{"use strict";var tI=up();lp.exports=function(a){return tI(a.length)}});var pp=m((RM,dp)=>{"use strict";var iI=gi(),rI=np(),aI=ts(),cp=function(a){return function(e,t,i){var r=iI(e),s=aI(r);if(s===0)return!a&&-1;var n=rI(i,s),o;if(a&&t!==t){for(;s>n;)if(o=r[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in r)&&r[n]===t)return a||n||0;return!a&&-1}};dp.exports={includes:cp(!0),indexOf:cp(!1)}});var mp=m(($M,fp)=>{"use strict";var sI=de(),po=He(),nI=gi(),oI=pp().indexOf,uI=Ja(),hp=sI([].push);fp.exports=function(a,e){var t=nI(a),i=0,r=[],s;for(s in t)!po(uI,s)&&po(t,s)&&hp(r,s);for(;e.length>i;)po(t,s=e[i++])&&(~oI(r,s)||hp(r,s));return r}});var ho=m((LM,bp)=>{"use strict";bp.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Sp=m((MM,gp)=>{"use strict";var lI=mp(),cI=ho();gp.exports=Object.keys||function(e){return lI(e,cI)}});var yp=m(vp=>{"use strict";var dI=Le(),pI=Vn(),hI=Ft(),fI=Ke(),mI=gi(),bI=Sp();vp.f=dI&&!pI?Object.defineProperties:function(e,t){fI(e);for(var i=mI(t),r=bI(t),s=r.length,n=0,o;s>n;)hI.f(e,o=r[n++],i[o]);return e}});var fo=m((DM,Tp)=>{"use strict";var gI=rt();Tp.exports=gI("document","documentElement")});var So=m((BM,kp)=>{"use strict";var SI=Ke(),vI=yp(),Ip=ho(),yI=Ja(),TI=fo(),II=Ga(),EI=Ka(),Ep=">",xp="<",bo="prototype",go="script",Ap=EI("IE_PROTO"),mo=function(){},wp=function(a){return xp+go+Ep+a+xp+"/"+go+Ep},Pp=function(a){a.write(wp("")),a.close();var e=a.parentWindow.Object;return a=null,e},xI=function(){var a=II("iframe"),e="java"+go+":",t;return a.style.display="none",TI.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(wp("document.F=Object")),t.close(),t.F},is,rs=function(){try{is=new ActiveXObject("htmlfile")}catch(e){}rs=typeof document!="undefined"?document.domain&&is?Pp(is):xI():Pp(is);for(var a=Ip.length;a--;)delete rs[bo][Ip[a]];return rs()};yI[Ap]=!0;kp.exports=Object.create||function(e,t){var i;return e!==null?(mo[bo]=SI(e),i=new mo,mo[bo]=null,i[Ap]=e):i=rs(),t===void 0?i:vI.f(i,t)}});var $p=m((OM,Rp)=>{"use strict";var PI=Ee();Rp.exports=!PI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var yo=m((VM,Mp)=>{"use strict";var AI=He(),wI=W(),kI=ur(),RI=Ka(),$I=$p(),Lp=RI("IE_PROTO"),vo=Object,LI=vo.prototype;Mp.exports=$I?vo.getPrototypeOf:function(a){var e=kI(a);if(AI(e,Lp))return e[Lp];var t=e.constructor;return wI(t)&&e instanceof t?t.prototype:e instanceof vo?LI:null}});var Ei=m((_M,Cp)=>{"use strict";var MI=yi();Cp.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:MI(a,e,t),a}});var xo=m((NM,Op)=>{"use strict";var CI=Ee(),DI=W(),BI=$e(),OI=So(),Dp=yo(),VI=Ei(),_I=se(),NI=qe(),Eo=_I("iterator"),Bp=!1,st,To,Io;[].keys&&(Io=[].keys(),"next"in Io?(To=Dp(Dp(Io)),To!==Object.prototype&&(st=To)):Bp=!0);var FI=!BI(st)||CI(function(){var a={};return st[Eo].call(a)!==a});FI?st={}:NI&&(st=OI(st));DI(st[Eo])||VI(st,Eo,function(){return this});Op.exports={IteratorPrototype:st,BUGGY_SAFARI_ITERATORS:Bp}});var as=m((FM,_p)=>{"use strict";var UI=se(),qI=UI("toStringTag"),Vp={};Vp[qI]="z";_p.exports=String(Vp)==="[object z]"});var fr=m((UM,Np)=>{"use strict";var HI=as(),jI=W(),ss=mi(),GI=se(),WI=GI("toStringTag"),YI=Object,QI=ss(function(){return arguments}())==="Arguments",zI=function(a,e){try{return a[e]}catch(t){}};Np.exports=HI?ss:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=zI(e=YI(a),WI))=="string"?t:QI?ss(e):(i=ss(e))==="Object"&&jI(e.callee)?"Arguments":i}});var Up=m((qM,Fp)=>{"use strict";var KI=as(),JI=fr();Fp.exports=KI?{}.toString:function(){return"[object "+JI(this)+"]"}});var mr=m((HM,Hp)=>{"use strict";var XI=as(),ZI=Ft().f,eE=yi(),tE=He(),iE=Up(),rE=se(),qp=rE("toStringTag");Hp.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(tE(r,qp)||ZI(r,qp,{configurable:!0,value:e}),i&&!XI&&eE(r,"toString",iE))}});var Gp=m((jM,jp)=>{"use strict";var aE=xo().IteratorPrototype,sE=So(),nE=lr(),oE=mr(),uE=Nt(),lE=function(){return this};jp.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=sE(aE,{next:nE(+!i,t)}),oE(a,r,!1,!0),uE[r]=lE,a}});var Yp=m((GM,Wp)=>{"use strict";var cE=de(),dE=at();Wp.exports=function(a,e,t){try{return cE(dE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(i){}}});var zp=m((WM,Qp)=>{"use strict";var pE=$e();Qp.exports=function(a){return pE(a)||a===null}});var Jp=m((YM,Kp)=>{"use strict";var hE=zp(),fE=String,mE=TypeError;Kp.exports=function(a){if(hE(a))return a;throw new mE("Can't set "+fE(a)+" as a prototype")}});var Po=m((QM,Xp)=>{"use strict";var bE=Yp(),gE=$e(),SE=ir(),vE=Jp();Xp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=bE(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(i){}return function(r,s){return SE(r),vE(s),gE(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var lh=m((zM,uh)=>{"use strict";var yE=Me(),TE=xe(),ns=qe(),nh=tp(),IE=W(),EE=Gp(),Zp=yo(),eh=Po(),xE=mr(),PE=yi(),Ao=Ei(),AE=se(),th=Nt(),oh=xo(),wE=nh.PROPER,kE=nh.CONFIGURABLE,ih=oh.IteratorPrototype,os=oh.BUGGY_SAFARI_ITERATORS,br=AE("iterator"),rh="keys",gr="values",ah="entries",sh=function(){return this};uh.exports=function(a,e,t,i,r,s,n){EE(t,e,i);var o=function(y){if(y===r&&h)return h;if(!os&&y&&y in c)return c[y];switch(y){case rh:return function(){return new t(this,y)};case gr:return function(){return new t(this,y)};case ah:return function(){return new t(this,y)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[br]||c["@@iterator"]||r&&c[r],h=!os&&d||o(r),p=e==="Array"&&c.entries||d,f,b,g;if(p&&(f=Zp(p.call(new a)),f!==Object.prototype&&f.next&&(!ns&&Zp(f)!==ih&&(eh?eh(f,ih):IE(f[br])||Ao(f,br,sh)),xE(f,u,!0,!0),ns&&(th[u]=sh))),wE&&r===gr&&d&&d.name!==gr&&(!ns&&kE?PE(c,"name",gr):(l=!0,h=function(){return TE(d,this)})),r)if(b={values:o(gr),keys:s?h:o(rh),entries:o(ah)},n)for(g in b)(os||l||!(g in c))&&Ao(c,g,b[g]);else yE({target:e,proto:!0,forced:os||l},b);return(!ns||n)&&c[br]!==h&&Ao(c,br,h,{name:r}),th[e]=h,b}});var dh=m((KM,ch)=>{"use strict";ch.exports=function(a,e){return{value:a,done:e}}});var ko=m((JM,bh)=>{"use strict";var RE=gi(),wo=Mn(),ph=Nt(),fh=so(),$E=Ft().f,LE=lh(),us=dh(),ME=qe(),CE=Le(),mh="Array Iterator",DE=fh.set,BE=fh.getterFor(mh);bh.exports=LE(Array,"Array",function(a,e){DE(this,{type:mh,target:RE(a),index:0,kind:e})},function(){var a=BE(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,us(void 0,!0);switch(a.kind){case"keys":return us(t,!1);case"values":return us(e[t],!1)}return us([t,e[t]],!1)},"values");var hh=ph.Arguments=ph.Array;wo("keys");wo("values");wo("entries");if(!ME&&CE&&hh.name!=="values")try{$E(hh,"name",{value:"values"})}catch(a){}});var Sh=m((XM,gh)=>{"use strict";var OE=se(),VE=Nt(),_E=OE("iterator"),NE=Array.prototype;gh.exports=function(a){return a!==void 0&&(VE.Array===a||NE[_E]===a)}});var Ro=m((ZM,yh)=>{"use strict";var FE=fr(),vh=nr(),UE=bi(),qE=Nt(),HE=se(),jE=HE("iterator");yh.exports=function(a){if(!UE(a))return vh(a,jE)||vh(a,"@@iterator")||qE[FE(a)]}});var Ih=m((eC,Th)=>{"use strict";var GE=xe(),WE=at(),YE=Ke(),QE=sr(),zE=Ro(),KE=TypeError;Th.exports=function(a,e){var t=arguments.length<2?zE(a):e;if(WE(t))return YE(GE(t,a));throw new KE(QE(a)+" is not iterable")}});var Ph=m((tC,xh)=>{"use strict";var JE=xe(),Eh=Ke(),XE=nr();xh.exports=function(a,e,t){var i,r;Eh(a);try{if(i=XE(a,"return"),!i){if(e==="throw")throw t;return t}i=JE(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return Eh(i),t}});var cs=m((iC,Rh)=>{"use strict";var ZE=pr(),ex=xe(),tx=Ke(),ix=sr(),rx=Sh(),ax=ts(),Ah=ar(),sx=Ih(),nx=Ro(),wh=Ph(),ox=TypeError,ls=function(a,e){this.stopped=a,this.result=e},kh=ls.prototype;Rh.exports=function(a,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=ZE(e,i),l,c,d,h,p,f,b,g=function(I){return l&&wh(l,"normal",I),new ls(!0,I)},y=function(I){return r?(tx(I),o?u(I[0],I[1],g):u(I[0],I[1])):o?u(I,g):u(I)};if(s)l=a.iterator;else if(n)l=a;else{if(c=nx(a),!c)throw new ox(ix(a)+" is not iterable");if(rx(c)){for(d=0,h=ax(a);h>d;d++)if(p=y(a[d]),p&&Ah(kh,p))return p;return new ls(!1)}l=sx(a,c)}for(f=s?a.next:l.next;!(b=ex(f,l)).done;){try{p=y(b.value)}catch(I){wh(l,"throw",I)}if(typeof p=="object"&&p&&Ah(kh,p))return p}return new ls(!1)}});var Lh=m((rC,$h)=>{"use strict";var ux=Le(),lx=Ft(),cx=lr();$h.exports=function(a,e,t){ux?lx.f(a,e,cx(0,t)):a[e]=t}});var Mh=m(()=>{"use strict";var dx=Me(),px=cs(),hx=Lh();dx({target:"Object",stat:!0},{fromEntries:function(e){var t={};return px(e,function(i,r){hx(t,i,r)},{AS_ENTRIES:!0}),t}})});var Dh=m((nC,Ch)=>{"use strict";ko();Mh();var fx=Ya();Ch.exports=fx.Object.fromEntries});var Oh=m((oC,Bh)=>{"use strict";Bh.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";ko();var mx=Oh(),bx=Y(),gx=mr(),Vh=Nt();for(ds in mx)gx(bx[ds],ds),Vh[ds]=Vh.Array;var ds});var Fh=m((cC,Nh)=>{"use strict";var Sx=Dh();_h();Nh.exports=Sx});var $o=m((dC,Uh)=>{"use strict";var vx=Fh();Uh.exports=vx});var qh=m(()=>{"use strict"});var Lo=m((fC,Hh)=>{"use strict";var Sr=Y(),yx=Si(),Tx=mi(),ps=function(a){return yx.slice(0,a.length)===a};Hh.exports=function(){return ps("Bun/")?"BUN":ps("Cloudflare-Workers")?"CLOUDFLARE":ps("Deno/")?"DENO":ps("Node.js/")?"NODE":Sr.Bun&&typeof Bun.version=="string"?"BUN":Sr.Deno&&typeof Deno.version=="object"?"DENO":Tx(Sr.process)==="process"?"NODE":Sr.window&&Sr.document?"BROWSER":"REST"}()});var hs=m((mC,jh)=>{"use strict";var Ix=Lo();jh.exports=Ix==="NODE"});var Wh=m((bC,Gh)=>{"use strict";var Ex=Ft();Gh.exports=function(a,e,t){return Ex.f(a,e,t)}});var zh=m((gC,Qh)=>{"use strict";var xx=rt(),Px=Wh(),Ax=se(),wx=Le(),Yh=Ax("species");Qh.exports=function(a){var e=xx(a);wx&&e&&!e[Yh]&&Px(e,Yh,{configurable:!0,get:function(){return this}})}});var Jh=m((SC,Kh)=>{"use strict";var kx=ar(),Rx=TypeError;Kh.exports=function(a,e){if(kx(e,a))return a;throw new Rx("Incorrect invocation")}});var Co=m((vC,Xh)=>{"use strict";var $x=de(),Lx=W(),Mo=or(),Mx=$x(Function.toString);Lx(Mo.inspectSource)||(Mo.inspectSource=function(a){return Mx(a)});Xh.exports=Mo.inspectSource});var sf=m((yC,af)=>{"use strict";var Cx=de(),Dx=Ee(),Zh=W(),Bx=fr(),Ox=rt(),Vx=Co(),ef=function(){},tf=Ox("Reflect","construct"),Do=/^\s*(?:class|function)\b/,_x=Cx(Do.exec),Nx=!Do.test(ef),vr=function(e){if(!Zh(e))return!1;try{return tf(ef,[],e),!0}catch(t){return!1}},rf=function(e){if(!Zh(e))return!1;switch(Bx(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Nx||!!_x(Do,Vx(e))}catch(t){return!0}};rf.sham=!0;af.exports=!tf||Dx(function(){var a;return vr(vr.call)||!vr(Object)||!vr(function(){a=!0})||a})?rf:vr});var of=m((TC,nf)=>{"use strict";var Fx=sf(),Ux=sr(),qx=TypeError;nf.exports=function(a){if(Fx(a))return a;throw new qx(Ux(a)+" is not a constructor")}});var Bo=m((IC,lf)=>{"use strict";var uf=Ke(),Hx=of(),jx=bi(),Gx=se(),Wx=Gx("species");lf.exports=function(a,e){var t=uf(a).constructor,i;return t===void 0||jx(i=uf(t)[Wx])?e:Hx(i)}});var df=m((EC,cf)=>{"use strict";var Yx=de();cf.exports=Yx([].slice)});var hf=m((xC,pf)=>{"use strict";var Qx=TypeError;pf.exports=function(a,e){if(a<e)throw new Qx("Not enough arguments");return a}});var Oo=m((PC,ff)=>{"use strict";var zx=Si();ff.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(zx)});var Go=m((AC,Ef)=>{"use strict";var Pe=Y(),Kx=no(),Jx=pr(),mf=W(),Xx=He(),If=Ee(),bf=fo(),Zx=df(),gf=Ga(),eP=hf(),tP=Oo(),iP=hs(),qo=Pe.setImmediate,Ho=Pe.clearImmediate,rP=Pe.process,Vo=Pe.Dispatch,aP=Pe.Function,Sf=Pe.MessageChannel,sP=Pe.String,_o=0,yr={},vf="onreadystatechange",Tr,qt,No,Fo;If(function(){Tr=Pe.location});var jo=function(a){if(Xx(yr,a)){var e=yr[a];delete yr[a],e()}},Uo=function(a){return function(){jo(a)}},yf=function(a){jo(a.data)},Tf=function(a){Pe.postMessage(sP(a),Tr.protocol+"//"+Tr.host)};(!qo||!Ho)&&(qo=function(e){eP(arguments.length,1);var t=mf(e)?e:aP(e),i=Zx(arguments,1);return yr[++_o]=function(){Kx(t,void 0,i)},qt(_o),_o},Ho=function(e){delete yr[e]},iP?qt=function(a){rP.nextTick(Uo(a))}:Vo&&Vo.now?qt=function(a){Vo.now(Uo(a))}:Sf&&!tP?(No=new Sf,Fo=No.port2,No.port1.onmessage=yf,qt=Jx(Fo.postMessage,Fo)):Pe.addEventListener&&mf(Pe.postMessage)&&!Pe.importScripts&&Tr&&Tr.protocol!=="file:"&&!If(Tf)?(qt=Tf,Pe.addEventListener("message",yf,!1)):vf in gf("script")?qt=function(a){bf.appendChild(gf("script"))[vf]=function(){bf.removeChild(this),jo(a)}}:qt=function(a){setTimeout(Uo(a),0)});Ef.exports={set:qo,clear:Ho}});var Af=m((wC,Pf)=>{"use strict";var xf=Y(),nP=Le(),oP=Object.getOwnPropertyDescriptor;Pf.exports=function(a){if(!nP)return xf[a];var e=oP(xf,a);return e&&e.value}});var Wo=m((kC,kf)=>{"use strict";var wf=function(){this.head=null,this.tail=null};wf.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}}};kf.exports=wf});var $f=m((RC,Rf)=>{"use strict";var uP=Si();Rf.exports=/ipad|iphone|ipod/i.test(uP)&&typeof Pebble!="undefined"});var Mf=m(($C,Lf)=>{"use strict";var lP=Si();Lf.exports=/web0s(?!.*chrome)/i.test(lP)});var Nf=m((LC,_f)=>{"use strict";var Pi=Y(),cP=Af(),Cf=pr(),Yo=Go().set,dP=Wo(),pP=Oo(),hP=$f(),fP=Mf(),Qo=hs(),Df=Pi.MutationObserver||Pi.WebKitMutationObserver,Bf=Pi.document,Of=Pi.process,fs=Pi.Promise,Jo=cP("queueMicrotask"),xi,zo,Ko,ms,Vf;Jo||(Ir=new dP,Er=function(){var a,e;for(Qo&&(a=Of.domain)&&a.exit();e=Ir.get();)try{e()}catch(t){throw Ir.head&&xi(),t}a&&a.enter()},!pP&&!Qo&&!fP&&Df&&Bf?(zo=!0,Ko=Bf.createTextNode(""),new Df(Er).observe(Ko,{characterData:!0}),xi=function(){Ko.data=zo=!zo}):!hP&&fs&&fs.resolve?(ms=fs.resolve(void 0),ms.constructor=fs,Vf=Cf(ms.then,ms),xi=function(){Vf(Er)}):Qo?xi=function(){Of.nextTick(Er)}:(Yo=Cf(Yo,Pi),xi=function(){Yo(Er)}),Jo=function(a){Ir.head||xi(),Ir.add(a)});var Ir,Er;_f.exports=Jo});var Uf=m((MC,Ff)=>{"use strict";Ff.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var bs=m((CC,qf)=>{"use strict";qf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Ht=m((DC,Hf)=>{"use strict";var mP=Y();Hf.exports=mP.Promise});var Ai=m((BC,Yf)=>{"use strict";var bP=Y(),xr=Ht(),gP=W(),SP=uo(),vP=Co(),yP=se(),jf=Lo(),TP=qe(),Xo=Un(),Gf=xr&&xr.prototype,IP=yP("species"),Zo=!1,Wf=gP(bP.PromiseRejectionEvent),EP=SP("Promise",function(){var a=vP(xr),e=a!==String(xr);if(!e&&Xo===66||TP&&!(Gf.catch&&Gf.finally))return!0;if(!Xo||Xo<51||!/native code/.test(a)){var t=new xr(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[IP]=i,Zo=t.then(function(){})instanceof i,!Zo)return!0}return!e&&(jf==="BROWSER"||jf==="DENO")&&!Wf});Yf.exports={CONSTRUCTOR:EP,REJECTION_EVENT:Wf,SUBCLASSING:Zo}});var wi=m((OC,zf)=>{"use strict";var Qf=at(),xP=TypeError,PP=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new xP("Bad Promise constructor");e=i,t=r}),this.resolve=Qf(e),this.reject=Qf(t)};zf.exports.f=function(a){return new PP(a)}});var fm=m(()=>{"use strict";var AP=Me(),wP=qe(),ys=hs(),Et=Y(),Li=xe(),Kf=Ei(),Jf=Po(),kP=mr(),RP=zh(),$P=at(),vs=W(),LP=$e(),MP=Jh(),CP=Bo(),im=Go().set,au=Nf(),DP=Uf(),BP=bs(),OP=Wo(),rm=so(),Ts=Ht(),su=Ai(),am=wi(),Is="Promise",sm=su.CONSTRUCTOR,VP=su.REJECTION_EVENT,_P=su.SUBCLASSING,eu=rm.getterFor(Is),NP=rm.set,ki=Ts&&Ts.prototype,jt=Ts,gs=ki,nm=Et.TypeError,tu=Et.document,nu=Et.process,iu=am.f,FP=iu,UP=!!(tu&&tu.createEvent&&Et.dispatchEvent),om="unhandledrejection",qP="rejectionhandled",Xf=0,um=1,HP=2,ou=1,lm=2,Ss,Zf,jP,em,cm=function(a){var e;return LP(a)&&vs(e=a.then)?e:!1},dm=function(a,e){var t=e.value,i=e.state===um,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{r?(i||(e.rejection===lm&&WP(e),e.rejection=ou),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),c=!0)),u===a.promise?n(new nm("Promise-chain cycle")):(l=cm(u))?Li(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},pm=function(a,e){a.notified||(a.notified=!0,au(function(){for(var t=a.reactions,i;i=t.get();)dm(i,a);a.notified=!1,e&&!a.rejection&&GP(a)}))},hm=function(a,e,t){var i,r;UP?(i=tu.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),Et.dispatchEvent(i)):i={promise:e,reason:t},!VP&&(r=Et["on"+a])?r(i):a===om&&DP("Unhandled promise rejection",t)},GP=function(a){Li(im,Et,function(){var e=a.facade,t=a.value,i=tm(a),r;if(i&&(r=BP(function(){ys?nu.emit("unhandledRejection",t,e):hm(om,e,t)}),a.rejection=ys||tm(a)?lm:ou,r.error))throw r.value})},tm=function(a){return a.rejection!==ou&&!a.parent},WP=function(a){Li(im,Et,function(){var e=a.facade;ys?nu.emit("rejectionHandled",e):hm(qP,e,a.value)})},Ri=function(a,e,t){return function(i){a(e,i,t)}},$i=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=HP,pm(a,!0))},ru=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new nm("Promise can't be resolved itself");var i=cm(e);i?au(function(){var r={done:!1};try{Li(i,e,Ri(ru,r,a),Ri($i,r,a))}catch(s){$i(r,s,a)}}):(a.value=e,a.state=um,pm(a,!1))}catch(r){$i({done:!1},r,a)}}};if(sm&&(jt=function(e){MP(this,gs),$P(e),Li(Ss,this);var t=eu(this);try{e(Ri(ru,t),Ri($i,t))}catch(i){$i(t,i)}},gs=jt.prototype,Ss=function(e){NP(this,{type:Is,done:!1,notified:!1,parent:!1,reactions:new OP,rejection:!1,state:Xf,value:void 0})},Ss.prototype=Kf(gs,"then",function(e,t){var i=eu(this),r=iu(CP(this,jt));return i.parent=!0,r.ok=vs(e)?e:!0,r.fail=vs(t)&&t,r.domain=ys?nu.domain:void 0,i.state===Xf?i.reactions.add(r):au(function(){dm(r,i)}),r.promise}),Zf=function(){var a=new Ss,e=eu(a);this.promise=a,this.resolve=Ri(ru,e),this.reject=Ri($i,e)},am.f=iu=function(a){return a===jt||a===jP?new Zf(a):FP(a)},!wP&&vs(Ts)&&ki!==Object.prototype)){em=ki.then,_P||Kf(ki,"then",function(e,t){var i=this;return new jt(function(r,s){Li(em,i,r,s)}).then(e,t)},{unsafe:!0});try{delete ki.constructor}catch(a){}Jf&&Jf(ki,gs)}AP({global:!0,constructor:!0,wrap:!0,forced:sm},{Promise:jt});kP(jt,Is,!1,!0);RP(Is)});var vm=m((NC,Sm)=>{"use strict";var YP=se(),bm=YP("iterator"),gm=!1;try{mm=0,uu={next:function(){return{done:!!mm++}},return:function(){gm=!0}},uu[bm]=function(){return this},Array.from(uu,function(){throw 2})}catch(a){}var mm,uu;Sm.exports=function(a,e){try{if(!e&&!gm)return!1}catch(r){return!1}var t=!1;try{var i={};i[bm]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch(r){}return t}});var lu=m((FC,ym)=>{"use strict";var QP=Ht(),zP=vm(),KP=Ai().CONSTRUCTOR;ym.exports=KP||!zP(function(a){QP.all(a).then(void 0,function(){})})});var Tm=m(()=>{"use strict";var JP=Me(),XP=xe(),ZP=at(),eA=wi(),tA=bs(),iA=cs(),rA=lu();JP({target:"Promise",stat:!0,forced:rA},{all:function(e){var t=this,i=eA.f(t),r=i.resolve,s=i.reject,n=tA(function(){var o=ZP(t.resolve),u=[],l=0,c=1;iA(e,function(d){var h=l++,p=!1;c++,XP(o,t,d).then(function(f){p||(p=!0,u[h]=f,--c||r(u))},s)}),--c||r(u)});return n.error&&s(n.value),i.promise}})});var Em=m(()=>{"use strict";var aA=Me(),sA=qe(),nA=Ai().CONSTRUCTOR,du=Ht(),oA=rt(),uA=W(),lA=Ei(),Im=du&&du.prototype;aA({target:"Promise",proto:!0,forced:nA,real:!0},{catch:function(a){return this.then(void 0,a)}});!sA&&uA(du)&&(cu=oA("Promise").prototype.catch,Im.catch!==cu&&lA(Im,"catch",cu,{unsafe:!0}));var cu});var xm=m(()=>{"use strict";var cA=Me(),dA=xe(),pA=at(),hA=wi(),fA=bs(),mA=cs(),bA=lu();cA({target:"Promise",stat:!0,forced:bA},{race:function(e){var t=this,i=hA.f(t),r=i.reject,s=fA(function(){var n=pA(t.resolve);mA(e,function(o){dA(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var Pm=m(()=>{"use strict";var gA=Me(),SA=wi(),vA=Ai().CONSTRUCTOR;gA({target:"Promise",stat:!0,forced:vA},{reject:function(e){var t=SA.f(this),i=t.reject;return i(e),t.promise}})});var pu=m((zC,Am)=>{"use strict";var yA=Ke(),TA=$e(),IA=wi();Am.exports=function(a,e){if(yA(a),TA(e)&&e.constructor===a)return e;var t=IA.f(a),i=t.resolve;return i(e),t.promise}});var Rm=m(()=>{"use strict";var EA=Me(),xA=rt(),wm=qe(),PA=Ht(),km=Ai().CONSTRUCTOR,AA=pu(),wA=xA("Promise"),kA=wm&&!km;EA({target:"Promise",stat:!0,forced:wm||km},{resolve:function(e){return AA(kA&&this===wA?PA:this,e)}})});var $m=m(()=>{"use strict";fm();Tm();Em();xm();Pm();Rm()});var Dm=m(()=>{"use strict";var RA=Me(),$A=qe(),Es=Ht(),LA=Ee(),Mm=rt(),Cm=W(),MA=Bo(),Lm=pu(),CA=Ei(),fu=Es&&Es.prototype,DA=!!Es&&LA(function(){fu.finally.call({then:function(){}},function(){})});RA({target:"Promise",proto:!0,real:!0,forced:DA},{finally:function(a){var e=MA(this,Mm("Promise")),t=Cm(a);return this.then(t?function(i){return Lm(e,a()).then(function(){return i})}:a,t?function(i){return Lm(e,a()).then(function(){throw i})}:a)}});!$A&&Cm(Es)&&(hu=Mm("Promise").prototype.finally,fu.finally!==hu&&CA(fu,"finally",hu,{unsafe:!0}));var hu});var xs=m((iD,Bm)=>{"use strict";var BA=rt();Bm.exports=BA});var Vm=m((rD,Om)=>{"use strict";qh();$m();Dm();var OA=xs();Om.exports=OA("Promise","finally")});var Nm=m((aD,_m)=>{"use strict";var VA=Vm();_m.exports=VA});var Ps=m((sD,Fm)=>{"use strict";var _A=Nm();Fm.exports=_A});var db=m(()=>{"use strict";var hw=Me(),fw=ur(),mw=ts(),bw=es(),gw=Mn();hw({target:"Array",proto:!0},{at:function(e){var t=fw(this),i=mw(t),r=bw(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});gw("at")});var hb=m((f0,pb)=>{"use strict";db();var Sw=xs();pb.exports=Sw("Array","at")});var mb=m((m0,fb)=>{"use strict";var vw=hb();fb.exports=vw});var Di=m((b0,bb)=>{"use strict";var yw=mb();bb.exports=yw});var Tg=m(()=>{"use strict"});var Ig=m(()=>{"use strict"});var xg=m((g_,Eg)=>{"use strict";var wk=$e(),kk=mi(),Rk=se(),$k=Rk("match");Eg.exports=function(a){var e;return wk(a)&&((e=a[$k])!==void 0?!!e:kk(a)==="RegExp")}});var Ag=m((S_,Pg)=>{"use strict";var Lk=fr(),Mk=String;Pg.exports=function(a){if(Lk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return Mk(a)}});var kg=m((v_,wg)=>{"use strict";var Ck=Ke();wg.exports=function(){var a=Ck(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 Lg=m((y_,$g)=>{"use strict";var Dk=xe(),Bk=He(),Ok=ar(),Vk=kg(),Rg=RegExp.prototype;$g.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in Rg)&&!Bk(a,"flags")&&Ok(Rg,a)?Dk(Vk,a):e}});var Cg=m((T_,Mg)=>{"use strict";var ju=de(),_k=ur(),Nk=Math.floor,qu=ju("".charAt),Fk=ju("".replace),Hu=ju("".slice),Uk=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,qk=/\$([$&'`]|\d{1,2})/g;Mg.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=qk;return r!==void 0&&(r=_k(r),u=Uk),Fk(s,u,function(l,c){var d;switch(qu(c,0)){case"$":return"$";case"&":return a;case"`":return Hu(e,0,t);case"'":return Hu(e,n);case"<":d=r[Hu(c,1,-1)];break;default:var h=+c;if(h===0)return l;if(h>o){var p=Nk(h/10);return p===0?l:p<=o?i[p-1]===void 0?qu(c,1):i[p-1]+qu(c,1):l}d=i[h-1]}return d===void 0?"":d})}});var Og=m(()=>{"use strict";var Hk=Me(),jk=xe(),Wu=de(),Dg=ir(),Gk=W(),Wk=bi(),Yk=xg(),Hi=Ag(),Qk=nr(),zk=Lg(),Kk=Cg(),Jk=se(),Xk=qe(),Zk=Jk("replace"),eR=TypeError,Gu=Wu("".indexOf),tR=Wu("".replace),Bg=Wu("".slice),iR=Math.max;Hk({target:"String",proto:!0},{replaceAll:function(e,t){var i=Dg(this),r,s,n,o,u,l,c,d,h,p,f=0,b="";if(!Wk(e)){if(r=Yk(e),r&&(s=Hi(Dg(zk(e))),!~Gu(s,"g")))throw new eR("`.replaceAll` does not allow non-global regexes");if(n=Qk(e,Zk),n)return jk(n,e,i,t);if(Xk&&r)return tR(Hi(i),e,t)}for(o=Hi(i),u=Hi(e),l=Gk(t),l||(t=Hi(t)),c=u.length,d=iR(1,c),h=Gu(o,u);h!==-1;)p=l?Hi(t(u,h,o)):Kk(u,o,h,[],void 0,t),b+=Bg(o,f,h)+p,f=h+c,h=h+d>o.length?-1:Gu(o,u,h+d);return f<o.length&&(b+=Bg(o,f)),b}})});var _g=m((x_,Vg)=>{"use strict";Tg();Ig();Og();var rR=xs();Vg.exports=rR("String","replaceAll")});var Fg=m((P_,Ng)=>{"use strict";var aR=_g();Ng.exports=aR});var qg=m((A_,Ug)=>{"use strict";var sR=Fg();Ug.exports=sR});var sc="2.0.116-dev.48c29cc5.0";var ce=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(ce||{}),It=(S=>(S.MPEG="MPEG",S.DASH="DASH",S.DASH_SEP="DASH_SEP",S.DASH_SEP_VK="DASH_SEP",S.DASH_WEBM="DASH_WEBM",S.DASH_WEBM_AV1="DASH_WEBM_AV1",S.DASH_STREAMS="DASH_STREAMS",S.DASH_WEBM_VK="DASH_WEBM",S.DASH_ONDEMAND="DASH_ONDEMAND",S.DASH_ONDEMAND_VK="DASH_ONDEMAND",S.DASH_LIVE="DASH_LIVE",S.DASH_LIVE_CMAF="DASH_LIVE_CMAF",S.DASH_LIVE_WEBM="DASH_LIVE_WEBM",S.HLS="HLS",S.HLS_ONDEMAND="HLS_ONDEMAND",S.HLS_JS="HLS",S.HLS_LIVE="HLS_LIVE",S.HLS_LIVE_CMAF="HLS_LIVE_CMAF",S.WEB_RTC_LIVE="WEB_RTC_LIVE",S))(It||{});var qa=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(qa||{}),An=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(An||{});var wn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(wn||{});import{assertNever as dc,assertNonNullable as xv,isNonNullable as Ha,ValueSubject as kn,Subject as Pv,Subscription as Av,merge as wv,observableFrom as kv,fromEvent as oc,map as uc,tap as lc,filterChanged as Rv,isNullable as Rn,ErrorCategory as cc}from"@vkontakte/videoplayer-shared";var nc=a=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});var ja=class{constructor(e){this.connection$=new kn(void 0);this.castState$=new kn("NOT_AVAILABLE");this.errorEvent$=new Pv;this.realCastState$=new kn("NOT_AVAILABLE");this.subscription=new Av;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=Ha((s=window.chrome)==null?void 0:s.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},r||nc("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:cc.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,s;(s=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Ha(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Rn(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Rn(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(oc(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var s,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=i.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return dc(r.sessionState)}})).add(wv(oc(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(lc(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),uc(r=>r.castState)),kv([i.getCastState()])).pipe(Rv(),uc($v),lc(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let s=r==="CONNECTED",n=Ha(this.connection$.getValue());if(s&&!n){let l=i.getCurrentSession();xv(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Rn(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?Ha(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:cc.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},$v=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 dc(a)}};var qS=Fe($o(),1);var Km=Fe(Ps(),1);import{assertNever as Um}from"@vkontakte/videoplayer-shared";var ie=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:Um(t)}return a},mu=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(a);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(a);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:Um(e)}};var x=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};import{isNonNullable as NA,Subject as As,merge as qm}from"@vkontakte/videoplayer-shared";var M=class{constructor(e){this.transitionStarted$=new As;this.transitionEnded$=new As;this.transitionUpdated$=new As;this.forceChanged$=new As;this.stateChangeStarted$=qm(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=qm(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||NA(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as FA}from"@vkontakte/videoplayer-shared";var Hm=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 FA(a)}};import{assertNever as Mi,assertNonNullable as Gt,debounce as jm,ErrorCategory as Gm,fromEvent as Wt,isNonNullable as Wm,map as Ym,merge as Qm,observableFrom as UA,Subject as qA,Subscription as bu,timeout as HA,getHighestQuality as jA}from"@vkontakte/videoplayer-shared";var GA=5,WA=5,YA=500,zm=7e3,Pr=class{constructor(e){this.subscription=new bu;this.loadMediaTimeoutSubscription=new bu;this.videoState=new M("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Mi(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:Mi(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:Mi(e)}break}default:Mi(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Hm(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 bu;this.subscription.add(e),this.subscription.add(Qm(this.videoState.stateChangeStarted$.pipe(Ym(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Ym(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new qA;e.add(r.pipe(jm(YA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Wt(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)>GA)&&r.next(o),s=o})),e.add(Wt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Wt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Wt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(Wt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<WA&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),x(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:Mi(n)}}),t(Wt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(Wt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Qm(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,UA(["init"])).pipe(jm(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),x(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),x(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&x(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,s;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(s=e.muted)!=null?s:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,i,r,s;switch(e){case"MPEG":{let c=t[e];Gt(c);let d=jA(Object.keys(c));Gt(d);let h=c[d];Gt(h),i=h,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];Gt(c),i=c.url,r="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];Gt(c),i=c.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];Gt(c),i=c.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];Gt(c),i=ie(c.url),r="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Gm.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Mi(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:i,r);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return Wm(o)&&(n.metadata.title=o),Wm(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add(HA(zm).subscribe(()=>s(`timeout(${zm})`)))});(0,Km.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Gm.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as Xm}from"@vkontakte/videoplayer-shared";import{clearVideoElement as QA}from"@vkontakte/videoplayer-shared";var Jm=a=>{try{a.pause(),a.playbackRate=0,QA(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as zA,Subscription as KA}from"@vkontakte/videoplayer-shared";var gu=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)}},Su=window.WeakMap?new WeakMap:new gu,vu=window.WeakMap?new WeakMap:new Map,JA=(a,e=20)=>{let t=0;return zA(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},pe=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),i=!!t;t?Xm(t):(t=document.createElement("video"),a.appendChild(t)),Su.set(t,i);let r=new KA;return r.add(JA(t,e)),vu.set(t,r),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},he=a=>{let e=vu.get(a);e==null||e.unsubscribe(),vu.delete(a);let t=Su.get(a);Su.delete(a),t?Xm(a):Jm(a)};import{assertNonNullable as Ar,isNonNullable as Xe,isNullable as ew,fromEvent as Ci,merge as Zm,observableFrom as eb,filterChanged as tb,map as wr,Subject as ib,Subscription as tw,ValueSubject as iw,ErrorCategory as rw}from"@vkontakte/videoplayer-shared";import{isNonNullable as yu,isNullable as XA,Subscription as ZA}from"@vkontakte/videoplayer-shared";var ws=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=XA(r),l=new ZA;return r&&l.add(r.subscribe(c=>{let d=a.getState();i(c,d)&&a.setState(c)},s)),i(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},Je=(a,e,t)=>ws(e,()=>a.loop,i=>{yu(i)&&(a.loop=i)},{onError:t}),fe=(a,e,t,i)=>ws(e,()=>({muted:a.muted,volume:a.volume}),r=>{yu(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||(r==null?void 0:r.muted)===(s==null?void 0:s.muted)&&(r==null?void 0:r.volume)===(s==null?void 0:s.volume),changed$:t,onError:i}),Ce=(a,e,t,i)=>ws(e,()=>a.playbackRate,r=>{yu(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),xt=ws;var aw=a=>["__",a.language,a.label].join("|"),sw=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},Tu=class a{constructor(){this.available$=new ib;this.current$=new iw(void 0);this.error$=new ib;this.subscription=new tw;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:rw.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(xt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{Xe(s)&&this.setInternal(s)},{equal:(s,n)=>Xe(s)&&Xe(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(wr(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(xt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{Xe(s)&&this.setExternal(s)},{equal:(s,n)=>Xe(s)&&Xe(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(wr(s=>s.filter(({type:n})=>n==="external"))),onError:r})),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:r})),this.subscription.add(xt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Ar(this.video);let{textTracks:e}=this.video;this.subscription.add(Ci(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(Zm(Ci(e,"addtrack"),Ci(e,"removetrack"),eb(["init"])).pipe(wr(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),tb((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add(Zm(Ci(e,"change"),eb(["init"])).pipe(wr(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),wr(i=>i&&this.htmlTextTrackToITextTrack(i).id),tb()).subscribe(this.current$));let t=i=>{var r,s;return this.applyCueSettings((s=(r=i.target)==null?void 0:r.activeCues)!=null?s:null)};this.subscription.add(Ci(e,"addtrack").subscribe(i=>{var s,n;(s=i.track)==null||s.addEventListener("cuechange",t);let r=o=>{var l,c,d,h,p;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((h=(d=o.target)==null?void 0:d.cues)!=null?h:null),(p=o.target)==null||p.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add(Ci(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;Xe(t.align)&&(r.align=t.align),Xe(t.position)&&(r.position=t.position),Xe(t.size)&&(r.size=t.size),Xe(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Ar(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c;let{language:t,label:i}=e,r=e.id?e.id:aw(e),s=this.externalTracks.has(r),n=(s?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)||r.includes("auto");return s?{id:r,type:"external",isAuto:n,language:t,label:i,url:(l=this.externalTracks.get(r))==null?void 0:l.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(c=this.internalTracks.get(r))==null?void 0:c.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){Ar(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(ew(e)||!sw(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){Ar(this.video);let t=document.createElement("track");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){Ar(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},De=Tu;var ot=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 rb=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},Iu=a=>{let e=rb(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},ab=a=>{let e=rb(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Be,map as Pt,merge as nb,filterChanged as ow,isNonNullable as ob,Subject as uw,filter as ub,mapTo as lb,combine as lw,once as cw,ErrorCategory as dw,ValueSubject as cb,clientChecker as pw}from"@vkontakte/videoplayer-shared";var nw=3,sb=(a,e,t=nw)=>{let i=0,r=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=s-1;u>=0;u--)a.end(u)+t>=i&&(i=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=r&&(r=a.end(u))}}return{from:i,to:r}};var me=a=>{let e=S=>Be(a,S).pipe(lb(void 0)),i=nb(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(S=>Be(a,S))).pipe(Pt(S=>S.type==="ended"?a.readyState<2:a.readyState<3),ow()),r=nb(Be(a,"progress"),Be(a,"timeupdate")).pipe(Pt(()=>sb(a.buffered,a.currentTime))),s=pw.isSafari?lw({play:e("play").pipe(cw()),playing:e("playing")}).pipe(lb(void 0)):e("playing"),n=Be(a,"volumechange").pipe(Pt(()=>({muted:a.muted,volume:a.volume}))),o=Be(a,"ratechange").pipe(Pt(()=>a.playbackRate)),u=Be(a,"error").pipe(ub(()=>!!(a.error||a.played.length)),Pt(()=>{var T;let S=a.error;return{id:S?`MediaError#${S.code}`:"HtmlVideoError",category:dw.VIDEO_PIPELINE,message:S?S.message:"Error event from HTML video element",thrown:(T=a.error)!=null?T:void 0}})),l=Be(a,"timeupdate").pipe(Pt(()=>a.currentTime)),c=new uw,d=.3,h;l.subscribe(S=>{a.loop&&ob(h)&&ob(S)&&h>=a.duration-d&&S<=d&&c.next(h),h=S});let p=e("pause").pipe(ub(()=>!a.error&&h!==a.duration)),f=Be(a,"enterpictureinpicture"),b=Be(a,"leavepictureinpicture"),g=new cb(ab(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let y=new cb(Iu(a));return Be(a,"fullscreenchange").pipe(Pt(()=>Iu(a))).subscribe(y),{playing$:s,pause$:p,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$:Be(a,"durationchange").pipe(Pt(()=>a.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:y}};import{VideoQuality as At}from"@vkontakte/videoplayer-shared";var wt=a=>{switch(a){case"mobile":return At.Q_144P;case"lowest":return At.Q_240P;case"low":return At.Q_360P;case"sd":case"medium":return At.Q_480P;case"hd":case"high":return At.Q_720P;case"fullhd":case"full":return At.Q_1080P;case"quadhd":case"quad":return At.Q_1440P;case"ultrahd":case"ultra":return At.Q_2160P}};var Yt=Fe(Di(),1);import{isNonNullable as X,isNullable as xu,now as xb,isHigher as Pu,isHigherOrEqual as yb,isInvariantQuality as Tb,isLower as Ib,isLowerOrEqual as Au,videoSizeToQuality as Tw,assertNotEmptyArray as Pb,assertNonNullable as Iw}from"@vkontakte/videoplayer-shared";var Eu=!1,ut={},gb=a=>{Eu=a},Sb=()=>{ut={}},vb=a=>{a(ut)},kr=(a,e)=>{var t;Eu&&(ut.meta=(t=ut.meta)!=null?t:{},ut.meta[a]=e)},ne=class{constructor(e){this.name=e}next(e){var i,r;if(!Eu)return;ut.series=(i=ut.series)!=null?i:{};let t=(r=ut.series[this.name])!=null?r:[];t.push([Date.now(),e]),ut.series[this.name]=t}};var Ew=new ne("best_bitrate"),Ab=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var wu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Rr=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=xb()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},wb='Assertion "ABR Tracks is empty array" failed',ks=(a,e,t,i)=>{var u;let r=[...e].sort(wu(1)),s=[...t].sort(wu(1)),n=s.filter(l=>X(l.bitrate)&&X(a.bitrate)?a.bitrate/l.bitrate>i:!0),o=(u=(0,Yt.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Yt.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,Yt.default)(n,-1):(0,Yt.default)(s,0)},Eb=a=>"quality"in a,kb=(a,e,t,i)=>{var n;let r=X((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&X(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&xb()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!s&&i.recordSelection(t),s&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=Eb(o)?"video":"audio",l=Eb(o)?o.quality:o.bitrate;return e({message:`
|
|
6
|
+
var gv=Object.create;var tc=Object.defineProperty;var Sv=Object.getOwnPropertyDescriptor;var vv=Object.getOwnPropertyNames;var yv=Object.getPrototypeOf,Tv=Object.prototype.hasOwnProperty;var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var Iv=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of vv(e))!Tv.call(a,i)&&i!==t&&tc(a,i,{get:()=>e[i],enumerable:!(r=Sv(e,i))||r.enumerable});return a};var Ue=(a,e,t)=>(t=a!=null?gv(yv(a)):{},Iv(e||!a||!a.__esModule?tc(t,"default",{value:a,enumerable:!0}):t,a));var Te=m((xL,lc)=>{"use strict";lc.exports=function(a){try{return!!a()}catch(e){return!0}}});var Zr=m((PL,cc)=>{"use strict";var $v=Te();cc.exports=!$v(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var de=m((AL,hc)=>{"use strict";var dc=Zr(),pc=Function.prototype,An=pc.call,Lv=dc&&pc.bind.bind(An,An);hc.exports=dc?Lv:function(a){return function(){return An.apply(a,arguments)}}});var br=m((wL,mc)=>{"use strict";var fc=de(),Mv=fc({}.toString),Cv=fc("".slice);mc.exports=function(a){return Cv(Mv(a),8,-1)}});var gc=m((kL,bc)=>{"use strict";var Dv=de(),Bv=Te(),Ov=br(),wn=Object,Vv=Dv("".split);bc.exports=Bv(function(){return!wn("z").propertyIsEnumerable(0)})?function(a){return Ov(a)==="String"?Vv(a,""):wn(a)}:wn});var gr=m((RL,Sc)=>{"use strict";Sc.exports=function(a){return a==null}});var ei=m(($L,vc)=>{"use strict";var _v=gr(),Nv=TypeError;vc.exports=function(a){if(_v(a))throw new Nv("Can't call method on "+a);return a}});var Sr=m((LL,yc)=>{"use strict";var Fv=gc(),Uv=ei();yc.exports=function(a){return Fv(Uv(a))}});var kn=m((ML,Tc)=>{"use strict";Tc.exports=function(){}});var Ft=m((CL,Ic)=>{"use strict";Ic.exports={}});var Y=m((Rn,Ec)=>{"use strict";var ti=function(a){return a&&a.Math===Math&&a};Ec.exports=ti(typeof globalThis=="object"&&globalThis)||ti(typeof window=="object"&&window)||ti(typeof self=="object"&&self)||ti(typeof global=="object"&&global)||ti(typeof Rn=="object"&&Rn)||function(){return this}()||Function("return this")()});var Q=m((DL,xc)=>{"use strict";var $n=typeof document=="object"&&document.all;xc.exports=typeof $n=="undefined"&&$n!==void 0?function(a){return typeof a=="function"||a===$n}:function(a){return typeof a=="function"}});var wc=m((BL,Ac)=>{"use strict";var qv=Y(),Hv=Q(),Pc=qv.WeakMap;Ac.exports=Hv(Pc)&&/native code/.test(String(Pc))});var $e=m((OL,kc)=>{"use strict";var jv=Q();kc.exports=function(a){return typeof a=="object"?a!==null:jv(a)}});var Le=m((VL,Rc)=>{"use strict";var Gv=Te();Rc.exports=!Gv(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var ja=m((_L,Lc)=>{"use strict";var Wv=Y(),$c=$e(),Ln=Wv.document,Qv=$c(Ln)&&$c(Ln.createElement);Lc.exports=function(a){return Qv?Ln.createElement(a):{}}});var Mn=m((NL,Mc)=>{"use strict";var Yv=Le(),zv=Te(),Kv=ja();Mc.exports=!Yv&&!zv(function(){return Object.defineProperty(Kv("div"),"a",{get:function(){return 7}}).a!==7})});var Cn=m((FL,Cc)=>{"use strict";var Jv=Le(),Xv=Te();Cc.exports=Jv&&Xv(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Ke=m((UL,Dc)=>{"use strict";var Zv=$e(),ey=String,ty=TypeError;Dc.exports=function(a){if(Zv(a))return a;throw new ty(ey(a)+" is not an object")}});var Ie=m((qL,Bc)=>{"use strict";var ry=Zr(),Ga=Function.prototype.call;Bc.exports=ry?Ga.bind(Ga):function(){return Ga.apply(Ga,arguments)}});var Wa=m((HL,Oc)=>{"use strict";Oc.exports={}});var rt=m((jL,_c)=>{"use strict";var Dn=Wa(),Bn=Y(),iy=Q(),Vc=function(a){return iy(a)?a:void 0};_c.exports=function(a,e){return arguments.length<2?Vc(Dn[a])||Vc(Bn[a]):Dn[a]&&Dn[a][e]||Bn[a]&&Bn[a][e]}});var ri=m((GL,Nc)=>{"use strict";var ay=de();Nc.exports=ay({}.isPrototypeOf)});var vr=m((WL,qc)=>{"use strict";var sy=Y(),Fc=sy.navigator,Uc=Fc&&Fc.userAgent;qc.exports=Uc?String(Uc):""});var Vn=m((QL,Yc)=>{"use strict";var Qc=Y(),On=vr(),Hc=Qc.process,jc=Qc.Deno,Gc=Hc&&Hc.versions||jc&&jc.version,Wc=Gc&&Gc.v8,qe,Qa;Wc&&(qe=Wc.split("."),Qa=qe[0]>0&&qe[0]<4?1:+(qe[0]+qe[1]));!Qa&&On&&(qe=On.match(/Edge\/(\d+)/),(!qe||qe[1]>=74)&&(qe=On.match(/Chrome\/(\d+)/),qe&&(Qa=+qe[1])));Yc.exports=Qa});var _n=m((YL,Kc)=>{"use strict";var zc=Vn(),ny=Te(),oy=Y(),uy=oy.String;Kc.exports=!!Object.getOwnPropertySymbols&&!ny(function(){var a=Symbol("symbol detection");return!uy(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&zc&&zc<41})});var Nn=m((zL,Jc)=>{"use strict";var ly=_n();Jc.exports=ly&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Fn=m((KL,Xc)=>{"use strict";var cy=rt(),dy=Q(),py=ri(),hy=Nn(),fy=Object;Xc.exports=hy?function(a){return typeof a=="symbol"}:function(a){var e=cy("Symbol");return dy(e)&&py(e.prototype,fy(a))}});var ii=m((JL,Zc)=>{"use strict";var my=String;Zc.exports=function(a){try{return my(a)}catch(e){return"Object"}}});var it=m((XL,ed)=>{"use strict";var by=Q(),gy=ii(),Sy=TypeError;ed.exports=function(a){if(by(a))return a;throw new Sy(gy(a)+" is not a function")}});var ai=m((ZL,td)=>{"use strict";var vy=it(),yy=gr();td.exports=function(a,e){var t=a[e];return yy(t)?void 0:vy(t)}});var id=m((eM,rd)=>{"use strict";var Un=Ie(),qn=Q(),Hn=$e(),Ty=TypeError;rd.exports=function(a,e){var t,r;if(e==="string"&&qn(t=a.toString)&&!Hn(r=Un(t,a))||qn(t=a.valueOf)&&!Hn(r=Un(t,a))||e!=="string"&&qn(t=a.toString)&&!Hn(r=Un(t,a)))return r;throw new Ty("Can't convert object to primitive value")}});var He=m((tM,ad)=>{"use strict";ad.exports=!0});var od=m((rM,nd)=>{"use strict";var sd=Y(),Iy=Object.defineProperty;nd.exports=function(a,e){try{Iy(sd,a,{value:e,configurable:!0,writable:!0})}catch(t){sd[a]=e}return e}});var si=m((iM,cd)=>{"use strict";var Ey=He(),xy=Y(),Py=od(),ud="__core-js_shared__",ld=cd.exports=xy[ud]||Py(ud,{});(ld.versions||(ld.versions=[])).push({version:"3.38.0",mode:Ey?"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 jn=m((aM,pd)=>{"use strict";var dd=si();pd.exports=function(a,e){return dd[a]||(dd[a]=e||{})}});var ni=m((sM,hd)=>{"use strict";var Ay=ei(),wy=Object;hd.exports=function(a){return wy(Ay(a))}});var je=m((nM,fd)=>{"use strict";var ky=de(),Ry=ni(),$y=ky({}.hasOwnProperty);fd.exports=Object.hasOwn||function(e,t){return $y(Ry(e),t)}});var Gn=m((oM,md)=>{"use strict";var Ly=de(),My=0,Cy=Math.random(),Dy=Ly(1 .toString);md.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+Dy(++My+Cy,36)}});var ne=m((uM,gd)=>{"use strict";var By=Y(),Oy=jn(),bd=je(),Vy=Gn(),_y=_n(),Ny=Nn(),yr=By.Symbol,Wn=Oy("wks"),Fy=Ny?yr.for||yr:yr&&yr.withoutSetter||Vy;gd.exports=function(a){return bd(Wn,a)||(Wn[a]=_y&&bd(yr,a)?yr[a]:Fy("Symbol."+a)),Wn[a]}});var Td=m((lM,yd)=>{"use strict";var Uy=Ie(),Sd=$e(),vd=Fn(),qy=ai(),Hy=id(),jy=ne(),Gy=TypeError,Wy=jy("toPrimitive");yd.exports=function(a,e){if(!Sd(a)||vd(a))return a;var t=qy(a,Wy),r;if(t){if(e===void 0&&(e="default"),r=Uy(t,a,e),!Sd(r)||vd(r))return r;throw new Gy("Can't convert object to primitive value")}return e===void 0&&(e="number"),Hy(a,e)}});var Qn=m((cM,Id)=>{"use strict";var Qy=Td(),Yy=Fn();Id.exports=function(a){var e=Qy(a,"string");return Yy(e)?e:e+""}});var Ut=m(xd=>{"use strict";var zy=Le(),Ky=Mn(),Jy=Cn(),Ya=Ke(),Ed=Qn(),Xy=TypeError,Yn=Object.defineProperty,Zy=Object.getOwnPropertyDescriptor,zn="enumerable",Kn="configurable",Jn="writable";xd.f=zy?Jy?function(e,t,r){if(Ya(e),t=Ed(t),Ya(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Jn in r&&!r[Jn]){var i=Zy(e,t);i&&i[Jn]&&(e[t]=r.value,r={configurable:Kn in r?r[Kn]:i[Kn],enumerable:zn in r?r[zn]:i[zn],writable:!1})}return Yn(e,t,r)}:Yn:function(e,t,r){if(Ya(e),t=Ed(t),Ya(r),Ky)try{return Yn(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new Xy("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var oi=m((pM,Pd)=>{"use strict";Pd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Tr=m((hM,Ad)=>{"use strict";var eT=Le(),tT=Ut(),rT=oi();Ad.exports=eT?function(a,e,t){return tT.f(a,e,rT(1,t))}:function(a,e,t){return a[e]=t,a}});var za=m((fM,kd)=>{"use strict";var iT=jn(),aT=Gn(),wd=iT("keys");kd.exports=function(a){return wd[a]||(wd[a]=aT(a))}});var Ka=m((mM,Rd)=>{"use strict";Rd.exports={}});var to=m((bM,Md)=>{"use strict";var sT=wc(),Ld=Y(),nT=$e(),oT=Tr(),Xn=je(),Zn=si(),uT=za(),lT=Ka(),$d="Object already initialized",eo=Ld.TypeError,cT=Ld.WeakMap,Ja,ui,Xa,dT=function(a){return Xa(a)?ui(a):Ja(a,{})},pT=function(a){return function(e){var t;if(!nT(e)||(t=ui(e)).type!==a)throw new eo("Incompatible receiver, "+a+" required");return t}};sT||Zn.state?(Ge=Zn.state||(Zn.state=new cT),Ge.get=Ge.get,Ge.has=Ge.has,Ge.set=Ge.set,Ja=function(a,e){if(Ge.has(a))throw new eo($d);return e.facade=a,Ge.set(a,e),e},ui=function(a){return Ge.get(a)||{}},Xa=function(a){return Ge.has(a)}):(qt=uT("state"),lT[qt]=!0,Ja=function(a,e){if(Xn(a,qt))throw new eo($d);return e.facade=a,oT(a,qt,e),e},ui=function(a){return Xn(a,qt)?a[qt]:{}},Xa=function(a){return Xn(a,qt)});var Ge,qt;Md.exports={set:Ja,get:ui,has:Xa,enforce:dT,getterFor:pT}});var ro=m((gM,Od)=>{"use strict";var hT=Zr(),Bd=Function.prototype,Cd=Bd.apply,Dd=Bd.call;Od.exports=typeof Reflect=="object"&&Reflect.apply||(hT?Dd.bind(Cd):function(){return Dd.apply(Cd,arguments)})});var io=m((SM,Vd)=>{"use strict";var fT=br(),mT=de();Vd.exports=function(a){if(fT(a)==="Function")return mT(a)}});var Ud=m(Fd=>{"use strict";var _d={}.propertyIsEnumerable,Nd=Object.getOwnPropertyDescriptor,bT=Nd&&!_d.call({1:2},1);Fd.f=bT?function(e){var t=Nd(this,e);return!!t&&t.enumerable}:_d});var jd=m(Hd=>{"use strict";var gT=Le(),ST=Ie(),vT=Ud(),yT=oi(),TT=Sr(),IT=Qn(),ET=je(),xT=Mn(),qd=Object.getOwnPropertyDescriptor;Hd.f=gT?qd:function(e,t){if(e=TT(e),t=IT(t),xT)try{return qd(e,t)}catch(r){}if(ET(e,t))return yT(!ST(vT.f,e,t),e[t])}});var ao=m((TM,Gd)=>{"use strict";var PT=Te(),AT=Q(),wT=/#|\.prototype\./,li=function(a,e){var t=RT[kT(a)];return t===LT?!0:t===$T?!1:AT(e)?PT(e):!!e},kT=li.normalize=function(a){return String(a).replace(wT,".").toLowerCase()},RT=li.data={},$T=li.NATIVE="N",LT=li.POLYFILL="P";Gd.exports=li});var ci=m((IM,Qd)=>{"use strict";var Wd=io(),MT=it(),CT=Zr(),DT=Wd(Wd.bind);Qd.exports=function(a,e){return MT(a),e===void 0?a:CT?DT(a,e):function(){return a.apply(e,arguments)}}});var Me=m((EM,zd)=>{"use strict";var di=Y(),BT=ro(),OT=io(),VT=Q(),_T=jd().f,NT=ao(),Ir=Wa(),FT=ci(),Er=Tr(),Yd=je();si();var UT=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 BT(a,this,arguments)};return e.prototype=a.prototype,e};zd.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?di:i?di[t]:di[t]&&di[t].prototype,o=r?Ir:Ir[t]||Er(Ir,t,{})[t],u=o.prototype,l,c,d,h,p,f,b,g,v;for(h in e)l=NT(r?h:t+(i?".":"#")+h,a.forced),c=!l&&n&&Yd(n,h),f=o[h],c&&(a.dontCallGetSet?(v=_T(n,h),b=v&&v.value):b=n[h]),p=c&&b?b:e[h],!(!l&&!s&&typeof f==typeof p)&&(a.bind&&c?g=FT(p,di):a.wrap&&c?g=UT(p):s&&VT(p)?g=OT(p):g=p,(a.sham||p&&p.sham||f&&f.sham)&&Er(g,"sham",!0),Er(o,h,g),s&&(d=t+"Prototype",Yd(Ir,d)||Er(Ir,d,{}),Er(Ir[d],h,p),a.real&&u&&(l||!u[h])&&Er(u,h,p)))}});var Xd=m((xM,Jd)=>{"use strict";var so=Le(),qT=je(),Kd=Function.prototype,HT=so&&Object.getOwnPropertyDescriptor,no=qT(Kd,"name"),jT=no&&function(){}.name==="something",GT=no&&(!so||so&&HT(Kd,"name").configurable);Jd.exports={EXISTS:no,PROPER:jT,CONFIGURABLE:GT}});var ep=m((PM,Zd)=>{"use strict";var WT=Math.ceil,QT=Math.floor;Zd.exports=Math.trunc||function(e){var t=+e;return(t>0?QT:WT)(t)}});var Za=m((AM,tp)=>{"use strict";var YT=ep();tp.exports=function(a){var e=+a;return e!==e||e===0?0:YT(e)}});var ip=m((wM,rp)=>{"use strict";var zT=Za(),KT=Math.max,JT=Math.min;rp.exports=function(a,e){var t=zT(a);return t<0?KT(t+e,0):JT(t,e)}});var sp=m((kM,ap)=>{"use strict";var XT=Za(),ZT=Math.min;ap.exports=function(a){var e=XT(a);return e>0?ZT(e,9007199254740991):0}});var es=m((RM,np)=>{"use strict";var eI=sp();np.exports=function(a){return eI(a.length)}});var lp=m(($M,up)=>{"use strict";var tI=Sr(),rI=ip(),iI=es(),op=function(a){return function(e,t,r){var i=tI(e),s=iI(i);if(s===0)return!a&&-1;var n=rI(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}};up.exports={includes:op(!0),indexOf:op(!1)}});var pp=m((LM,dp)=>{"use strict";var aI=de(),oo=je(),sI=Sr(),nI=lp().indexOf,oI=Ka(),cp=aI([].push);dp.exports=function(a,e){var t=sI(a),r=0,i=[],s;for(s in t)!oo(oI,s)&&oo(t,s)&&cp(i,s);for(;e.length>r;)oo(t,s=e[r++])&&(~nI(i,s)||cp(i,s));return i}});var uo=m((MM,hp)=>{"use strict";hp.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var mp=m((CM,fp)=>{"use strict";var uI=pp(),lI=uo();fp.exports=Object.keys||function(e){return uI(e,lI)}});var gp=m(bp=>{"use strict";var cI=Le(),dI=Cn(),pI=Ut(),hI=Ke(),fI=Sr(),mI=mp();bp.f=cI&&!dI?Object.defineProperties:function(e,t){hI(e);for(var r=fI(t),i=mI(t),s=i.length,n=0,o;s>n;)pI.f(e,o=i[n++],r[o]);return e}});var lo=m((BM,Sp)=>{"use strict";var bI=rt();Sp.exports=bI("document","documentElement")});var fo=m((OM,Pp)=>{"use strict";var gI=Ke(),SI=gp(),vp=uo(),vI=Ka(),yI=lo(),TI=ja(),II=za(),yp=">",Tp="<",po="prototype",ho="script",Ep=II("IE_PROTO"),co=function(){},xp=function(a){return Tp+ho+yp+a+Tp+"/"+ho+yp},Ip=function(a){a.write(xp("")),a.close();var e=a.parentWindow.Object;return a=null,e},EI=function(){var a=TI("iframe"),e="java"+ho+":",t;return a.style.display="none",yI.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(xp("document.F=Object")),t.close(),t.F},ts,rs=function(){try{ts=new ActiveXObject("htmlfile")}catch(e){}rs=typeof document!="undefined"?document.domain&&ts?Ip(ts):EI():Ip(ts);for(var a=vp.length;a--;)delete rs[po][vp[a]];return rs()};vI[Ep]=!0;Pp.exports=Object.create||function(e,t){var r;return e!==null?(co[po]=gI(e),r=new co,co[po]=null,r[Ep]=e):r=rs(),t===void 0?r:SI.f(r,t)}});var wp=m((VM,Ap)=>{"use strict";var xI=Te();Ap.exports=!xI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var bo=m((_M,Rp)=>{"use strict";var PI=je(),AI=Q(),wI=ni(),kI=za(),RI=wp(),kp=kI("IE_PROTO"),mo=Object,$I=mo.prototype;Rp.exports=RI?mo.getPrototypeOf:function(a){var e=wI(a);if(PI(e,kp))return e[kp];var t=e.constructor;return AI(t)&&e instanceof t?t.prototype:e instanceof mo?$I:null}});var xr=m((NM,$p)=>{"use strict";var LI=Tr();$p.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:LI(a,e,t),a}});var yo=m((FM,Cp)=>{"use strict";var MI=Te(),CI=Q(),DI=$e(),BI=fo(),Lp=bo(),OI=xr(),VI=ne(),_I=He(),vo=VI("iterator"),Mp=!1,at,go,So;[].keys&&(So=[].keys(),"next"in So?(go=Lp(Lp(So)),go!==Object.prototype&&(at=go)):Mp=!0);var NI=!DI(at)||MI(function(){var a={};return at[vo].call(a)!==a});NI?at={}:_I&&(at=BI(at));CI(at[vo])||OI(at,vo,function(){return this});Cp.exports={IteratorPrototype:at,BUGGY_SAFARI_ITERATORS:Mp}});var is=m((UM,Bp)=>{"use strict";var FI=ne(),UI=FI("toStringTag"),Dp={};Dp[UI]="z";Bp.exports=String(Dp)==="[object z]"});var pi=m((qM,Op)=>{"use strict";var qI=is(),HI=Q(),as=br(),jI=ne(),GI=jI("toStringTag"),WI=Object,QI=as(function(){return arguments}())==="Arguments",YI=function(a,e){try{return a[e]}catch(t){}};Op.exports=qI?as:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=YI(e=WI(a),GI))=="string"?t:QI?as(e):(r=as(e))==="Object"&&HI(e.callee)?"Arguments":r}});var _p=m((HM,Vp)=>{"use strict";var zI=is(),KI=pi();Vp.exports=zI?{}.toString:function(){return"[object "+KI(this)+"]"}});var hi=m((jM,Fp)=>{"use strict";var JI=is(),XI=Ut().f,ZI=Tr(),eE=je(),tE=_p(),rE=ne(),Np=rE("toStringTag");Fp.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(eE(i,Np)||XI(i,Np,{configurable:!0,value:e}),r&&!JI&&ZI(i,"toString",tE))}});var qp=m((GM,Up)=>{"use strict";var iE=yo().IteratorPrototype,aE=fo(),sE=oi(),nE=hi(),oE=Ft(),uE=function(){return this};Up.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=aE(iE,{next:sE(+!r,t)}),nE(a,i,!1,!0),oE[i]=uE,a}});var jp=m((WM,Hp)=>{"use strict";var lE=de(),cE=it();Hp.exports=function(a,e,t){try{return lE(cE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var Wp=m((QM,Gp)=>{"use strict";var dE=$e();Gp.exports=function(a){return dE(a)||a===null}});var Yp=m((YM,Qp)=>{"use strict";var pE=Wp(),hE=String,fE=TypeError;Qp.exports=function(a){if(pE(a))return a;throw new fE("Can't set "+hE(a)+" as a prototype")}});var To=m((zM,zp)=>{"use strict";var mE=jp(),bE=$e(),gE=ei(),SE=Yp();zp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=mE(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return gE(i),SE(s),bE(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var nh=m((KM,sh)=>{"use strict";var vE=Me(),yE=Ie(),ss=He(),ih=Xd(),TE=Q(),IE=qp(),Kp=bo(),Jp=To(),EE=hi(),xE=Tr(),Io=xr(),PE=ne(),Xp=Ft(),ah=yo(),AE=ih.PROPER,wE=ih.CONFIGURABLE,Zp=ah.IteratorPrototype,ns=ah.BUGGY_SAFARI_ITERATORS,fi=PE("iterator"),eh="keys",mi="values",th="entries",rh=function(){return this};sh.exports=function(a,e,t,r,i,s,n){IE(t,e,r);var o=function(v){if(v===i&&h)return h;if(!ns&&v&&v in c)return c[v];switch(v){case eh:return function(){return new t(this,v)};case mi:return function(){return new t(this,v)};case th:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[fi]||c["@@iterator"]||i&&c[i],h=!ns&&d||o(i),p=e==="Array"&&c.entries||d,f,b,g;if(p&&(f=Kp(p.call(new a)),f!==Object.prototype&&f.next&&(!ss&&Kp(f)!==Zp&&(Jp?Jp(f,Zp):TE(f[fi])||Io(f,fi,rh)),EE(f,u,!0,!0),ss&&(Xp[u]=rh))),AE&&i===mi&&d&&d.name!==mi&&(!ss&&wE?xE(c,"name",mi):(l=!0,h=function(){return yE(d,this)})),i)if(b={values:o(mi),keys:s?h:o(eh),entries:o(th)},n)for(g in b)(ns||l||!(g in c))&&Io(c,g,b[g]);else vE({target:e,proto:!0,forced:ns||l},b);return(!ss||n)&&c[fi]!==h&&Io(c,fi,h,{name:i}),Xp[e]=h,b}});var uh=m((JM,oh)=>{"use strict";oh.exports=function(a,e){return{value:a,done:e}}});var xo=m((XM,hh)=>{"use strict";var kE=Sr(),Eo=kn(),lh=Ft(),dh=to(),RE=Ut().f,$E=nh(),os=uh(),LE=He(),ME=Le(),ph="Array Iterator",CE=dh.set,DE=dh.getterFor(ph);hh.exports=$E(Array,"Array",function(a,e){CE(this,{type:ph,target:kE(a),index:0,kind:e})},function(){var a=DE(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,os(void 0,!0);switch(a.kind){case"keys":return os(t,!1);case"values":return os(e[t],!1)}return os([t,e[t]],!1)},"values");var ch=lh.Arguments=lh.Array;Eo("keys");Eo("values");Eo("entries");if(!LE&&ME&&ch.name!=="values")try{RE(ch,"name",{value:"values"})}catch(a){}});var mh=m((ZM,fh)=>{"use strict";var BE=ne(),OE=Ft(),VE=BE("iterator"),_E=Array.prototype;fh.exports=function(a){return a!==void 0&&(OE.Array===a||_E[VE]===a)}});var Po=m((eC,gh)=>{"use strict";var NE=pi(),bh=ai(),FE=gr(),UE=Ft(),qE=ne(),HE=qE("iterator");gh.exports=function(a){if(!FE(a))return bh(a,HE)||bh(a,"@@iterator")||UE[NE(a)]}});var vh=m((tC,Sh)=>{"use strict";var jE=Ie(),GE=it(),WE=Ke(),QE=ii(),YE=Po(),zE=TypeError;Sh.exports=function(a,e){var t=arguments.length<2?YE(a):e;if(GE(t))return WE(jE(t,a));throw new zE(QE(a)+" is not iterable")}});var Ih=m((rC,Th)=>{"use strict";var KE=Ie(),yh=Ke(),JE=ai();Th.exports=function(a,e,t){var r,i;yh(a);try{if(r=JE(a,"return"),!r){if(e==="throw")throw t;return t}r=KE(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return yh(r),t}});var ls=m((iC,Ah)=>{"use strict";var XE=ci(),ZE=Ie(),ex=Ke(),tx=ii(),rx=mh(),ix=es(),Eh=ri(),ax=vh(),sx=Po(),xh=Ih(),nx=TypeError,us=function(a,e){this.stopped=a,this.result=e},Ph=us.prototype;Ah.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=XE(e,r),l,c,d,h,p,f,b,g=function(T){return l&&xh(l,"normal",T),new us(!0,T)},v=function(T){return i?(ex(T),o?u(T[0],T[1],g):u(T[0],T[1])):o?u(T,g):u(T)};if(s)l=a.iterator;else if(n)l=a;else{if(c=sx(a),!c)throw new nx(tx(a)+" is not iterable");if(rx(c)){for(d=0,h=ix(a);h>d;d++)if(p=v(a[d]),p&&Eh(Ph,p))return p;return new us(!1)}l=ax(a,c)}for(f=s?a.next:l.next;!(b=ZE(f,l)).done;){try{p=v(b.value)}catch(T){xh(l,"throw",T)}if(typeof p=="object"&&p&&Eh(Ph,p))return p}return new us(!1)}});var kh=m((aC,wh)=>{"use strict";var ox=Le(),ux=Ut(),lx=oi();wh.exports=function(a,e,t){ox?ux.f(a,e,lx(0,t)):a[e]=t}});var Rh=m(()=>{"use strict";var cx=Me(),dx=ls(),px=kh();cx({target:"Object",stat:!0},{fromEntries:function(e){var t={};return dx(e,function(r,i){px(t,r,i)},{AS_ENTRIES:!0}),t}})});var Lh=m((oC,$h)=>{"use strict";xo();Rh();var hx=Wa();$h.exports=hx.Object.fromEntries});var Ch=m((uC,Mh)=>{"use strict";Mh.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 Bh=m(()=>{"use strict";xo();var fx=Ch(),mx=Y(),bx=hi(),Dh=Ft();for(cs in fx)bx(mx[cs],cs),Dh[cs]=Dh.Array;var cs});var Vh=m((dC,Oh)=>{"use strict";var gx=Lh();Bh();Oh.exports=gx});var Ao=m((pC,_h)=>{"use strict";var Sx=Vh();_h.exports=Sx});var Nh=m(()=>{"use strict"});var wo=m((mC,Fh)=>{"use strict";var bi=Y(),vx=vr(),yx=br(),ds=function(a){return vx.slice(0,a.length)===a};Fh.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":yx(bi.process)==="process"?"NODE":bi.window&&bi.document?"BROWSER":"REST"}()});var ps=m((bC,Uh)=>{"use strict";var Tx=wo();Uh.exports=Tx==="NODE"});var Hh=m((gC,qh)=>{"use strict";var Ix=Ut();qh.exports=function(a,e,t){return Ix.f(a,e,t)}});var Wh=m((SC,Gh)=>{"use strict";var Ex=rt(),xx=Hh(),Px=ne(),Ax=Le(),jh=Px("species");Gh.exports=function(a){var e=Ex(a);Ax&&e&&!e[jh]&&xx(e,jh,{configurable:!0,get:function(){return this}})}});var Yh=m((vC,Qh)=>{"use strict";var wx=ri(),kx=TypeError;Qh.exports=function(a,e){if(wx(e,a))return a;throw new kx("Incorrect invocation")}});var Ro=m((yC,zh)=>{"use strict";var Rx=de(),$x=Q(),ko=si(),Lx=Rx(Function.toString);$x(ko.inspectSource)||(ko.inspectSource=function(a){return Lx(a)});zh.exports=ko.inspectSource});var tf=m((TC,ef)=>{"use strict";var Mx=de(),Cx=Te(),Kh=Q(),Dx=pi(),Bx=rt(),Ox=Ro(),Jh=function(){},Xh=Bx("Reflect","construct"),$o=/^\s*(?:class|function)\b/,Vx=Mx($o.exec),_x=!$o.test(Jh),gi=function(e){if(!Kh(e))return!1;try{return Xh(Jh,[],e),!0}catch(t){return!1}},Zh=function(e){if(!Kh(e))return!1;switch(Dx(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return _x||!!Vx($o,Ox(e))}catch(t){return!0}};Zh.sham=!0;ef.exports=!Xh||Cx(function(){var a;return gi(gi.call)||!gi(Object)||!gi(function(){a=!0})||a})?Zh:gi});var af=m((IC,rf)=>{"use strict";var Nx=tf(),Fx=ii(),Ux=TypeError;rf.exports=function(a){if(Nx(a))return a;throw new Ux(Fx(a)+" is not a constructor")}});var Lo=m((EC,nf)=>{"use strict";var sf=Ke(),qx=af(),Hx=gr(),jx=ne(),Gx=jx("species");nf.exports=function(a,e){var t=sf(a).constructor,r;return t===void 0||Hx(r=sf(t)[Gx])?e:qx(r)}});var uf=m((xC,of)=>{"use strict";var Wx=de();of.exports=Wx([].slice)});var cf=m((PC,lf)=>{"use strict";var Qx=TypeError;lf.exports=function(a,e){if(a<e)throw new Qx("Not enough arguments");return a}});var Mo=m((AC,df)=>{"use strict";var Yx=vr();df.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Yx)});var Uo=m((wC,yf)=>{"use strict";var Ee=Y(),zx=ro(),Kx=ci(),pf=Q(),Jx=je(),vf=Te(),hf=lo(),Xx=uf(),ff=ja(),Zx=cf(),eP=Mo(),tP=ps(),_o=Ee.setImmediate,No=Ee.clearImmediate,rP=Ee.process,Co=Ee.Dispatch,iP=Ee.Function,mf=Ee.MessageChannel,aP=Ee.String,Do=0,Si={},bf="onreadystatechange",vi,Ht,Bo,Oo;vf(function(){vi=Ee.location});var Fo=function(a){if(Jx(Si,a)){var e=Si[a];delete Si[a],e()}},Vo=function(a){return function(){Fo(a)}},gf=function(a){Fo(a.data)},Sf=function(a){Ee.postMessage(aP(a),vi.protocol+"//"+vi.host)};(!_o||!No)&&(_o=function(e){Zx(arguments.length,1);var t=pf(e)?e:iP(e),r=Xx(arguments,1);return Si[++Do]=function(){zx(t,void 0,r)},Ht(Do),Do},No=function(e){delete Si[e]},tP?Ht=function(a){rP.nextTick(Vo(a))}:Co&&Co.now?Ht=function(a){Co.now(Vo(a))}:mf&&!eP?(Bo=new mf,Oo=Bo.port2,Bo.port1.onmessage=gf,Ht=Kx(Oo.postMessage,Oo)):Ee.addEventListener&&pf(Ee.postMessage)&&!Ee.importScripts&&vi&&vi.protocol!=="file:"&&!vf(Sf)?(Ht=Sf,Ee.addEventListener("message",gf,!1)):bf in ff("script")?Ht=function(a){hf.appendChild(ff("script"))[bf]=function(){hf.removeChild(this),Fo(a)}}:Ht=function(a){setTimeout(Vo(a),0)});yf.exports={set:_o,clear:No}});var Ef=m((kC,If)=>{"use strict";var Tf=Y(),sP=Le(),nP=Object.getOwnPropertyDescriptor;If.exports=function(a){if(!sP)return Tf[a];var e=nP(Tf,a);return e&&e.value}});var qo=m((RC,Pf)=>{"use strict";var xf=function(){this.head=null,this.tail=null};xf.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}}};Pf.exports=xf});var wf=m(($C,Af)=>{"use strict";var oP=vr();Af.exports=/ipad|iphone|ipod/i.test(oP)&&typeof Pebble!="undefined"});var Rf=m((LC,kf)=>{"use strict";var uP=vr();kf.exports=/web0s(?!.*chrome)/i.test(uP)});var Of=m((MC,Bf)=>{"use strict";var Ar=Y(),lP=Ef(),$f=ci(),Ho=Uo().set,cP=qo(),dP=Mo(),pP=wf(),hP=Rf(),jo=ps(),Lf=Ar.MutationObserver||Ar.WebKitMutationObserver,Mf=Ar.document,Cf=Ar.process,hs=Ar.Promise,Qo=lP("queueMicrotask"),Pr,Go,Wo,fs,Df;Qo||(yi=new cP,Ti=function(){var a,e;for(jo&&(a=Cf.domain)&&a.exit();e=yi.get();)try{e()}catch(t){throw yi.head&&Pr(),t}a&&a.enter()},!dP&&!jo&&!hP&&Lf&&Mf?(Go=!0,Wo=Mf.createTextNode(""),new Lf(Ti).observe(Wo,{characterData:!0}),Pr=function(){Wo.data=Go=!Go}):!pP&&hs&&hs.resolve?(fs=hs.resolve(void 0),fs.constructor=hs,Df=$f(fs.then,fs),Pr=function(){Df(Ti)}):jo?Pr=function(){Cf.nextTick(Ti)}:(Ho=$f(Ho,Ar),Pr=function(){Ho(Ti)}),Qo=function(a){yi.head||Pr(),yi.add(a)});var yi,Ti;Bf.exports=Qo});var _f=m((CC,Vf)=>{"use strict";Vf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var ms=m((DC,Nf)=>{"use strict";Nf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var jt=m((BC,Ff)=>{"use strict";var fP=Y();Ff.exports=fP.Promise});var wr=m((OC,jf)=>{"use strict";var mP=Y(),Ii=jt(),bP=Q(),gP=ao(),SP=Ro(),vP=ne(),Uf=wo(),yP=He(),Yo=Vn(),qf=Ii&&Ii.prototype,TP=vP("species"),zo=!1,Hf=bP(mP.PromiseRejectionEvent),IP=gP("Promise",function(){var a=SP(Ii),e=a!==String(Ii);if(!e&&Yo===66||yP&&!(qf.catch&&qf.finally))return!0;if(!Yo||Yo<51||!/native code/.test(a)){var t=new Ii(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[TP]=r,zo=t.then(function(){})instanceof r,!zo)return!0}return!e&&(Uf==="BROWSER"||Uf==="DENO")&&!Hf});jf.exports={CONSTRUCTOR:IP,REJECTION_EVENT:Hf,SUBCLASSING:zo}});var kr=m((VC,Wf)=>{"use strict";var Gf=it(),EP=TypeError,xP=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new EP("Bad Promise constructor");e=r,t=i}),this.resolve=Gf(e),this.reject=Gf(t)};Wf.exports.f=function(a){return new xP(a)}});var dm=m(()=>{"use strict";var PP=Me(),AP=He(),vs=ps(),yt=Y(),Mr=Ie(),Qf=xr(),Yf=To(),wP=hi(),kP=Wh(),RP=it(),Ss=Q(),$P=$e(),LP=Yh(),MP=Lo(),Zf=Uo().set,eu=Of(),CP=_f(),DP=ms(),BP=qo(),em=to(),ys=jt(),tu=wr(),tm=kr(),Ts="Promise",rm=tu.CONSTRUCTOR,OP=tu.REJECTION_EVENT,VP=tu.SUBCLASSING,Ko=em.getterFor(Ts),_P=em.set,Rr=ys&&ys.prototype,Gt=ys,bs=Rr,im=yt.TypeError,Jo=yt.document,ru=yt.process,Xo=tm.f,NP=Xo,FP=!!(Jo&&Jo.createEvent&&yt.dispatchEvent),am="unhandledrejection",UP="rejectionhandled",zf=0,sm=1,qP=2,iu=1,nm=2,gs,Kf,HP,Jf,om=function(a){var e;return $P(a)&&Ss(e=a.then)?e:!1},um=function(a,e){var t=e.value,r=e.state===sm,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===nm&&GP(e),e.rejection=iu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new im("Promise-chain cycle")):(l=om(u))?Mr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},lm=function(a,e){a.notified||(a.notified=!0,eu(function(){for(var t=a.reactions,r;r=t.get();)um(r,a);a.notified=!1,e&&!a.rejection&&jP(a)}))},cm=function(a,e,t){var r,i;FP?(r=Jo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),yt.dispatchEvent(r)):r={promise:e,reason:t},!OP&&(i=yt["on"+a])?i(r):a===am&&CP("Unhandled promise rejection",t)},jP=function(a){Mr(Zf,yt,function(){var e=a.facade,t=a.value,r=Xf(a),i;if(r&&(i=DP(function(){vs?ru.emit("unhandledRejection",t,e):cm(am,e,t)}),a.rejection=vs||Xf(a)?nm:iu,i.error))throw i.value})},Xf=function(a){return a.rejection!==iu&&!a.parent},GP=function(a){Mr(Zf,yt,function(){var e=a.facade;vs?ru.emit("rejectionHandled",e):cm(UP,e,a.value)})},$r=function(a,e,t){return function(r){a(e,r,t)}},Lr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=qP,lm(a,!0))},Zo=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new im("Promise can't be resolved itself");var r=om(e);r?eu(function(){var i={done:!1};try{Mr(r,e,$r(Zo,i,a),$r(Lr,i,a))}catch(s){Lr(i,s,a)}}):(a.value=e,a.state=sm,lm(a,!1))}catch(i){Lr({done:!1},i,a)}}};if(rm&&(Gt=function(e){LP(this,bs),RP(e),Mr(gs,this);var t=Ko(this);try{e($r(Zo,t),$r(Lr,t))}catch(r){Lr(t,r)}},bs=Gt.prototype,gs=function(e){_P(this,{type:Ts,done:!1,notified:!1,parent:!1,reactions:new BP,rejection:!1,state:zf,value:void 0})},gs.prototype=Qf(bs,"then",function(e,t){var r=Ko(this),i=Xo(MP(this,Gt));return r.parent=!0,i.ok=Ss(e)?e:!0,i.fail=Ss(t)&&t,i.domain=vs?ru.domain:void 0,r.state===zf?r.reactions.add(i):eu(function(){um(i,r)}),i.promise}),Kf=function(){var a=new gs,e=Ko(a);this.promise=a,this.resolve=$r(Zo,e),this.reject=$r(Lr,e)},tm.f=Xo=function(a){return a===Gt||a===HP?new Kf(a):NP(a)},!AP&&Ss(ys)&&Rr!==Object.prototype)){Jf=Rr.then,VP||Qf(Rr,"then",function(e,t){var r=this;return new Gt(function(i,s){Mr(Jf,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Rr.constructor}catch(a){}Yf&&Yf(Rr,bs)}PP({global:!0,constructor:!0,wrap:!0,forced:rm},{Promise:Gt});wP(Gt,Ts,!1,!0);kP(Ts)});var bm=m((FC,mm)=>{"use strict";var WP=ne(),hm=WP("iterator"),fm=!1;try{pm=0,au={next:function(){return{done:!!pm++}},return:function(){fm=!0}},au[hm]=function(){return this},Array.from(au,function(){throw 2})}catch(a){}var pm,au;mm.exports=function(a,e){try{if(!e&&!fm)return!1}catch(i){return!1}var t=!1;try{var r={};r[hm]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var su=m((UC,gm)=>{"use strict";var QP=jt(),YP=bm(),zP=wr().CONSTRUCTOR;gm.exports=zP||!YP(function(a){QP.all(a).then(void 0,function(){})})});var Sm=m(()=>{"use strict";var KP=Me(),JP=Ie(),XP=it(),ZP=kr(),eA=ms(),tA=ls(),rA=su();KP({target:"Promise",stat:!0,forced:rA},{all:function(e){var t=this,r=ZP.f(t),i=r.resolve,s=r.reject,n=eA(function(){var o=XP(t.resolve),u=[],l=0,c=1;tA(e,function(d){var h=l++,p=!1;c++,JP(o,t,d).then(function(f){p||(p=!0,u[h]=f,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var ym=m(()=>{"use strict";var iA=Me(),aA=He(),sA=wr().CONSTRUCTOR,ou=jt(),nA=rt(),oA=Q(),uA=xr(),vm=ou&&ou.prototype;iA({target:"Promise",proto:!0,forced:sA,real:!0},{catch:function(a){return this.then(void 0,a)}});!aA&&oA(ou)&&(nu=nA("Promise").prototype.catch,vm.catch!==nu&&uA(vm,"catch",nu,{unsafe:!0}));var nu});var Tm=m(()=>{"use strict";var lA=Me(),cA=Ie(),dA=it(),pA=kr(),hA=ms(),fA=ls(),mA=su();lA({target:"Promise",stat:!0,forced:mA},{race:function(e){var t=this,r=pA.f(t),i=r.reject,s=hA(function(){var n=dA(t.resolve);fA(e,function(o){cA(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var Im=m(()=>{"use strict";var bA=Me(),gA=kr(),SA=wr().CONSTRUCTOR;bA({target:"Promise",stat:!0,forced:SA},{reject:function(e){var t=gA.f(this),r=t.reject;return r(e),t.promise}})});var uu=m((KC,Em)=>{"use strict";var vA=Ke(),yA=$e(),TA=kr();Em.exports=function(a,e){if(vA(a),yA(e)&&e.constructor===a)return e;var t=TA.f(a),r=t.resolve;return r(e),t.promise}});var Am=m(()=>{"use strict";var IA=Me(),EA=rt(),xm=He(),xA=jt(),Pm=wr().CONSTRUCTOR,PA=uu(),AA=EA("Promise"),wA=xm&&!Pm;IA({target:"Promise",stat:!0,forced:xm||Pm},{resolve:function(e){return PA(wA&&this===AA?xA:this,e)}})});var wm=m(()=>{"use strict";dm();Sm();ym();Tm();Im();Am()});var Lm=m(()=>{"use strict";var kA=Me(),RA=He(),Is=jt(),$A=Te(),Rm=rt(),$m=Q(),LA=Lo(),km=uu(),MA=xr(),cu=Is&&Is.prototype,CA=!!Is&&$A(function(){cu.finally.call({then:function(){}},function(){})});kA({target:"Promise",proto:!0,real:!0,forced:CA},{finally:function(a){var e=LA(this,Rm("Promise")),t=$m(a);return this.then(t?function(r){return km(e,a()).then(function(){return r})}:a,t?function(r){return km(e,a()).then(function(){throw r})}:a)}});!RA&&$m(Is)&&(lu=Rm("Promise").prototype.finally,cu.finally!==lu&&MA(cu,"finally",lu,{unsafe:!0}));var lu});var Es=m((iD,Mm)=>{"use strict";var DA=rt();Mm.exports=DA});var Dm=m((aD,Cm)=>{"use strict";Nh();wm();Lm();var BA=Es();Cm.exports=BA("Promise","finally")});var Om=m((sD,Bm)=>{"use strict";var OA=Dm();Bm.exports=OA});var xs=m((nD,Vm)=>{"use strict";var VA=Om();Vm.exports=VA});var ub=m(()=>{"use strict";var pw=Me(),hw=ni(),fw=es(),mw=Za(),bw=kn();pw({target:"Array",proto:!0},{at:function(e){var t=hw(this),r=fw(t),i=mw(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});bw("at")});var cb=m((m0,lb)=>{"use strict";ub();var gw=Es();lb.exports=gw("Array","at")});var pb=m((b0,db)=>{"use strict";var Sw=cb();db.exports=Sw});var Br=m((g0,hb)=>{"use strict";var vw=pb();hb.exports=vw});var vg=m(()=>{"use strict"});var yg=m(()=>{"use strict"});var Ig=m((T_,Tg)=>{"use strict";var wk=$e(),kk=br(),Rk=ne(),$k=Rk("match");Tg.exports=function(a){var e;return wk(a)&&((e=a[$k])!==void 0?!!e:kk(a)==="RegExp")}});var xg=m((I_,Eg)=>{"use strict";var Lk=pi(),Mk=String;Eg.exports=function(a){if(Lk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return Mk(a)}});var Ag=m((E_,Pg)=>{"use strict";var Ck=Ke();Pg.exports=function(){var a=Ck(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 Rg=m((x_,kg)=>{"use strict";var Dk=Ie(),Bk=je(),Ok=ri(),Vk=Ag(),wg=RegExp.prototype;kg.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in wg)&&!Bk(a,"flags")&&Ok(wg,a)?Dk(Vk,a):e}});var Lg=m((P_,$g)=>{"use strict";var Fu=de(),_k=ni(),Nk=Math.floor,_u=Fu("".charAt),Fk=Fu("".replace),Nu=Fu("".slice),Uk=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,qk=/\$([$&'`]|\d{1,2})/g;$g.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=qk;return i!==void 0&&(i=_k(i),u=Uk),Fk(s,u,function(l,c){var d;switch(_u(c,0)){case"$":return"$";case"&":return a;case"`":return Nu(e,0,t);case"'":return Nu(e,n);case"<":d=i[Nu(c,1,-1)];break;default:var h=+c;if(h===0)return l;if(h>o){var p=Nk(h/10);return p===0?l:p<=o?r[p-1]===void 0?_u(c,1):r[p-1]+_u(c,1):l}d=r[h-1]}return d===void 0?"":d})}});var Dg=m(()=>{"use strict";var Hk=Me(),jk=Ie(),qu=de(),Mg=ei(),Gk=Q(),Wk=gr(),Qk=Ig(),Ur=xg(),Yk=ai(),zk=Rg(),Kk=Lg(),Jk=ne(),Xk=He(),Zk=Jk("replace"),eR=TypeError,Uu=qu("".indexOf),tR=qu("".replace),Cg=qu("".slice),rR=Math.max;Hk({target:"String",proto:!0},{replaceAll:function(e,t){var r=Mg(this),i,s,n,o,u,l,c,d,h,p,f=0,b="";if(!Wk(e)){if(i=Qk(e),i&&(s=Ur(Mg(zk(e))),!~Uu(s,"g")))throw new eR("`.replaceAll` does not allow non-global regexes");if(n=Yk(e,Zk),n)return jk(n,e,r,t);if(Xk&&i)return tR(Ur(r),e,t)}for(o=Ur(r),u=Ur(e),l=Gk(t),l||(t=Ur(t)),c=u.length,d=rR(1,c),h=Uu(o,u);h!==-1;)p=l?Ur(t(u,h,o)):Kk(u,o,h,[],void 0,t),b+=Cg(o,f,h)+p,f=h+c,h=h+d>o.length?-1:Uu(o,u,h+d);return f<o.length&&(b+=Cg(o,f)),b}})});var Og=m((k_,Bg)=>{"use strict";vg();yg();Dg();var iR=Es();Bg.exports=iR("String","replaceAll")});var _g=m((R_,Vg)=>{"use strict";var aR=Og();Vg.exports=aR});var Fg=m(($_,Ng)=>{"use strict";var sR=_g();Ng.exports=sR});var rc="2.0.116-dev.68a2c5fb.0";var ce=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(ce||{}),vt=(S=>(S.MPEG="MPEG",S.DASH="DASH",S.DASH_SEP="DASH_SEP",S.DASH_SEP_VK="DASH_SEP",S.DASH_WEBM="DASH_WEBM",S.DASH_WEBM_AV1="DASH_WEBM_AV1",S.DASH_STREAMS="DASH_STREAMS",S.DASH_WEBM_VK="DASH_WEBM",S.DASH_ONDEMAND="DASH_ONDEMAND",S.DASH_ONDEMAND_VK="DASH_ONDEMAND",S.DASH_LIVE="DASH_LIVE",S.DASH_LIVE_CMAF="DASH_LIVE_CMAF",S.DASH_LIVE_WEBM="DASH_LIVE_WEBM",S.HLS="HLS",S.HLS_ONDEMAND="HLS_ONDEMAND",S.HLS_JS="HLS",S.HLS_LIVE="HLS_LIVE",S.HLS_LIVE_CMAF="HLS_LIVE_CMAF",S.WEB_RTC_LIVE="WEB_RTC_LIVE",S))(vt||{});var Ua=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(Ua||{}),In=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(In||{});var En=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(En||{});import{assertNever as uc,assertNonNullable as Ev,isNonNullable as qa,ValueSubject as xn,Subject as xv,Subscription as Pv,merge as Av,observableFrom as wv,fromEvent as ac,map as sc,tap as nc,filterChanged as kv,isNullable as Pn,ErrorCategory as oc}from"@vkontakte/videoplayer-shared";var ic=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var Ha=class{constructor(e){this.connection$=new xn(void 0);this.castState$=new xn("NOT_AVAILABLE");this.errorEvent$=new xv;this.realCastState$=new xn("NOT_AVAILABLE");this.subscription=new Pv;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=qa((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||ic("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:oc.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,i,s;(s=(i=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:i.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){qa(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Pn(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Pn(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(ac(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{var s,n,o;switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return uc(i.sessionState)}})).add(Av(ac(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(nc(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),sc(i=>i.castState)),wv([r.getCastState()])).pipe(kv(),sc(Rv),nc(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=qa(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();Ev(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Pn(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?qa(this.connection$.getValue())?"CONNECTED":"AVAILABLE":i)}))}initializeCastApi(){var i;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(s){return}try{e.setOptions({receiverApplicationId:(i=this.params.receiverApplicationId)!=null?i:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:oc.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Rv=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 uc(a)}};var US=Ue(Ao(),1);var Qm=Ue(xs(),1);import{assertNever as _m}from"@vkontakte/videoplayer-shared";var re=(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:_m(t)}return a},du=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(a);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(a);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:_m(e)}};var x=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as _A,Subject as Ps,merge as Nm}from"@vkontakte/videoplayer-shared";var L=class{constructor(e){this.transitionStarted$=new Ps;this.transitionEnded$=new Ps;this.transitionUpdated$=new Ps;this.forceChanged$=new Ps;this.stateChangeStarted$=Nm(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Nm(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||_A(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 NA}from"@vkontakte/videoplayer-shared";var Fm=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 NA(a)}};import{assertNever as Cr,assertNonNullable as Wt,debounce as Um,ErrorCategory as qm,fromEvent as Qt,isNonNullable as Hm,map as jm,merge as Gm,observableFrom as FA,Subject as UA,Subscription as pu,timeout as qA,getHighestQuality as HA}from"@vkontakte/videoplayer-shared";var jA=5,GA=5,WA=500,Wm=7e3,Ei=class{constructor(e){this.subscription=new pu;this.loadMediaTimeoutSubscription=new pu;this.videoState=new L("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==null?void 0: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(Fm(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(Gm(this.videoState.stateChangeStarted$.pipe(jm(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(jm(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 UA;e.add(i.pipe(Um(WA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Qt(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)>jA)&&i.next(o),s=o})),e.add(Qt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Qt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Qt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(Qt(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<GA&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),x(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(Qt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(Qt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=Gm(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,FA(["init"])).pipe(Um(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"),x(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),x(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(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),x(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&x(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s: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){var l;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let c=t[e];Wt(c);let d=HA(Object.keys(c));Wt(d);let h=c[d];Wt(h),r=h,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];Wt(c),r=c.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 c=t[e];Wt(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];Wt(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];Wt(c),r=re(c.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:qm.VIDEO_PIPELINE,message:c,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((l=this.params.meta.videoId)!=null?l:r,i);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return Hm(o)&&(n.metadata.title=o),Hm(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(qA(Wm).subscribe(()=>s(`timeout(${Wm})`)))});(0,Qm.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:qm.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as zm}from"@vkontakte/videoplayer-shared";import{clearVideoElement as QA}from"@vkontakte/videoplayer-shared";var Ym=a=>{try{a.pause(),a.playbackRate=0,QA(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as YA,Subscription as zA}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)}},fu=window.WeakMap?new WeakMap:new hu,mu=window.WeakMap?new WeakMap:new Map,KA=(a,e=20)=>{let t=0;return YA(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},pe=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?zm(t):(t=document.createElement("video"),a.appendChild(t)),fu.set(t,r);let i=new zA;return i.add(KA(t,e)),mu.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},he=a=>{let e=mu.get(a);e==null||e.unsubscribe(),mu.delete(a);let t=fu.get(a);fu.delete(a),t?zm(a):Ym(a)};import{assertNonNullable as xi,isNonNullable as Xe,isNullable as ZA,fromEvent as Dr,merge as Km,observableFrom as Jm,filterChanged as Xm,map as Pi,Subject as Zm,Subscription as ew,ValueSubject as tw,ErrorCategory as rw}from"@vkontakte/videoplayer-shared";import{isNonNullable as bu,isNullable as JA,Subscription as XA}from"@vkontakte/videoplayer-shared";var As=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=JA(i),l=new XA;return i&&l.add(i.subscribe(c=>{let d=a.getState();r(c,d)&&a.setState(c)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},Je=(a,e,t)=>As(e,()=>a.loop,r=>{bu(r)&&(a.loop=r)},{onError:t}),fe=(a,e,t,r)=>As(e,()=>({muted:a.muted,volume:a.volume}),i=>{bu(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),Ce=(a,e,t,r)=>As(e,()=>a.playbackRate,i=>{bu(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Tt=As;var iw=a=>["__",a.language,a.label].join("|"),aw=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},gu=class a{constructor(){this.available$=new Zm;this.current$=new tw(void 0);this.error$=new Zm;this.subscription=new ew;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:rw.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(Tt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{Xe(s)&&this.setInternal(s)},{equal:(s,n)=>Xe(s)&&Xe(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:i})),this.subscription.add(Tt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{Xe(s)&&this.setExternal(s)},{equal:(s,n)=>Xe(s)&&Xe(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:i})),this.subscription.add(Tt(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(Tt(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(Dr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(Km(Dr(e,"addtrack"),Dr(e,"removetrack"),Jm(["init"])).pipe(Pi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Xm((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(Km(Dr(e,"change"),Jm(["init"])).pipe(Pi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Pi(r=>r&&this.htmlTextTrackToITextTrack(r).id),Xm()).subscribe(this.current$));let t=r=>{var i,s;return this.applyCueSettings((s=(i=r.target)==null?void 0:i.activeCues)!=null?s:null)};this.subscription.add(Dr(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,h,p;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((h=(d=o.target)==null?void 0:d.cues)!=null?h:null),(p=o.target)==null||p.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(Dr(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.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;Xe(t.align)&&(i.align=t.align),Xe(t.position)&&(i.position=t.position),Xe(t.size)&&(i.size=t.size),Xe(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){xi(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c;let{language:t,label:r}=e,i=e.id?e.id:iw(e),s=this.externalTracks.has(i),n=(s?(o=this.externalTracks.get(i))==null?void 0:o.isAuto:(u=this.internalTracks.get(i))==null?void 0:u.isAuto)||i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(l=this.externalTracks.get(i))==null?void 0:l.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(c=this.internalTracks.get(i))==null?void 0:c.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){xi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(ZA(e)||!aw(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");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=gu;var nt=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 eb=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},Su=a=>{let e=eb(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},tb=a=>{let e=eb(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Be,map as It,merge as ib,filterChanged as nw,isNonNullable as ab,Subject as ow,filter as sb,mapTo as nb,combine as uw,once as lw,ErrorCategory as cw,ValueSubject as ob,clientChecker as dw}from"@vkontakte/videoplayer-shared";var sw=3,rb=(a,e,t=sw)=>{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 me=a=>{let e=S=>Be(a,S).pipe(nb(void 0)),r=ib(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(S=>Be(a,S))).pipe(It(S=>S.type==="ended"?a.readyState<2:a.readyState<3),nw()),i=ib(Be(a,"progress"),Be(a,"timeupdate")).pipe(It(()=>rb(a.buffered,a.currentTime))),s=dw.isSafari?uw({play:e("play").pipe(lw()),playing:e("playing")}).pipe(nb(void 0)):e("playing"),n=Be(a,"volumechange").pipe(It(()=>({muted:a.muted,volume:a.volume}))),o=Be(a,"ratechange").pipe(It(()=>a.playbackRate)),u=Be(a,"error").pipe(sb(()=>!!(a.error||a.played.length)),It(()=>{var E;let S=a.error;return{id:S?`MediaError#${S.code}`:"HtmlVideoError",category:cw.VIDEO_PIPELINE,message:S?S.message:"Error event from HTML video element",thrown:(E=a.error)!=null?E:void 0}})),l=Be(a,"timeupdate").pipe(It(()=>a.currentTime)),c=new ow,d=.3,h;l.subscribe(S=>{a.loop&&ab(h)&&ab(S)&&h>=a.duration-d&&S<=d&&c.next(h),h=S});let p=e("pause").pipe(sb(()=>!a.error&&h!==a.duration)),f=Be(a,"enterpictureinpicture"),b=Be(a,"leavepictureinpicture"),g=new ob(tb(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new ob(Su(a));return Be(a,"fullscreenchange").pipe(It(()=>Su(a))).subscribe(v),{playing$:s,pause$:p,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$:Be(a,"durationchange").pipe(It(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v}};import{VideoQuality as Et}from"@vkontakte/videoplayer-shared";var xt=a=>{switch(a){case"mobile":return Et.Q_144P;case"lowest":return Et.Q_240P;case"low":return Et.Q_360P;case"sd":case"medium":return Et.Q_480P;case"hd":case"high":return Et.Q_720P;case"fullhd":case"full":return Et.Q_1080P;case"quadhd":case"quad":return Et.Q_1440P;case"ultrahd":case"ultra":return Et.Q_2160P}};var Yt=Ue(Br(),1);import{isNonNullable as J,isNullable as yu,now as Tb,isHigher as Tu,isHigherOrEqual as gb,isInvariantQuality as Sb,isLower as vb,isLowerOrEqual as Iu,videoSizeToQuality as yw,assertNotEmptyArray as Ib,assertNonNullable as Tw}from"@vkontakte/videoplayer-shared";var vu=!1,ot={},fb=a=>{vu=a},mb=()=>{ot={}},bb=a=>{a(ot)},Ai=(a,e)=>{var t;vu&&(ot.meta=(t=ot.meta)!=null?t:{},ot.meta[a]=e)},oe=class{constructor(e){this.name=e}next(e){var r,i;if(!vu)return;ot.series=(r=ot.series)!=null?r:{};let t=(i=ot.series[this.name])!=null?i:[];t.push([Date.now(),e]),ot.series[this.name]=t}};var Iw=new oe("best_bitrate"),Eb=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var Eu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),wi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Tb()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},xb='Assertion "ABR Tracks is empty array" failed',ws=(a,e,t,r)=>{var u;let i=[...e].sort(Eu(1)),s=[...t].sort(Eu(1)),n=s.filter(l=>J(l.bitrate)&&J(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Yt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Yt.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,Yt.default)(n,-1):(0,Yt.default)(s,0)},yb=a=>"quality"in a,Pb=(a,e,t,r)=>{var n;let i=J((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&J(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&Tb()-r.history[t.id]<=i&&(!r.last||t.id!==r.last.id);if(t!=null&&t.id&&r&&!s&&r.recordSelection(t),s&&(r!=null&&r.last)){let o=r.last;r==null||r.recordSwitch(o);let u=yb(o)?"video":"audio",l=yb(o)?o.quality:o.bitrate;return e({message:`
|
|
7
7
|
[last ${u} selected] ${l}
|
|
8
|
-
`}),o}return
|
|
8
|
+
`}),o}return r==null||r.recordSwitch(t),t},Pt=(a,{container:e,throughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,abrLogger:h})=>{var B,w,A,U,z;Ib(a,xb);let p=(B=window.devicePixelRatio)!=null?B:1,f=r.usePixelRatio?r.pixelRatioMultiplier*(p-1)+1:1,b=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*f*r.containerSizeFactor,height:e.height*f*r.containerSizeFactor},g=b&&yw(b),v=r.considerPlaybackRate&&J(o)?o:1,T=a.filter(y=>!Sb(y.quality)).sort((y,$)=>Tu(y.quality,$.quality)?-1:1),S=(w=(0,Yt.default)(T,-1))==null?void 0:w.quality,E=(A=(0,Yt.default)(T,0))==null?void 0:A.quality,I=yu(i)||J(i.min)&&J(i.max)&&vb(i.max,i.min)||J(i.min)&&E&&Tu(i.min,E)||J(i.max)&&S&&vb(i.max,S),k=v*Eb(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),C={},R=T.filter(y=>{if(!(g?Iu(y.quality,g):!0))return C[y.quality]="FitsContainer",!1;if(!(J(t)&&isFinite(t)&&J(y.bitrate)?t-s>=y.bitrate*k:!0))return C[y.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&J(r.minBufferToSwitchUp)&&u&&!Sb(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&Tu(y.quality,u.quality))return C[y.quality]="Buffer",!1;if(!!d&&gb(y.quality,d))return C[y.quality]="DroppedFramesLimit",!1;let _e=I||(yu(i.max)||Iu(y.quality,i.max))&&(yu(i.min)||gb(y.quality,i.min)),or=J(c)&&!c?Iu(y.quality,r.backgroundVideoQualityLimit):!0;return!_e||!or?(C[y.quality]="FitsQualityLimits",!1):!0})[0];R&&R.bitrate&&Iw.next(R.bitrate);let D=(U=R!=null?R:T[Math.ceil((T.length-1)/2)])!=null?U:a[0];return D.quality!==((z=l==null?void 0:l.last)==null?void 0:z.quality)&&h({message:`
|
|
9
9
|
[VIDEO TRACKS ABR]
|
|
10
10
|
[available video tracks]
|
|
11
|
-
${a.map(
|
|
11
|
+
${a.map(y=>`{ id: ${y.id}, quality: ${y.quality}, bitrate: ${y.bitrate} }`).join(`
|
|
12
12
|
`)}
|
|
13
13
|
|
|
14
14
|
[tuning]
|
|
15
|
-
${Object.entries(
|
|
15
|
+
${Object.entries(r!=null?r:{}).map(([y,$])=>`${y}: ${$}`).join(`
|
|
16
16
|
`)}
|
|
17
17
|
|
|
18
18
|
[limit params]
|
|
@@ -20,49 +20,49 @@ var Sv=Object.create;var ac=Object.defineProperty;var vv=Object.getOwnPropertyDe
|
|
|
20
20
|
throughput: ${t},
|
|
21
21
|
reserve: ${s},
|
|
22
22
|
playbackRate: ${o},
|
|
23
|
-
playbackRateFactor: ${
|
|
23
|
+
playbackRateFactor: ${v},
|
|
24
24
|
forwardBufferHealth: ${n},
|
|
25
25
|
bitrateFactor: ${k},
|
|
26
|
-
minBufferToSwitchUp: ${
|
|
26
|
+
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
27
27
|
droppedVideoMaxQualityLimit: ${d},
|
|
28
|
-
limitsAreInvalid: ${
|
|
29
|
-
maxQualityLimit: ${
|
|
30
|
-
minQualityLimit: ${
|
|
28
|
+
limitsAreInvalid: ${I},
|
|
29
|
+
maxQualityLimit: ${i==null?void 0:i.max},
|
|
30
|
+
minQualityLimit: ${i==null?void 0:i.min},
|
|
31
31
|
|
|
32
32
|
[limited video tracks]
|
|
33
|
-
${Object.entries(C).map(([
|
|
33
|
+
${Object.entries(C).map(([y,$])=>`${y}: ${$}`).join(`
|
|
34
34
|
`)||"All tracks are available"}
|
|
35
35
|
|
|
36
|
-
[best video track] ${
|
|
37
|
-
[selected video track] ${
|
|
38
|
-
`}),
|
|
36
|
+
[best video track] ${R==null?void 0:R.quality}
|
|
37
|
+
[selected video track] ${D==null?void 0:D.quality}
|
|
38
|
+
`}),Pb(r,h,D,l)},Ab=(a,e,t,{throughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u})=>{var b;Ib(t,xb);let l=i.considerPlaybackRate&&J(s)?s:1,c=[...t].sort(Eu(-1)),d=a.bitrate;Tw(d);let h=l*Eb(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),p,f=ws(a,e,t,i.minVideoAudioRatio);return J(r)&&isFinite(r)&&(p=c.find(g=>J(g.bitrate)&&J(f==null?void 0:f.bitrate)?r-d>=g.bitrate*h&&g.bitrate>=f.bitrate:!1)),p||(p=f),(p==null?void 0:p.bitrate)!==((b=o==null?void 0:o.last)==null?void 0:b.bitrate)&&u({message:`
|
|
39
39
|
[AUDIO TRACKS ABR]
|
|
40
40
|
[available audio tracks]
|
|
41
41
|
${t.map(g=>`{ id: ${g.id}, bitrate: ${g.bitrate} }`).join(`
|
|
42
42
|
`)}
|
|
43
43
|
|
|
44
44
|
[tuning]
|
|
45
|
-
${Object.entries(
|
|
45
|
+
${Object.entries(i!=null?i:{}).map(([g,v])=>`${g}: ${v}`).join(`
|
|
46
46
|
`)}
|
|
47
47
|
|
|
48
48
|
[limit params]
|
|
49
|
-
throughput: ${
|
|
49
|
+
throughput: ${r},
|
|
50
50
|
reserve: ${d},
|
|
51
51
|
playbackRate: ${s},
|
|
52
52
|
playbackRateFactor: ${l},
|
|
53
53
|
forwardBufferHealth: ${n},
|
|
54
54
|
bitrateFactor: ${h},
|
|
55
|
-
minBufferToSwitchUp: ${
|
|
55
|
+
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
56
56
|
|
|
57
57
|
[selected audio track] ${p==null?void 0:p.id}
|
|
58
|
-
`}),p&&kb(r,u,p,o)};var Z=a=>new URL(a).hostname;import{assertNever as Bb,assertNonNullable as Ob,combine as jw,debounce as Gw,ErrorCategory as Vb,filter as _b,filterChanged as Ww,isNonNullable as Mu,map as Cs,merge as Nb,observableFrom as Yw,once as Qw,Subscription as zw,ValueSubject as Cu,videoQualityToHeight as Kw,videoSizeToQuality as Jw}from"@vkontakte/videoplayer-shared";var $b=a=>{if(a instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},be=async(a,e)=>{let t=a.muted;try{await a.play()}catch(i){if(!$b(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{await a.play()}catch(r){return $b(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as $s,isNullable as Aw,assertNonNullable as Mr}from"@vkontakte/videoplayer-shared";import{isNonNullable as Lb,assertNonNullable as Rs,now as xw}from"@vkontakte/videoplayer-shared";function ee(){return xw()}function ku(a){return ee()-a}function Ru(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Mb(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function Bi(a,e,t,i){let r=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,h=!1,p="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;Rs(c);let R=ku(c),w;if(R<b){w=b-R,setTimeout(g,w);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new r,k()},y=R=>(s=R,O),I=R=>(d=R,O),S=()=>(p="json",O),T=()=>{if(!u){if(--l>=0){g(),i&&i();return}u=!0,d&&d(),t&&t()}},E=R=>(h=R,O),k=()=>{c=ee(),n=new r,n.open("get",a);let R=0,w,U=0,z=()=>(Rs(c),Math.max(c,Math.max(w||0,U||0)));if(s&&n.addEventListener("progress",v=>{let L=ee();s.updateChunk&&v.loaded>R&&(s.updateChunk(z(),v.loaded-R),R=v.loaded,w=L)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>T())),n.addEventListener("load",()=>{if(u)return;Rs(n);let v=n.status;if(v>=200&&v<300){if(n.response.byteLength&&s){let L=n.response.byteLength-R;L&&s.updateChunk&&s.updateChunk(z(),L)}n.responseType==="json"&&!Object.values(n.response).length?T():(d&&d(),e(n.response))}else T()}),n.addEventListener("error",()=>{T()}),h){let v=()=>{Rs(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(U=ee(),n.removeEventListener("readystatechange",v))};n.addEventListener("readystatechange",v)}return n.responseType=p,n.send(),O},O={withBitrateReporting:y,withParallel:E,withJSONResponse:S,withRetryCount:R=>(l=R,O),withRetryInterval:(R,w)=>(Lb(R)&&(b=R),Lb(w)&&(f=w),O),withTimeout:R=>(o=R,O),withFinally:I,send:k,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return O}var $r=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;i+=n;let u=s.bytes*n/o;r+=u,s.start=t,s.bytes-=u}}}if(r>0&&i>0){let s=r*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Lr=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=ee(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=ee()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Bi(t,s,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ee()}_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=ee();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=r,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as ww}from"@vkontakte/videoplayer-shared";var Ls=1e4,$u=3;var kw=6e4,Rw=10,$w=1,Lw=500,Cr=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 ww,this.chunkRateEstimator=new $r(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Ru(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){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=Ru(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,n=t&&1.62*(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)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s));return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||$s(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Mb(r,"progress",()=>{r.buffered.length?(r.currentTime=r.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 Lr($u,Ls,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let T=s&&(!c||c===this.rep);return T||t("Not running!"),T},h=(T,E,k)=>{u&&u.abort(),u=Bi(this.urlResolver.resolve(T,!1),E,k,()=>this._retryCallback()).withTimeout(Ls).withBitrateReporting(this.bitrateSwitcher).withRetryCount($u).withFinally(()=>{u=null}).send()},p=(T,E,k)=>{Mr(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(T,!1),E,k,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=T=>{let E=i.playbackRate;i.playbackRate!==T&&(t(`Playback rate switch: ${E}=>${T}`),i.playbackRate=T)},b=T=>{this.lowLatency=T,t(`lowLatency changed to ${T}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let T=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let k=ee()-1e4,C=0;for(let $=0;$<this.bufferStates.length;$++){let B=this.bufferStates[$];T=Math.min(T,B.buf),B.ts<k&&C++}this.bufferStates.splice(0,C),t(`update playback rate; minBuffer=${T} drop=${C} jitter=${this.sourceJitter}`);let N=T-$w;this.sourceJitter>=0?N-=this.sourceJitter/2:this.sourceJitter-=1,N>3?f(1.15):N>1?f(1.1):N>.3?f(1.05):f(1)}},y=T=>{let E,k=()=>E&&E.start?E.start.length:0,C=v=>E.start[v]/1e3,N=v=>E.dur[v]/1e3,$=v=>E.fragIndex+v,B=(v,L)=>({chunkIdx:$(v),startTS:C(v),dur:N(v),discontinuity:L}),O=()=>{let v=0;if(E&&E.dur){let L=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,H=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,G=L;this.sourceJitter>1&&(G+=this.sourceJitter-1);let K=E.dur.length-1;for(;K>=0&&(G-=E.dur[K],!(G<=0));--K);v=Math.min(K,E.dur.length-1-H),v=Math.max(v,0)}return B(v,!0)},R=v=>{let L=k();if(!(L<=0)){if($s(v)){for(let H=0;H<L;H++)if(C(H)>v)return B(H)}return O()}},w=v=>{let L=k(),H=v?v.chunkIdx+1:0,G=H-E.fragIndex;if(!(L<=0)){if(!v||G<0||G-L>Rw)return t(`Resync: offset=${G} bChunks=${L} chunk=`+JSON.stringify(v)),O();if(!(G>=L))return B(H-E.fragIndex,!1)}},U=(v,L,H)=>{l&&l.abort(),l=Bi(this.urlResolver.resolve(v,!0,this.lowLatency),L,H,()=>this._retryCallback()).withTimeout(Ls).withRetryCount($u).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(v,L)=>{U(T,H=>{if(!d())return;E=H;let G=!!E.lowLatency;G!==this.lowLatency&&b(G);let K=0;for(let ue=0;ue<E.dur.length;++ue)K+=E.dur[ue];K>0&&(Mr(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(K/E.dur.length)),r({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,v(R(L))},()=>this._handleNetworkError())},nextChunk:w}},I=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Mr(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:T=>{let{videoElement:E,logger:k}=this.params,C=y(e.jidxUrl),N,$,B,O,R=0,w,U,z,v=()=>{w&&(clearTimeout(w),w=void 0);let A=Math.max(Lw,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),le=R+A,Ie=ee(),ke=Math.min(1e4,le-Ie);R=Ie;let mt=()=>{l||d()&&C.seek(()=>{d()&&(R=ee(),L(),v())})};ke>0?w=window.setTimeout(()=>{this.paused?v():mt()},ke):mt()},L=()=>{let A;for(;A=C.nextChunk(O);)O=A,tt(A);let le=C.nextChunk(B);if(le){if(B&&le.discontinuity){k("Detected discontinuity; restarting playback"),this.paused?v():(I(),this._initPlayerWith(e));return}ue(le)}else v()},H=(A,le)=>{if(!d()||!this.sourceBuffer)return;let Ie,ke,mt,oi=bt=>{window.setTimeout(()=>{d()&&H(A,le)},bt)};if(this.sourceBuffer.updating)k("Source buffer is updating; delaying appendBuffer"),oi(100);else{let bt=ee(),Dt=E.currentTime;!this.paused&&E.buffered.length>1&&U===Dt&&bt-z>500&&(k("Stall suspected; trying to fix"),this._fixupStall()),U!==Dt&&(U=Dt,z=bt);let ui=this._getBufferSizeSec();if(ui>30)k(`Buffered ${ui} seconds; delaying appendBuffer`),oi(2e3);else try{this.sourceBuffer.appendBuffer(A),this.videoPlayStarted?(this.bufferStates.push({ts:bt,buf:ui}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),le&&le()}catch(zi){if(zi.name==="QuotaExceededError")k("QuotaExceededError; delaying appendBuffer"),mt=this.sourceBuffer.buffered.length,mt!==0&&(Ie=this.sourceBuffer.buffered.start(0),ke=Dt,ke-Ie>4&&this.sourceBuffer.remove(Ie,ke-3)),oi(1e3);else throw zi}}},G=()=>{$&&N&&(k([`Appending chunk, sz=${$.byteLength}:`,JSON.stringify(B)]),H($,function(){$=null,L()}))},K=A=>e.fragUrlTemplate.replace("%%id%%",A.chunkIdx),ue=A=>{d()&&p(K(A),(le,Ie)=>{if(d()){if(Ie/=1e3,$=le,B=A,n=A.startTS,Ie){let ke=Math.min(10,A.dur/Ie);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ke:ke}G()}},()=>this._handleNetworkError())},tt=A=>{d()&&(Mr(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(K(A),!1)))},ft=A=>{d()&&(e.cachedHeader=A,H(A,()=>{N=!0,G()}))};s=!0,C.seek(A=>{if(d()){if(R=ee(),!A){v();return}O=A,!Aw(T)||A.startTS>T?ue(A):(B=A,L())}},T),e.cachedHeader?ft(e.cachedHeader):h(e.headerUrl,ft,()=>this._handleNetworkError())},stop:I,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),$s(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Mr(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return $s(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=d=>{if(!this.autoQuality)return;let h,p,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),f=d/this.bitrate,p>10&&f>.8||p>15&&f>.5||p>20&&f>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}h=this._selectQuality(d),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(h,p)=>{let f=ee();if(this.chunkRateEstimator.addInterval(h,f,p)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:f-h,speed:g}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.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;i(d)}u=this.autoQuality};return{updateChunk:(d,h)=>{let p=s.updateChunk(d,h);return p&&l(),p},notifySwitch:d=>{let h=ee();d<o&&(n=h),o=d}}}_fetchManifest(e,t,i){this.manifestRequest=Bi(this.urlResolver.resolve(e,!0),t,i,()=>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;be(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},kw))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as Mw,filter as Cb,fromEvent as Cw,interval as Dw,isHigher as Bw,isInvariantQuality as Ow,isLower as Vw,merge as _w,Subject as Db,Subscription as Nw}from"@vkontakte/videoplayer-shared";var Lu=class{constructor(){this.onDroopedVideoFramesLimit$=new Db;this.subscription=new Nw;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==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!Ow(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&Bw(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(Cw(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=Dw(this.droppedFramesChecker.checkTime).pipe(Cb(()=>this.playing),Cb(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(Mw(this.droppedFramesChecker.checkTime)),i=_w(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var i,r;let t=(r=(i=Object.entries(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>Vw(s,n)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Ms=Lu;import{map as Fw,Observable as Uw}from"@vkontakte/videoplayer-shared";import{fromEvent as qw}from"@vkontakte/videoplayer-shared";var Dr=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var Hw=(a,e)=>new Uw(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Dr()))},{...i,...e});r.observe(a);let s=qw(document,"visibilitychange").pipe(Fw(n=>!document.hidden||Dr())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe}}),Oe=Hw;var Xw=["paused","playing","ready"],Zw=["paused","playing","ready"],Br=class{constructor(e){this.subscription=new zw;this.videoState=new M("stopped");this.representations$=new Cu([]);this.textTracksManager=new De;this.droppedFramesManager=new Ms;this.maxSeekBackTime$=new Cu(1/0);this.zeroTime$=new Cu(void 0);this.liveOffset=new ot;this._dashCb=e=>{var t,i,r,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Vb.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(i=wt(u.name))!=null?i:Jw(u.video),d=u.bitrate/1e3,h={...u.video};if(!c)continue;let p={id:l,quality:c,bitrate:d,size:h};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),Mu(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Zw.includes(e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&Xw.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ie(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(ie(this.params.source.url,u))}return;default:return Bb(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Vb.WTF,message:"DashLiveProvider internal logic error",thrown:r})};Nb(this.videoState.stateChangeStarted$.pipe(Cs(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Cs(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})}),this.video=pe(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Z(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=me(this.video);this.subscription.add(this.representations$.pipe(Cs(r=>r.map(({track:s})=>s)),_b(r=>!!r.length),Qw()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())==null?void 0:r.to)==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(Ww(),Cs(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(jw({zeroTime:this.zeroTime$.pipe(_b(Mu)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(Je(this.video,this.params.desiredState.isLooped,t)).add(fe(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Ce(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Oe(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{let s=r&&Kw(r);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var s;switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return Bb(r.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$,Yw(["init"])).pipe(Gw(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),he(this.video)}createLiveDashPlayer(){let e=new Cr({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(){var l,c,d,h,p,f;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),i=(h=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?h:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&Mu(t)?t:kt(e.map(({track:b})=>b),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||s!==o){let b=(f=e.find(({track:g})=>g.id===s))==null?void 0:f.representation;Ob(b,"Representations missing"),this.dash.startPlay(b,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;Ob(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ie(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Fb=Br;var Ze=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as RR,assertNonNullable as $R,debounce as LR,ErrorCategory as ul,filter as hS,filterChanged as ll,fromEvent as MR,isNonNullable as CR,map as fS,merge as nn,observableFrom as DR,observeElementSize as BR,once as mS,Subscription as OR,ValueSubject as VR}from"@vkontakte/videoplayer-shared";var Ds=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,s=i.length;r<s;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,s=i.length;r<s;r++){let n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Oi=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)}},Or=class{constructor(){Object.defineProperty(this,"signal",{value:new Oi,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(r){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Or.prototype[Symbol.toStringTag]="AbortController",Oi.prototype[Symbol.toStringTag]="AbortSignal");function Bs(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:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!Bs({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let h=new t(l,c);return d&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),h},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(p){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let h=new Promise((p,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([h,n(u,l)])}return n(u,l)},Request:s}}var Vr=Bs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Ub=Vr?Du({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,lt=Vr?Ub.fetch:window.fetch,NB=Vr?Ub.Request:window.Request,Ge=Vr?Or:window.AbortController,FB=Vr?Oi:window.AbortSignal;var js=Fe(Di(),1);var ct=()=>window.ManagedMediaSource||window.MediaSource,Os=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},qb=()=>{var a,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Hb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Ws,clientChecker as Gs}from"@vkontakte/videoplayer-shared";var Ve=document.createElement("video"),ik='video/mp4; codecs="avc1.42000a,mp4a.40.2"',rk='video/mp4; codecs="hev1.1.6.L93.B0"',eg='video/webm; codecs="vp09.00.10.08"',tg='video/webm; codecs="av01.0.00M.08"',ak='audio/mp4; codecs="mp4a.40.2"',sk='audio/webm; codecs="opus"',jb,Gb,Qt={mms:Os(),mse:qb(),hls:!!((jb=Ve.canPlayType)!=null&&jb.call(Ve,"application/x-mpegurl")||(Gb=Ve.canPlayType)!=null&&Gb.call(Ve,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Wb,Yb,ge={mp4:!!((Wb=Ve.canPlayType)!=null&&Wb.call(Ve,"video/mp4")),webm:!!((Yb=Ve.canPlayType)!=null&&Yb.call(Ve,"video/webm")),cmaf:!0},_s,Qb,Ns,zb,Fs,Kb,Us,Jb,qs,Xb,Hs,Zb,Se={h264:!!((Qb=(_s=ct())==null?void 0:_s.isTypeSupported)!=null&&Qb.call(_s,ik)),h265:!!((zb=(Ns=ct())==null?void 0:Ns.isTypeSupported)!=null&&zb.call(Ns,rk)),vp9:!!((Kb=(Fs=ct())==null?void 0:Fs.isTypeSupported)!=null&&Kb.call(Fs,eg)),av1:!!((Jb=(Us=ct())==null?void 0:Us.isTypeSupported)!=null&&Jb.call(Us,tg)),aac:!!((Xb=(qs=ct())==null?void 0:qs.isTypeSupported)!=null&&Xb.call(qs,ak)),opus:!!((Zb=(Hs=ct())==null?void 0:Hs.isTypeSupported)!=null&&Zb.call(Hs,sk))},Vi=(Se.h264||Se.h265)&&Se.aac,zt,nk=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:tg}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:eg}})]);zt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{nk()}catch(a){console.error(a)}var _i=Qt.hls&&ge.mp4,ig=()=>Object.keys(Se).filter(a=>Se[a]),rg=(a,e=!1,t=!1)=>{let i=Qt.mse||Qt.mms&&t;return a.filter(r=>{switch(r){case"DASH_SEP":return i&&ge.mp4&&Vi;case"DASH_WEBM":return i&&ge.webm&&Se.vp9&&Se.opus;case"DASH_WEBM_AV1":return i&&ge.webm&&Se.av1&&Se.opus;case"DASH_STREAMS":return i&&(ge.mp4&&Vi||ge.webm&&(Se.vp9||Se.av1)&&(Se.opus||Se.aac));case"DASH_LIVE":return Qt.mse&&ge.mp4&&Vi;case"DASH_LIVE_CMAF":return i&&ge.mp4&&Vi&&ge.cmaf;case"DASH_ONDEMAND":return i&&ge.mp4&&Vi;case"HLS":case"HLS_ONDEMAND":return _i||e&&Qt.mse&&ge.mp4&&Vi;case"HLS_LIVE":case"HLS_LIVE_CMAF":return _i;case"MPEG":return ge.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Qt.webrtc&&Qt.ws&&Se.h264&&(ge.mp4||ge.webm);default:return Ws(r)}})},Vs=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:Ws(a)}return[e,t]},ag=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...Vs(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Gs.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...Vs(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Vs(a),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Vs(a),...r,"HLS","HLS_ONDEMAND"];default:Ws(e)}return _i?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},sg=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],n=[...r,...i],o,u=Gs.isMac&&Gs.isSafari;if(Gs.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:Ws(a)}else _i&&!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"],ng=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,js.default)(t.value.split("."),0)}for(let t of a){let i=(0,js.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,js.default)(e.value.split("."),0)};import{ErrorCategory as _r}from"@vkontakte/videoplayer-shared";var og=a=>{if(!a)return{id:"EmptyResponse",category:_r.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:_r.NETWORK,message:`UV Error ${a}`};let e=a.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:_r.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:_r.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:_r.PARSER,message:"Response is valid XML, but parser failed"}};var Ni=(a,e)=>{for(let t=0;t<a.length;t++)if(a.start(t)*1e3<=e&&a.end(t)*1e3>e)return!0;return!1};import{abortable as al,assertNonNullable as ri,clientChecker as SR,combine as en,ErrorCategory as pt,filter as sl,filterChanged as oS,flattenObject as ma,fromEvent as ai,getTraceSubscriptionMethod as vR,interval as nl,isNonNullable as uS,map as ol,merge as si,now as yR,Subject as lS,Subscription as cS,tap as TR,throttle as IR,ValueSubject as re}from"@vkontakte/videoplayer-shared";var ji=Fe(Di(),1);var ok=(a,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},uk=a=>window.clearTimeout(a),ug=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),lg=!ug(window.requestIdleCallback)||!ug(window.cancelIdleCallback),Ou=lg?ok:window.requestIdleCallback,eO=lg?uk:window.cancelIdleCallback;var eS=Fe(Ps(),1);import{assertNever as lk,ErrorCategory as cg,clientChecker as Vu,Subject as dg}from"@vkontakte/videoplayer-shared";var ck=16,pg=!1;try{pg=Vu.isSafari&&!!Vu.macVersion&&Vu.macVersion<=ck}catch(a){console.error(a)}var _u=class{constructor(e){this.bufferFull$=new dg;this.error$=new dg;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:cg.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i;pg&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(let{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:cg.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:lk(t)}}},hg=_u;var Nu=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};import{abortable as Zt,assertNonNullable as ve,ErrorCategory as ei,fromEvent as Zu,getExponentialDelay as el,isNonNullable as oa,isNullable as ye,now as zs,once as uR,Subject as lR,Subscription as cR,ValueSubject as ua}from"@vkontakte/videoplayer-shared";var F=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,r),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Fi=class extends F{};var Nr=class extends F{};var Fr=class extends F{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var Ur=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var qr=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Hr=class extends F{constructor(e,t){super(e,t),this.data=this.content}};var Q=class extends F{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Kt=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 i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var jr=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Gr=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Wr=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 Yr=class extends Q{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Qr=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 zr=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Kr=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 Jr=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Xr=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Zr=class extends Q{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ea=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ta=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 ia=class extends Q{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var ra=class extends Q{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var pk={ftyp:Fr,moov:Ur,moof:qr,mdat:Hr,sidx:Kt,trak:jr,mdia:zr,mfhd:Zr,tkhd:Kr,traf:ea,tfhd:ta,tfdt:ia,trun:ra,minf:Jr,sv3d:Gr,st3d:Wr,prhd:Yr,proj:Xr,equi:Qr,uuid:Nr,unknown:Fi},Jt=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=pk[e];return i?new i(t,new a):new Fi(t,new a)}};var Ui=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,s;(s=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var fk=new TextDecoder("ascii"),mk=a=>fk.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",bk=a=>{let e=new Kt(a,new Jt),t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},gk=(a,e)=>{let i=new Jt().parse(a),r=new Ui(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},Sk=(a,e)=>{let i=new Jt().parse(a),s=new Ui(i).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,h)=>d+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},vk=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new Jt().parse(a),r=new Ui(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},fg={validateData:mk,parseInit:vk,getIndexRange:()=>{},parseSegments:bk,parseFeedableSegmentChunk:gk,getSegmentEndTime:Sk};import{assertNonNullable as Uu,isNonNullable as Sg,isNullable as Tk}from"@vkontakte/videoplayer-shared";import{assertNever as yk}from"@vkontakte/videoplayer-shared";var mg={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"}},bg=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=aa(a,t),r=i in mg,s=r?mg[i].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,c=aa(u),d=l*2**((o-1)*8)+c,h=t+o,p;return h+d>a.byteLength?p=new DataView(a.buffer,a.byteOffset+h):p=new DataView(a.buffer,a.byteOffset+h,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:h,tagSize:h+d,value:p,valueSize:d}},aa=(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},We=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return aa(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:yk(e)}},Xt=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=bg(i);if(!e(r))return;r.type==="master"&&Xt(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},gg=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=bg(a);return Xt(r.value,({tag:s,type:n,value:o})=>(s===17143?e=We(o,n):s===17026?t=We(o,n):s===17029&&(i=We(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var vg=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Ik=[231,22612,22743,167,171,163,160,175],Ek=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return Xt(a,({tag:h,type:p,value:f,valueSize:b})=>{if(h===21419){let g=We(f,p);l=aa(g)}else h!==21420&&(l=void 0);return h===408125543?(e=f.byteOffset,t=f.byteOffset+b):h===357149030?s=!0:h===290298740?n=!0:h===2807729?i=We(f,p):h===17545?r=We(f,p):h===21420&&l===475249515?u=We(f,p):h===374648427?Xt(f,({tag:g,type:y,value:I})=>g===30321?(c=We(I,y)===1,!1):!0):s&&n&&vg.includes(h)&&(o=!0),!o}),Uu(e,"Failed to parse webm Segment start"),Uu(t,"Failed to parse webm Segment end"),Uu(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},xk=a=>{if(Tk(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Pk=(a,e)=>{let t=!1,i=!1,r=o=>Sg(o.time)&&Sg(o.position),s=[],n;return Xt(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=We(l,u));break;case 183:break;case 241:n&&(n.position=We(l,u));break;default:t&&vg.includes(o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},Ak=a=>{let e=0,t=!1;try{Xt(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Ik.includes(i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||(t=[163,160,175].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},yg={validateData:gg,parseInit:Ek,getIndexRange:xk,parseSegments:Pk,parseFeedableSegmentChunk:Ak};var qi=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return yg;case"mp4":return fg}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Qu=Fe(qg(),1),Qg=Fe(Di(),1);var Yu=a=>{let e=a.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,s,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,n]=r.toUpperCase(),o=s+n;return["6E","7A","F4"].includes(o)}}return!1};import{isNonNullable as Gg,isNullable as Wg}from"@vkontakte/videoplayer-shared";var Hg=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var jg=a=>{var e;try{let t=nR(),i=a.match(t),{groups:r}=i!=null?i:{};if(r){let s={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function nR(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
|
|
58
|
+
`}),p&&Pb(i,u,p,o)};var X=a=>new URL(a).hostname;import{assertNever as Mb,assertNonNullable as Cb,combine as Hw,debounce as jw,ErrorCategory as Db,filter as Bb,filterChanged as Gw,isNonNullable as ku,map as Ms,merge as Ob,observableFrom as Ww,once as Qw,Subscription as Yw,ValueSubject as Ru,videoQualityToHeight as zw,videoSizeToQuality as Kw}from"@vkontakte/videoplayer-shared";var wb=a=>{if(a instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},be=async(a,e)=>{let t=a.muted;try{await a.play()}catch(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 Pw,assertNonNullable as $i}from"@vkontakte/videoplayer-shared";import{isNonNullable as kb,assertNonNullable as ks,now as Ew}from"@vkontakte/videoplayer-shared";function Z(){return Ew()}function xu(a){return Z()-a}function Pu(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 Rb(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function Or(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,h=!1,p="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;ks(c);let w=xu(c),A;if(w<b){A=b-w,setTimeout(g,A);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,k()},v=w=>(s=w,B),T=w=>(d=w,B),S=()=>(p="json",B),E=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},I=w=>(h=w,B),k=()=>{c=Z(),n=new i,n.open("get",a);let w=0,A,U=0,z=()=>(ks(c),Math.max(c,Math.max(A||0,U||0)));if(s&&n.addEventListener("progress",y=>{let $=Z();s.updateChunk&&y.loaded>w&&(s.updateChunk(z(),y.loaded-w),w=y.loaded,A=$)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(u)return;ks(n);let y=n.status;if(y>=200&&y<300){if(n.response.byteLength&&s){let $=n.response.byteLength-w;$&&s.updateChunk&&s.updateChunk(z(),$)}n.responseType==="json"&&!Object.values(n.response).length?E():(d&&d(),e(n.response))}else E()}),n.addEventListener("error",()=>{E()}),h){let y=()=>{ks(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(U=Z(),n.removeEventListener("readystatechange",y))};n.addEventListener("readystatechange",y)}return n.responseType=p,n.send(),B},B={withBitrateReporting:v,withParallel:I,withJSONResponse:S,withRetryCount:w=>(l=w,B),withRetryInterval:(w,A)=>(kb(w)&&(b=w),kb(A)&&(f=A),B),withTimeout:w=>(o=w,B),withFinally:T,send:k,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return B}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 Ri=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=Z(),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=Z()-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=Or(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=Z()}_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=Z();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(){Object.values(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 Aw}from"@vkontakte/videoplayer-shared";var $s=1e4,Au=3;var ww=6e4,kw=10,Rw=1,$w=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 Aw,this.chunkRateEstimator=new ki(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Pu(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=Pu(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",()=>{var i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)==null?void 0:i.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=()=>{Rb(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 Ri(Au,$s,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,c=!1,d=()=>{let E=s&&(!c||c===this.rep);return E||t("Not running!"),E},h=(E,I,k)=>{u&&u.abort(),u=Or(this.urlResolver.resolve(E,!1),I,k,()=>this._retryCallback()).withTimeout($s).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Au).withFinally(()=>{u=null}).send()},p=(E,I,k)=>{$i(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),I,k,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=E=>{let I=r.playbackRate;r.playbackRate!==E&&(t(`Playback rate switch: ${I}=>${E}`),r.playbackRate=E)},b=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let k=Z()-1e4,C=0;for(let R=0;R<this.bufferStates.length;R++){let D=this.bufferStates[R];E=Math.min(E,D.buf),D.ts<k&&C++}this.bufferStates.splice(0,C),t(`update playback rate; minBuffer=${E} drop=${C} jitter=${this.sourceJitter}`);let q=E-Rw;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=E=>{let I,k=()=>I&&I.start?I.start.length:0,C=y=>I.start[y]/1e3,q=y=>I.dur[y]/1e3,R=y=>I.fragIndex+y,D=(y,$)=>({chunkIdx:R(y),startTS:C(y),dur:q(y),discontinuity:$}),B=()=>{let y=0;if(I&&I.dur){let $=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,j=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,O=$;this.sourceJitter>1&&(O+=this.sourceJitter-1);let ae=I.dur.length-1;for(;ae>=0&&(O-=I.dur[ae],!(O<=0));--ae);y=Math.min(ae,I.dur.length-1-j),y=Math.max(y,0)}return D(y,!0)},w=y=>{let $=k();if(!($<=0)){if(Rs(y)){for(let j=0;j<$;j++)if(C(j)>y)return D(j)}return B()}},A=y=>{let $=k(),j=y?y.chunkIdx+1:0,O=j-I.fragIndex;if(!($<=0)){if(!y||O<0||O-$>kw)return t(`Resync: offset=${O} bChunks=${$} chunk=`+JSON.stringify(y)),B();if(!(O>=$))return D(j-I.fragIndex,!1)}},U=(y,$,j)=>{l&&l.abort(),l=Or(this.urlResolver.resolve(y,!0,this.lowLatency),$,j,()=>this._retryCallback()).withTimeout($s).withRetryCount(Au).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(y,$)=>{U(E,j=>{if(!d())return;I=j;let O=!!I.lowLatency;O!==this.lowLatency&&b(O);let ae=0;for(let _e=0;_e<I.dur.length;++_e)ae+=I.dur[_e];ae>0&&($i(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ae/I.dur.length)),i({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,y(w($))},()=>this._handleNetworkError())},nextChunk:A}},T=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),$i(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:E=>{let{videoElement:I,logger:k}=this.params,C=v(e.jidxUrl),q,R,D,B,w=0,A,U,z,y=()=>{A&&(clearTimeout(A),A=void 0);let N=Math.max($w,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),le=w+N,ye=Z(),ke=Math.min(1e4,le-ye);w=ye;let pt=()=>{l||d()&&C.seek(()=>{d()&&(w=Z(),$(),y())})};ke>0?A=window.setTimeout(()=>{this.paused?y():pt()},ke):pt()},$=()=>{let N;for(;N=C.nextChunk(B);)B=N,or(N);let le=C.nextChunk(D);if(le){if(D&&le.discontinuity){k("Detected discontinuity; restarting playback"),this.paused?y():(T(),this._initPlayerWith(e));return}_e(le)}else y()},j=(N,le)=>{if(!d()||!this.sourceBuffer)return;let ye,ke,pt,ur=ht=>{window.setTimeout(()=>{d()&&j(N,le)},ht)};if(this.sourceBuffer.updating)k("Source buffer is updating; delaying appendBuffer"),ur(100);else{let ht=Z(),Bt=I.currentTime;!this.paused&&I.buffered.length>1&&U===Bt&&ht-z>500&&(k("Stall suspected; trying to fix"),this._fixupStall()),U!==Bt&&(U=Bt,z=ht);let lr=this._getBufferSizeSec();if(lr>30)k(`Buffered ${lr} seconds; delaying appendBuffer`),ur(2e3);else try{this.sourceBuffer.appendBuffer(N),this.videoPlayStarted?(this.bufferStates.push({ts:ht,buf:lr}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),le&&le()}catch(Qr){if(Qr.name==="QuotaExceededError")k("QuotaExceededError; delaying appendBuffer"),pt=this.sourceBuffer.buffered.length,pt!==0&&(ye=this.sourceBuffer.buffered.start(0),ke=Bt,ke-ye>4&&this.sourceBuffer.remove(ye,ke-3)),ur(1e3);else throw Qr}}},O=()=>{R&&q&&(k([`Appending chunk, sz=${R.byteLength}:`,JSON.stringify(D)]),j(R,function(){R=null,$()}))},ae=N=>e.fragUrlTemplate.replace("%%id%%",N.chunkIdx),_e=N=>{d()&&p(ae(N),(le,ye)=>{if(d()){if(ye/=1e3,R=le,D=N,n=N.startTS,ye){let ke=Math.min(10,N.dur/ye);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ke:ke}O()}},()=>this._handleNetworkError())},or=N=>{d()&&($i(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ae(N),!1)))},Wr=N=>{d()&&(e.cachedHeader=N,j(N,()=>{q=!0,O()}))};s=!0,C.seek(N=>{if(d()){if(w=Z(),!N){y();return}B=N,!Pw(E)||N.startTS>E?_e(N):(D=N,$())}},E),e.cachedHeader?Wr(e.cachedHeader):h(e.headerUrl,Wr,()=>this._handleNetworkError())},stop:T,getTimestampSec:()=>n},c}_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,$i(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=d=>{if(!this.autoQuality)return;let h,p,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),f=d/this.bitrate,p>10&&f>.8||p>15&&f>.5||p>20&&f>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}h=this._selectQuality(d),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(h,p)=>{let f=Z();if(this.chunkRateEstimator.addInterval(h,f,p)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:f-h,speed:g}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&xu(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,h)=>{let p=s.updateChunk(d,h);return p&&l(),p},notifySwitch:d=>{let h=Z();d<o&&(n=h),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Or(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout($s).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;be(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n!=null&&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))},ww))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as Lw,filter as $b,fromEvent as Mw,interval as Cw,isHigher as Dw,isInvariantQuality as Bw,isLower as Ow,merge as Vw,Subject as Lb,Subscription as _w}from"@vkontakte/videoplayer-shared";var wu=class{constructor(){this.onDroopedVideoFramesLimit$=new Lb;this.subscription=new _w;this.playing=!1;this.tracks=[];this.forceChecker$=new Lb;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!Bw(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;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&&Dw(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(Mw(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=Cw(this.droppedFramesChecker.checkTime).pipe($b(()=>this.playing),$b(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(Lw(this.droppedFramesChecker.checkTime)),r=Vw(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){var r,i;let t=(i=(r=Object.entries(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>Ow(s,n)?-1:1))==null?void 0:r[0])==null?void 0:i[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Ls=wu;import{map as Nw,Observable as Fw}from"@vkontakte/videoplayer-shared";import{fromEvent as Uw}from"@vkontakte/videoplayer-shared";var Mi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var qw=(a,e)=>new Fw(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Mi()))},{...r,...e});i.observe(a);let s=Uw(document,"visibilitychange").pipe(Nw(n=>!document.hidden||Mi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Oe=qw;var Jw=["paused","playing","ready"],Xw=["paused","playing","ready"],Ci=class{constructor(e){this.subscription=new Yw;this.videoState=new L("stopped");this.representations$=new Ru([]);this.textTracksManager=new De;this.droppedFramesManager=new Ls;this.maxSeekBackTime$=new Ru(1/0);this.zeroTime$=new Ru(void 0);this.liveOffset=new nt;this._dashCb=e=>{var t,r,i,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Db.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(r=xt(u.name))!=null?r:Kw(u.video),d=u.bitrate/1e3,h={...u.video};if(!c)continue;let p={id:l,quality:c,bitrate:d,size:h};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),ku(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),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(Xw.includes(e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&Jw.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(re(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==null?void 0: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(re(this.params.source.url,u))}return;default:return Mb(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:Db.WTF,message:"DashLiveProvider internal logic error",thrown:i})};Ob(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=pe(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(X(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=me(this.video);this.subscription.add(this.representations$.pipe(Ms(i=>i.map(({track:s})=>s)),Bb(i=>!!i.length),Qw()).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(()=>{var i;((i=this.videoState.getTransition())==null?void 0:i.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(Gw(),Ms(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(Hw({zeroTime:this.zeroTime$.pipe(Bb(ku)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(Je(this.video,this.params.desiredState.isLooped,t)).add(fe(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Ce(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(Oe(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&zw(i);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:i})})).add(this.videoState.stateChangeEnded$.subscribe(i=>{var s;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":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return Mb(i.to)}},t)).add(Ob(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Ww(["init"])).pipe(jw(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),he(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(){var l,c,d,h,p,f;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(h=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?h:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&ku(t)?t:Pt(e.map(({track:b})=>b),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput: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==null?void 0:i.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let b=(f=e.find(({track:g})=>g.id===s))==null?void 0:f.representation;Cb(b,"Representations missing"),this.dash.startPlay(b,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:i})=>i.id===e.id))==null?void 0:r.representation;Cb(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(re(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var Vb=Ci;var Ze=(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 RR,assertNonNullable as $R,debounce as LR,ErrorCategory as nl,filter as pS,filterChanged as ol,fromEvent as MR,isNonNullable as CR,map as hS,merge as rn,observableFrom as DR,observeElementSize as BR,once as fS,Subscription as OR,ValueSubject as VR}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 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}},Vr=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)}},Di=class{constructor(){Object.defineProperty(this,"signal",{value:new Vr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){typeof document!="undefined"?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=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(i){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Di.prototype[Symbol.toStringTag]="AbortController",Vr.prototype[Symbol.toStringTag]="AbortSignal");function Ds(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 $u(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!Ds({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,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let h=new t(l,c);return d&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),h},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(p){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let h=new Promise((p,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([h,n(u,l)])}return n(u,l)},Request:s}}var Bi=Ds({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),_b=Bi?$u({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ut=Bi?_b.fetch:window.fetch,FB=Bi?_b.Request:window.Request,xe=Bi?Di:window.AbortController,UB=Bi?Vr:window.AbortSignal;var Hs=Ue(Br(),1);var lt=()=>window.ManagedMediaSource||window.MediaSource,Bs=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Nb=()=>{var a,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Fb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Gs,clientChecker as js}from"@vkontakte/videoplayer-shared";var Ve=document.createElement("video"),tk='video/mp4; codecs="avc1.42000a,mp4a.40.2"',rk='video/mp4; codecs="hev1.1.6.L93.B0"',Jb='video/webm; codecs="vp09.00.10.08"',Xb='video/webm; codecs="av01.0.00M.08"',ik='audio/mp4; codecs="mp4a.40.2"',ak='audio/webm; codecs="opus"',Ub,qb,zt={mms:Bs(),mse:Nb(),hls:!!((Ub=Ve.canPlayType)!=null&&Ub.call(Ve,"application/x-mpegurl")||(qb=Ve.canPlayType)!=null&&qb.call(Ve,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Hb,jb,ge={mp4:!!((Hb=Ve.canPlayType)!=null&&Hb.call(Ve,"video/mp4")),webm:!!((jb=Ve.canPlayType)!=null&&jb.call(Ve,"video/webm")),cmaf:!0},Vs,Gb,_s,Wb,Ns,Qb,Fs,Yb,Us,zb,qs,Kb,Se={h264:!!((Gb=(Vs=lt())==null?void 0:Vs.isTypeSupported)!=null&&Gb.call(Vs,tk)),h265:!!((Wb=(_s=lt())==null?void 0:_s.isTypeSupported)!=null&&Wb.call(_s,rk)),vp9:!!((Qb=(Ns=lt())==null?void 0:Ns.isTypeSupported)!=null&&Qb.call(Ns,Jb)),av1:!!((Yb=(Fs=lt())==null?void 0:Fs.isTypeSupported)!=null&&Yb.call(Fs,Xb)),aac:!!((zb=(Us=lt())==null?void 0:Us.isTypeSupported)!=null&&zb.call(Us,ik)),opus:!!((Kb=(qs=lt())==null?void 0:qs.isTypeSupported)!=null&&Kb.call(qs,ak))},_r=(Se.h264||Se.h265)&&Se.aac,Kt,sk=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:Xb}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Jb}})]);Kt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{sk()}catch(a){console.error(a)}var Nr=zt.hls&&ge.mp4,Zb=()=>Object.keys(Se).filter(a=>Se[a]),eg=(a,e=!1,t=!1)=>{let r=zt.mse||zt.mms&&t;return a.filter(i=>{switch(i){case"DASH_SEP":return r&&ge.mp4&&_r;case"DASH_WEBM":return r&&ge.webm&&Se.vp9&&Se.opus;case"DASH_WEBM_AV1":return r&&ge.webm&&Se.av1&&Se.opus;case"DASH_STREAMS":return r&&(ge.mp4&&_r||ge.webm&&(Se.vp9||Se.av1)&&(Se.opus||Se.aac));case"DASH_LIVE":return zt.mse&&ge.mp4&&_r;case"DASH_LIVE_CMAF":return r&&ge.mp4&&_r&&ge.cmaf;case"DASH_ONDEMAND":return r&&ge.mp4&&_r;case"HLS":case"HLS_ONDEMAND":return Nr||e&&zt.mse&&ge.mp4&&_r;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Nr;case"MPEG":return ge.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return zt.webrtc&&zt.ws&&Se.h264&&(ge.mp4||ge.webm);default:return Gs(i)}})},Os=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 Kt?Kt[t].smooth?[t,e]:Kt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Kt?Kt[t].powerEfficient?[t,e]:Kt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Gs(a)}return[e,t]},tg=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...Os(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(js.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",...Os(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Os(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Os(a),...i,"HLS","HLS_ONDEMAND"];default:Gs(e)}return Nr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},rg=({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=js.isMac&&js.isSafari;if(js.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:Gs(a)}else Nr&&!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"]},Lu=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],ig=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,Hs.default)(t.value.split("."),0)}for(let t of a){let r=(0,Hs.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,Hs.default)(e.value.split("."),0)};import{ErrorCategory as Oi}from"@vkontakte/videoplayer-shared";var ag=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=a.trimStart().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 At=(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 rl,assertNonNullable as ir,clientChecker as SR,combine as Js,ErrorCategory as $t,filter as il,filterChanged as nS,flattenObject as fa,fromEvent as ar,getTraceSubscriptionMethod as vR,interval as al,isNonNullable as oS,map as sl,merge as sr,now as yR,Subject as uS,Subscription as lS,tap as TR,throttle as IR,ValueSubject as ie}from"@vkontakte/videoplayer-shared";var qr=Ue(Br(),1);var nk=(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)},ok=a=>window.clearTimeout(a),sg=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),ng=!sg(window.requestIdleCallback)||!sg(window.cancelIdleCallback),Mu=ng?nk:window.requestIdleCallback,tO=ng?ok:window.cancelIdleCallback;var Xg=Ue(xs(),1);import{assertNever as uk,ErrorCategory as og,clientChecker as Cu,Subject as ug}from"@vkontakte/videoplayer-shared";var lk=18,lg=!1;try{lg=Cu.isSafari&&!!Cu.macVersion&&Cu.macVersion<=lk}catch(a){console.error(a)}var Du=class{constructor(e){this.bufferFull$=new ug;this.error$=new ug;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:og.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(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;lg&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:i}of this.queue)i(!1);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(){var i;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((i=e.signal)!=null&&i.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:og.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:uk(t)}}},cg=Du;var Bu=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 er,assertNonNullable as ee,ErrorCategory as kt,fromEvent as Ju,getExponentialDelay as Xu,isNonNullable as na,isNullable as Ae,now as Ws,once as uR,Subject as lR,Subscription as cR,ValueSubject as oa}from"@vkontakte/videoplayer-shared";var F=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),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}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 Fr=class extends F{};var Vi=class extends F{};var _i=class extends F{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 Ni=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var W=class extends F{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Fi=class extends W{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 Ui=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var qi=class extends F{constructor(e,t){super(e,t),this.data=this.content}};var Jt=class extends W{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 Hi=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ji=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Gi=class extends W{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 Wi=class extends W{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Qi=class extends W{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Yi=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var zi=class extends W{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 Ki=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ji=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Xi=class extends W{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Zi=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ea=class extends W{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 ta=class extends W{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 ra=class extends W{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 dk={ftyp:_i,moov:Ni,mvhd:Fi,moof:Ui,mdat:qi,sidx:Jt,trak:Hi,mdia:Yi,mfhd:Xi,tkhd:zi,traf:Zi,tfhd:ea,tfdt:ta,trun:ra,minf:Ki,sv3d:ji,st3d:Gi,prhd:Wi,proj:Ji,equi:Qi,uuid:Vi,unknown:Fr},wt=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(i){break}return t}createBox(e,t){let r=dk[e];return r?new r(t,new a):new Fr(t,new a)}};var Xt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),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 hk=new TextDecoder("ascii"),fk=a=>hk.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",mk=a=>{let e=new Jt(a,new wt),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})},bk=(a,e)=>{let r=new wt().parse(a),i=new Xt(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,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},gk=a=>{var i;let t=new wt().parse(a);return(i=new Xt(t).find("sidx"))==null?void 0:i.timescale},Sk=(a,e)=>{let r=new wt().parse(a),s=new Xt(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,h)=>d+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},vk=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 wt().parse(a),i=new Xt(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},dg={validateData:fk,parseInit:vk,getIndexRange:()=>{},parseSegments:mk,parseFeedableSegmentChunk:bk,getChunkEndTime:Sk,getTimescaleFromIndex:gk};import{assertNonNullable as Vu,isNonNullable as mg,isNullable as Tk}from"@vkontakte/videoplayer-shared";import{assertNever as yk}from"@vkontakte/videoplayer-shared";var pg={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"}},hg=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=ia(a,t),i=r in pg,s=i?pg[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,c=ia(u),d=l*2**((o-1)*8)+c,h=t+o,p;return h+d>a.byteLength?p=new DataView(a.buffer,a.byteOffset+h):p=new DataView(a.buffer,a.byteOffset+h,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:h,tagSize:h+d,value:p,valueSize:d}},ia=(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},We=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return ia(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:yk(e)}},Zt=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=hg(r);if(!e(i))return;i.type==="master"&&Zt(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},fg=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=hg(a);return Zt(i.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 bg=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Ik=[231,22612,22743,167,171,163,160,175],Ek=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return Zt(a,({tag:h,type:p,value:f,valueSize:b})=>{if(h===21419){let g=We(f,p);l=ia(g)}else h!==21420&&(l=void 0);return h===408125543?(e=f.byteOffset,t=f.byteOffset+b):h===357149030?s=!0:h===290298740?n=!0:h===2807729?r=We(f,p):h===17545?i=We(f,p):h===21420&&l===475249515?u=We(f,p):h===374648427?Zt(f,({tag:g,type:v,value:T})=>g===30321?(c=We(T,v)===1,!1):!0):s&&n&&bg.includes(h)&&(o=!0),!o}),Vu(e,"Failed to parse webm Segment start"),Vu(t,"Failed to parse webm Segment end"),Vu(i,"Failed to parse webm Segment duration"),r=r!=null?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:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},xk=a=>{if(Tk(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Pk=(a,e)=>{let t=!1,r=!1,i=o=>mg(o.time)&&mg(o.position),s=[],n;return Zt(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=We(l,u));break;case 183:break;case 241:n&&(n.position=We(l,u));break;default:t&&bg.includes(o)&&(r=!0)}return!(t&&r)}),n&&i(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}}})},Ak=a=>{let e=0,t=!1;try{Zt(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):Ik.includes(r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=[163,160,175].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},gg={validateData:fg,parseInit:Ek,getIndexRange:xk,parseSegments:Pk,parseFeedableSegmentChunk:Ak};var aa=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return gg;case"mp4":return dg}}throw new ReferenceError(`Unsupported mime type ${a}`)},Sg=a=>"getChunkEndTime"in a;var ju=Ue(Fg(),1),Wg=Ue(Br(),1);var Hu=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["6E","7A","F4"].includes(o)}}return!1};import{isNonNullable as Hg,isNullable as jg}from"@vkontakte/videoplayer-shared";var Ug=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var qg=a=>{var e;try{let t=nR(),r=a.match(t),{groups:i}=r!=null?r:{};if(i){let s={};if(i.extensions){let u=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=i.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function nR(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
|
|
59
59
|
(?<language>${`(?:[a-z]{2,3}(?:-${a})?|[a-z]{4}|[a-z]{5,8})`})
|
|
60
60
|
(-(?<script>[a-z]{4}))?
|
|
61
61
|
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
62
62
|
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
63
63
|
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
64
64
|
(?:-(?<privateuse>(?:${e})))?
|
|
65
|
-
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var Yg=a=>{if(!a.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),r=(i==null?void 0:i[1])==="-"?-1:1,s={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},dt=(a,e)=>{let t=a;t=(0,Qu.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of Object.entries(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Qu.default)(t,n,(o,u)=>Wg(s)?o:Wg(u)?s:s.padStart(parseInt(u,10),"0"))}return t},zg=(a,e)=>{var E,k,C,N,$,B,O,R,w,U,z,v,L,H,G,K,ue,tt,ft,A,le,Ie,ke,mt,oi,bt,Dt,ui,zi,Pl,Al,wl,kl,Rl,$l,Ll,Ml,Cl,Dl,Bl,Ol,Vl,_l,Nl,Fl,Ul,ql,Hl,jl,Gl,Wl,Yl,Ql,zl,Kl,Jl,Xl,Zl,ec,tc;let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=s.getElementsByTagName("Period")[0],o=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(te=>{var Ra,gt;return(gt=(Ra=te.textContent)==null?void 0:Ra.trim())!=null?gt:""}),u=(E=(0,Qg.default)(o,0))!=null?E:"",l=n.children,c=s.getAttribute("type")==="dynamic",d=s.getAttribute("availabilityStartTime"),h=d?new Date(d).getTime():void 0,p,f=s.getAttribute("mediaPresentationDuration"),b=n.getAttribute("duration"),g=s.getElementsByTagName("vk:Attrs")[0],y=g==null?void 0:g.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)p=Yg(f);else if(b){let te=Yg(b);Gg(te)&&(p=te)}else y&&(p=parseInt(y,10));let I=0,S=(C=(k=s.getAttribute("profiles"))==null?void 0:k.split(","))!=null?C:[];for(let te of l){let Ra=(N=te.getAttribute("id"))!=null?N:"id"+(I++).toString(10),gt=($=te.getAttribute("mimeType"))!=null?$:"",Tn=(B=te.getAttribute("codecs"))!=null?B:"",In=(O=te.getAttribute("contentType"))!=null?O:gt==null?void 0:gt.split("/")[0],ov=(w=(R=te.getAttribute("profiles"))==null?void 0:R.split(","))!=null?w:[],ic=(z=jg((U=te.getAttribute("lang"))!=null?U:""))!=null?z:{},uv=(H=(L=(v=te.querySelector("Label"))==null?void 0:v.textContent)==null?void 0:L.trim())!=null?H:void 0,lv=te.querySelectorAll("Representation"),cv=te.querySelector("SegmentTemplate"),dv=(K=(G=te.querySelector("Role"))==null?void 0:G.getAttribute("value"))!=null?K:void 0,Ki=In,J={id:Ra,language:ic.language,isDefault:dv==="main",label:uv,codecs:Tn,hdr:Ki==="video"&&Yu(Tn),mime:gt,representations:[]};for(let j of lv){let pv=(ue=j.getAttribute("lang"))!=null?ue:void 0,hv=(tt=j.getAttribute("label"))!=null?tt:void 0,fv=(le=(A=(ft=j.querySelector("BaseURL"))==null?void 0:ft.textContent)==null?void 0:A.trim())!=null?le:"",$a=new URL(fv||u,e).toString(),li=(Ie=j.getAttribute("mimeType"))!=null?Ie:gt,La=(mt=(ke=j.getAttribute("codecs"))!=null?ke:Tn)!=null?mt:"",Ma;if(In==="text"){let St=j.getAttribute("id")||"",Ca=((oi=ic.privateuse)==null?void 0:oi.includes("x-auto"))||St.includes("_auto"),Bt=j.querySelector("SegmentTemplate");if(Bt){let Ji={representationId:(bt=j.getAttribute("id"))!=null?bt:void 0,bandwidth:(Dt=j.getAttribute("bandwidth"))!=null?Dt:void 0},Da=parseInt((ui=j.getAttribute("bandwidth"))!=null?ui:"",10)/1e3,Ba=(Pl=parseInt((zi=Bt.getAttribute("startNumber"))!=null?zi:"",10))!=null?Pl:1,ci=parseInt((Al=Bt.getAttribute("timescale"))!=null?Al:"",10),En=(wl=Bt.querySelectorAll("SegmentTimeline S"))!=null?wl:[],di=Bt.getAttribute("media");if(!di)continue;let Oa=[],Va=0,_a="",pi=0,Xi=Ba,ae=0;for(let _e of En){let Ot=parseInt((kl=_e.getAttribute("d"))!=null?kl:"",10),Re=parseInt((Rl=_e.getAttribute("r"))!=null?Rl:"",10)||0,vt=parseInt(($l=_e.getAttribute("t"))!=null?$l:"",10);ae=Number.isFinite(vt)?vt:ae;let Vt=Ot/ci*1e3,yt=ae/ci*1e3;for(let Qe=0;Qe<Re+1;Qe++){let Tt=dt(di,{...Ji,segmentNumber:Xi.toString(10),segmentTime:(ae+Qe*Ot).toString(10)}),hi=(yt!=null?yt:0)+Qe*Vt,er=hi+Vt;Xi++,Oa.push({time:{from:hi,to:er},url:Tt})}ae+=(Re+1)*Ot,Va+=(Re+1)*Vt}pi=ae/ci*1e3,_a=dt(di,{...Ji,segmentNumber:Xi.toString(10),segmentTime:ae.toString(10)});let Zi={time:{from:pi,to:1/0},url:_a},it={type:"template",baseUrl:$a,segmentTemplateUrl:di,initUrl:"",totalSegmentsDurationMs:Va,segments:Oa,nextSegmentBeyondManifest:Zi,timescale:ci};Ma={id:St,kind:"text",segmentReference:it,profiles:[],duration:p,bitrate:Da,mime:"",codecs:"",width:0,height:0,isAuto:Ca}}else Ma={id:St,isAuto:Ca,kind:"text",url:$a}}else{let St=(Ml=(Ll=j.getAttribute("contentType"))!=null?Ll:li==null?void 0:li.split("/")[0])!=null?Ml:In,Ca=(Dl=(Cl=te.getAttribute("profiles"))==null?void 0:Cl.split(","))!=null?Dl:[],Bt=parseInt((Bl=j.getAttribute("width"))!=null?Bl:"",10),Ji=parseInt((Ol=j.getAttribute("height"))!=null?Ol:"",10),Da=parseInt((Vl=j.getAttribute("bandwidth"))!=null?Vl:"",10)/1e3,Ba=(_l=j.getAttribute("frameRate"))!=null?_l:"",ci=(Nl=j.getAttribute("quality"))!=null?Nl:void 0,En=Ba?Hg(Ba):void 0,di=(Fl=j.getAttribute("id"))!=null?Fl:"id"+(I++).toString(10),Oa=St==="video"?`${Ji}p`:St==="audio"?`${Da}Kbps`:La,Va=`${di}@${Oa}`,_a=[...S,...ov,...Ca],pi,Xi=j.querySelector("SegmentBase"),ae=(Ul=j.querySelector("SegmentTemplate"))!=null?Ul:cv;if(Xi){let it=(Hl=(ql=j.querySelector("SegmentBase Initialization"))==null?void 0:ql.getAttribute("range"))!=null?Hl:"",[_e,Ot]=it.split("-").map(Tt=>parseInt(Tt,10)),Re={from:_e,to:Ot},vt=(jl=j.querySelector("SegmentBase"))==null?void 0:jl.getAttribute("indexRange"),[Vt,yt]=vt?vt.split("-").map(Tt=>parseInt(Tt,10)):[],Qe=vt?{from:Vt,to:yt}:void 0;pi={type:"byteRange",url:$a,initRange:Re,indexRange:Qe}}else if(ae){let it={representationId:(Gl=j.getAttribute("id"))!=null?Gl:void 0,bandwidth:(Wl=j.getAttribute("bandwidth"))!=null?Wl:void 0},_e=parseInt((Yl=ae.getAttribute("timescale"))!=null?Yl:"",10),Ot=(Ql=ae.getAttribute("initialization"))!=null?Ql:"",Re=ae.getAttribute("media"),vt=(Kl=parseInt((zl=ae.getAttribute("startNumber"))!=null?zl:"",10))!=null?Kl:1,Vt=dt(Ot,it);if(!Re)throw new ReferenceError("No media attribute in SegmentTemplate");let yt=(Jl=ae.querySelectorAll("SegmentTimeline S"))!=null?Jl:[],Qe=[],Tt=0,hi="",er=0;if(yt.length){let Na=vt,Ne=0;for(let fi of yt){let ze=parseInt((Xl=fi.getAttribute("d"))!=null?Xl:"",10),_t=parseInt((Zl=fi.getAttribute("r"))!=null?Zl:"",10)||0,Fa=parseInt((ec=fi.getAttribute("t"))!=null?ec:"",10);Ne=Number.isFinite(Fa)?Fa:Ne;let xn=ze/_e*1e3,Pn=Ne/_e*1e3;for(let Ua=0;Ua<_t+1;Ua++){let bv=dt(Re,{...it,segmentNumber:Na.toString(10),segmentTime:(Ne+Ua*ze).toString(10)}),rc=(Pn!=null?Pn:0)+Ua*xn,gv=rc+xn;Na++,Qe.push({time:{from:rc,to:gv},url:bv})}Ne+=(_t+1)*ze,Tt+=(_t+1)*xn}er=Ne/_e*1e3,hi=dt(Re,{...it,segmentNumber:Na.toString(10),segmentTime:Ne.toString(10)})}else if(Gg(p)){let Ne=parseInt((tc=ae.getAttribute("duration"))!=null?tc:"",10)/_e*1e3,fi=Math.ceil(p/Ne),ze=0;for(let _t=1;_t<fi;_t++){let Fa=dt(Re,{...it,segmentNumber:_t.toString(10),segmentTime:ze.toString(10)});Qe.push({time:{from:ze,to:ze+Ne},url:Fa}),ze+=Ne}er=ze,hi=dt(Re,{...it,segmentNumber:fi.toString(10),segmentTime:ze.toString(10)})}let mv={time:{from:er,to:1/0},url:hi};pi={type:"template",baseUrl:$a,segmentTemplateUrl:Re,initUrl:Vt,totalSegmentsDurationMs:Tt,segments:Qe,nextSegmentBeyondManifest:mv,timescale:_e}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!St||!li)continue;let Zi={video:"video",audio:"audio",text:"text"}[St];if(!Zi)continue;Ki||(Ki=Zi),Ma={id:Va,kind:Zi,segmentReference:pi,profiles:_a,duration:p,bitrate:Da,mime:li,codecs:La,width:Bt,height:Ji,fps:En,quality:ci}}J.language||(J.language=pv),J.label||(J.label=hv),J.mime||(J.mime=li),J.codecs||(J.codecs=La),J.hdr||(J.hdr=Ki==="video"&&Yu(La)),J.representations.push(Ma)}Ki&&r[Ki].push(J)}return{dynamic:c,liveAvailabilityStartTime:h,duration:p,streams:r,baseUrls:o}};var sa=Fe(Di(),1);import{videoSizeToQuality as oR}from"@vkontakte/videoplayer-shared";var Kg=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s})=>{var o;let n=(o=s?wt(s):void 0)!=null?o:oR({width:e,height:t});return n&&{id:a,quality:n,bitrate:i,size:{width:e,height:t},fps:r}},Jg=({id:a,bitrate:e})=>({id:a,bitrate:e}),Ys=(a,e,t)=>{var r;let i=e.indexOf(a);return(r=(0,sa.default)(t,Math.round(t.length*i/e.length)))!=null?r:(0,sa.default)(t,-1)},Xg=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Zg=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Ju=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,sa.default)(i.split("."),0),isDefault:r}),Xu=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,sa.default)(r.split("."),0)}),Qs=a=>"url"in a,Ae=a=>a.type==="template",na=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var la=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentSegmentLength$=new ua(0);this.onLastSegment$=new ua(!1);this.fullyBuffered$=new ua(!1);this.playingRepresentation$=new ua(void 0);this.playingRepresentationInit$=new ua(void 0);this.error$=new lR;this.gaps=[];this.subscription=new cR;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Ge;this.switchAbortController=new Ge;this.destroyAbortController=new Ge;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Zt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);ve(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new hg(this.sourceBuffer),this.subscription.add(Zu(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:ei.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:ei.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Zu(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:ei.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,Nu(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let l=Ze(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,n*2,l<c)}else this.pruneBufferOld(o,n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);ve(i,"No init buffer for starting representation"),ve(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchToOld=Zt(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);ve(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ye(s)||ye(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),ve(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(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();oa(n)&&(this.isLive||(this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Zt(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=e==null?void 0:e.flatMap(c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(f=>f.id===c);d&&this.representations.set(c,d);let h=this.representations.get(c);if(!h||!Ae(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);ve(r);let s=this.segments.get(i);ve(s,"No segments for starting representation");let n=this.initData.get(i);if(ve(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var c;this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.resetAccumulateBufferAfterStall(),this.startAccumulateBuffer(),this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Ge,Zt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);ve(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(ye(o)||ye(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),ve(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();oa(u)&&!this.isLive&&(this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0,this.maintain(u)}}.bind(this))(e,t))}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Ge,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,c;if(ye(e)||ye(this.downloadingRepresentationId)||ye(this.playingRepresentationId)||ye(this.sourceBuffer)||oa(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(ve(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((l=r==null?void 0:r.time.to)!=null?l:0)-((c=r==null?void 0:r.time.from)!=null?c:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let h=Ze(this.sourceBuffer.buffered,e),p=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=r.time.to-e+100&&(s=p)}if(isFinite(this.bufferLimit)&&Nu(this.sourceBuffer.buffered)>=this.bufferLimit){let d=Ze(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,s),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))d="high";else{let h=(0,ji.default)(o,0);h&&h.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!o.length&&Ze(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,ji.default)(i,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(r===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r}),i=s.time.to;oa(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.streams[this.kind].flatMap(r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,s,n;let t=(i=e==null?void 0:e.streams[this.kind].flatMap(o=>o.representations))!=null?i:[];for(let o of t){if(!o||!Ae(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>({...h,status:"none",size:void 0})),l=(r=this.segments.get(o.id))!=null?r:[],c=(n=(s=(0,ji.default)(l,-1))==null?void 0:s.time.to)!=null?n:0,d=u==null?void 0:u.findIndex(h=>Math.floor(c)>=Math.floor(h.time.from)&&Math.floor(c)<=Math.floor(h.time.to));if(d===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(d+1);this.segments.set(o.id,[...l,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;ve(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}startAccumulateBuffer(){this.bufferAccumulation.enabled=!0}resetAccumulateBufferAfterStall(){this.bufferAccumulation={enabled:!1,targetBufferSizeMs:this.tuning.accumulationBufferStallSizeMs,accumulatedBufferSizeMs:0,accumulated:[]}}updateLowLatencyLiveIfNeeded(e){var t;for(let i of this.representations.values()){let r=i.segmentReference;if(!Ae(r))return;let s=(t=this.segments.get(i.id))!=null?t:[],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),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=dt(r.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:d,time:{from:h,to:p}},f)=>{let b=h<=i&&p>=i,g=h>i||b||f===0&&i===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),I=this.preloadOnly&&h<=i+y||p<=i+y;return(d==="none"||d==="partially_ejected"&&g&&I&&this.sourceBuffer&&!(Ni(this.sourceBuffer.buffered,h)&&Ni(this.sourceBuffer.buffered,p)))&&g&&I});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+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=r;d<s.length&&(n<=l||o<=c);d++){let h=s[d];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}async loadSegments(e,t,i="auto"){Ae(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Zt(o,async function*(){let c=el(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=zs(),!c)return;let d=new DataView(c);if(!isFinite(r.segment.time.to)){let h=t.segmentReference.timescale,p=qi(t.mime);r.segment.time.to=p.getSegmentEndTime(d,h)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),na(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())Ae(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Zt(n,async function*(){let u=el(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Zu(window,"online").pipe(uR()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=zs(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),na(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Ae(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,ji.default)(e,0).byte.from,to:(0,ji.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=zs(),this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:ei.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ae(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=zs();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:ei.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,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){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=qi(n.mime).parseFeedableSegmentChunk(l,this.isLive);c!=null&&c.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){let o={dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let u=o.segmentReference.type,l=e.byteLength;for(let c of this.activeSegments){let{segment:d}=c,h=u==="byteRange",p=h?d.byte.to-d.byte.from+1:l;if(c.representationId!==t||!(!h||d.byte.from>=i&&d.byte.to<i+e.byteLength))continue;if(s.aborted){n();continue}let b=h?d.byte.from-i:0,g=h?d.byte.to-i:e.byteLength,y=b<r,I=g<=r;if(d.status==="downloading"&&y&&I){d.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+b,p),T=this.getCurrentPosition();oa(T)&&(this.bufferAccumulation.accumulatedBufferSizeMs=d.time.to-T,this.bufferAccumulation.accumulated.push({segmentView:S,segmentProgress:c}),this.activeSegments.delete(c));let E=({segmentView:k,segmentProgress:C})=>this.sourceBufferTaskQueue.append(k,s).then(N=>N&&!s.aborted?this.onSegmentFullyAppended(C,t):n());this.bufferAccumulation.enabled&&this.bufferAccumulation.targetBufferSizeMs<this.bufferAccumulation.accumulatedBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(E),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||ye(T))&&(E({segmentView:S,segmentProgress:c}),this.resetAccumulateBufferAfterStall())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&y&&!I&&(c.loadedBytes=Math.min(p,r-b),c.loadedBytes>c.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+b+c.feedingBytes,c.loadedBytes-c.feedingBytes),T=c.loadedBytes===p?S:qi(o.mime).parseFeedableSegmentChunk(S);T!=null&&T.byteLength&&(d.status="partially_fed",c.feedingBytes+=T.byteLength,this.sourceBufferTaskQueue.append(T,s).then(E=>{if(s.aborted)n();else if(E)c.fedBytes+=T.byteLength,c.fedBytes===p&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<p)return;n()}}))}}}async onSomeByteRangesDataLoadedNew({dataView:e,representationId:t,globalFrom:i,loaded:r,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){n();continue}let c=l.byte.from-i,d=l.byte.to-i,h=d-c+1,p=c<r,f=d<=r;if(p){if(l.status==="downloading"&&f){l.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+c,h);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(h,r-c),u.loadedBytes>u.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),g=u.loadedBytes===h?b:qi(o.mime).parseFeedableSegmentChunk(b);g!=null&&g.byteLength&&(l.status="partially_fed",u.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(u.fedBytes+=g.byteLength,u.fedBytes===h&&this.onSegmentFullyAppended(u,t)):n())}}}}onSegmentFullyAppended(e,t){var i;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Qs(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let s of(i=this.segments.get(r.id))!=null?i:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");ve(this.sourceBuffer),this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Ou(()=>(0,eS.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Zt(this.destroyAbortController.signal,async function*(){let o=el(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,qi(e.mime),r)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let h=c;this.isLive&&Ae(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:ei.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,i):this.pruneBufferOld(e,t,i)}async pruneBufferNew(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||ye(e)||this.sourceBuffer.updating)return!1;let r=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:h}=u[c],p=l[l.length-1];p.to>=d?p.to=Math.max(p.to,h):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return r;r.push({...u.time}),r=n(r);let l=Qs(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let h of this.segments.values())for(let p of h)["none","partially_ejected"].includes(p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let h={time:{from:l,to:c},url:"",status:"none"};o(h)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}async pruneBufferOld(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||ye(e)||this.sourceBuffer.updating)return!1;let r=0,s=1/0,n=-1/0,o=!1,u=l=>{var d;s=Math.min(s,l.time.from),n=Math.max(n,l.time.to);let c=Qs(l)?(d=l.size)!=null?d:0:l.byte.to-l.byte.from;r+=c};for(let l of this.segments.values())for(let c of l){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;c.status==="fed"&&u(c)}if(o=isFinite(s)&&isFinite(n),!o){r=0,s=1/0,n=-1/0;for(let l of this.segments.values())for(let c of l){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;c.status==="fed"&&u(c)}}if(o=isFinite(s)&&isFinite(n),!o)for(let l=0;l<this.sourceBuffer.buffered.length;l++){let c=this.sourceBuffer.buffered.start(l)*1e3,d=this.sourceBuffer.buffered.end(l)*1e3;for(let h of this.segments.values())for(let p of h)if(p.status==="none"&&Math.round(p.time.from)<=Math.round(c)&&Math.round(p.time.to)>=Math.round(d)){s=c,n=d;break}}if(o=isFinite(s)&&isFinite(n),!o&&i){r=0,s=1/0,n=-1/0;let l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let d of c)d.time.from>e+l&&d.status==="fed"&&u(d)}return o=isFinite(s)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(s,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!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||!this.sourceBuffer.buffered.length||ye(e)?0:Ze(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(this.sourceBuffer)for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(!this.gapDetectionIdleCallback){ve(this.sourceBuffer);for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Ou(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:ei.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(ye(this.sourceBuffer)||ye(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}};var ca=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var tS=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:i,reused:r}};import{abortable as da,assertNever as iS,fromEvent as rS,merge as dR,now as pa,Subscription as pR,ValueSubject as tl,flattenObject as Gi}from"@vkontakte/videoplayer-shared";var Ks=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1}){this.lastConnectionType$=new tl(void 0);this.lastConnectionReused$=new tl(void 0);this.lastRequestFirstBytes$=new tl(void 0);this.abortAllController=new Ge;this.subscription=new pR;this.fetchManifest=da(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=ca(i));let r=yield lt(i,{signal:this.abortAllController.signal}).catch(ha);return r?(t.log("success",Gi({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Gi({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=da(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var O,R;let l=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let w=new URL(l,location.href);w.searchParams.append("bytes",`${i.from}-${i.to}`),l=w.toString();break}default:iS(t)}this.requestQuic&&(l=ca(l));let h=this.abortAllController.signal,p;if(n){let w=new Ge;if(p=dR(rS(this.abortAllController.signal,"abort"),rS(n,"abort")).subscribe(()=>{try{w.abort()}catch(U){ha(U)}}),this.abortAllController.signal.aborted||n.aborted)try{w.abort()}catch(U){ha(U)}h=w.signal}let f=pa();d.log("startRequest",Gi({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:f}));let b=yield lt(l,{priority:s,headers:c,signal:h}).catch(ha),g=pa();if(!b)return d.error("error",{message:"No response in request"}),d.end(),p==null||p.unsubscribe(),null;if((O=this.throughputEstimator)==null||O.addRawRtt(g-f),!b.ok||!b.body){p==null||p.unsubscribe();let w=`Fetch error ${b.status}: ${b.statusText}`;return d.error("error",{message:w}),d.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!r&&!o){p==null||p.unsubscribe();let w=pa(),U={requestStartedAt:f,requestEndedAt:w,duration:w-f};return d.log("endRequest",Gi(U)),d.end(),b.arrayBuffer()}let[y,I]=b.body.tee(),S=y.getReader();o&&((R=this.throughputEstimator)==null||R.trackStream(I,u));let T=0,E=new Uint8Array(0),k=!1,C=w=>{p==null||p.unsubscribe(),k=!0,ha(w)},N=da(h,async function*({done:w,value:U}){if(T===0&&this.lastRequestFirstBytes$.next(pa()-f),h.aborted){p==null||p.unsubscribe();return}if(!w&&U){let z=new Uint8Array(E.length+U.length);z.set(E),z.set(U,E.length),E=z,T+=U.byteLength,r==null||r(new DataView(E.buffer),T),yield S==null?void 0:S.read().then(N,C)}}.bind(this));yield S==null?void 0:S.read().then(N,C),p==null||p.unsubscribe();let $=pa(),B={failed:k,requestStartedAt:f,requestEndedAt:$,duration:$-f};return k?(d.error("endRequest",Gi(B)),d.end(),null):(d.log("endRequest",Gi(B)),d.end(),E.buffer)}.bind(this));this.fetchByteRangeRepresentation=da(this.abortAllController.signal,async function*(e,t,i){var y;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,r),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let h=new DataView(d,r-n,s-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),f=(y=e.indexRange)!=null?y:t.getIndexRange(p);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 I=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!I)return null;b=new DataView(I)}let g=t.parseSegments(b,p,f);return{init:p,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=da(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher")}onHeadersReceived(e){let{type:t,reused:i}=tS(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:iS(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},ha=a=>{if(!na(a))throw a};var ti=(a,e,t)=>t*e+(1-t)*a,il=(a,e)=>a.reduce((t,i)=>t+i,0)/e,aS=(a,e,t,i)=>{let r=0,s=t,n=il(a,e),o=e<i?e:i;for(let u=0;u<o;u++)a[s]>n?r++:r--,s=(a.length+s-1)%a.length;return Math.abs(r)===o};import{isNullable as hR,ValueSubject as sS}from"@vkontakte/videoplayer-shared";var Rt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new sS(e.initial),this.debounced$=new sS(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ne(`raw_${t}`),this.smoothedSeries$=new ne(`smoothed_${t}`),this.reportedSeries$=new ne(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(hR(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 Js=class extends Rt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ti(this.slow,e,this.params.emaAlphaSlow),this.fast=ti(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Xs=class extends Rt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=il(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ti(this.emaSmoothed,e,this.params.emaAlpha);let i=aS(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Zs=class extends Rt{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?ti(this.smoothed,t,this.params.emaAlpha):t}};var ii=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Js({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Xs({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new Zs({initial:e,label:"liveEdgeDelay",...t})}};var rl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as fR,ValueSubject as mR}from"@vkontakte/videoplayer-shared";var fa=class a{constructor(e,t){this.currentRepresentation$=new mR(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!fR(e))for(let i of this.representations)for(let r of i){let s=r.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Ae(t.segmentReference))}};var ER=["timeupdate","progress","play","seeked","stalled","waiting"],xR=["timeupdate","progress","loadeddata","playing","seeked"];var tn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new cS;this.representationSubscription=new cS;this.state$=new M("none");this.currentVideoRepresentation$=new re(void 0);this.currentVideoRepresentationInit$=new re(void 0);this.currentAudioRepresentation$=new re(void 0);this.currentVideoSegmentLength$=new re(0);this.currentAudioSegmentLength$=new re(0);this.error$=new lS;this.lastConnectionType$=new re(void 0);this.lastConnectionReused$=new re(void 0);this.lastRequestFirstBytes$=new re(void 0);this.currentLiveTextRepresentation$=new re(null);this.isLive$=new re(!1);this.liveDuration$=new re(0);this.liveAvailabilityStartTime$=new re(void 0);this.bufferLength$=new re(0);this.liveLoadBufferLength$=new re(0);this.livePositionFromPlayer$=new re(0);this.isActiveLowLatency$=new re(!1);this.timeInWaiting=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new lS;this.gapWatchdogActive=!1;this.destroyController=new Ge;this.initManifest=al(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ie(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:pt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=al(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:pt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=zg(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=og(e))!=null?n:{id:"ManifestParsing",category:pt.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,c)=>{var d,h,p,f;return!!((h=(d=this.element)==null?void 0:d.canPlayType)!=null&&h.call(d,l)&&((f=(p=ct())==null?void 0:p.isTypeSupported)!=null&&f.call(p,`${l}; codecs="${c}"`))||u==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((o=t.duration)!=null?o:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:p,codecs:f})=>i(u,p,f)),d=new Set(c.map(({codecs:p})=>p)),h=ng(d);if(h&&(r[u]=c.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,f=r.video.some(g=>g.hdr),b=r.video.some(g=>!g.hdr);SR.isHDR&&p&&f?r.video=r.video.filter(g=>g.hdr):b&&(r.video=r.video.filter(g=>!g.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",ma(s)),s}.bind(this));this.initRepresentations=al(this.destroyController.signal,async function*(e,t,i){var h;this.tracer.log("initRepresentationsStart",ma({initialVideo:e,initialAudio:t,sourceHls:i})),ri(this.manifest),ri(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(ai(p,"error").pipe(sl(f=>{var b;return!!((b=this.element)!=null&&b.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:pt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?Hb():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Os())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);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,f)=>[...p,...f.representations],[]);if(this.videoBufferManager=new la("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],uS(t)){let p=this.manifest.streams.audio.reduce((f,b)=>[...f,...b.representations],[]);this.audioBufferManager=new la("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}fa.isSupported(this.manifest.streams.text)&&!this.tuning.dashCmafLive.lowLatency.isActive&&(this.liveTextManager=new fa(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(nl(1e3).subscribe(p=>{var f;if((f=this.element)!=null&&f.paused){let b=mu(this.manifestUrlString,2);this.manifestUrlString=ie(this.manifestUrlString,b+1e3,2)}}));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.timeInWaiting=0};if(this.representationSubscription.add(si(...xR.map(p=>ai(this.element,p))).pipe(ol(p=>this.element?Ze(this.element.buffered,this.element.currentTime*1e3):0),oS(),TR(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(si(ai(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(oS()).subscribe(f=>rl(this.element,1))),this.representationSubscription.add(en({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(sl(({bufferLength:f,isActiveLowLatency:b})=>b&&!!f)).subscribe(({bufferLength:f})=>this.liveEstimatedDelay.next(f))),this.representationSubscription.add(en({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:f,isActiveLowLatency:b})=>{if(!b)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,y=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,I=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,S=f-g,T=1;Math.abs(S)>y&&(T=1+Math.sign(S)*I),rl(this.element,T)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var g,y;let b=0;if(f){let I=((y=(g=this.element)==null?void 0:g.currentTime)!=null?y:0)*1e3;b=Math.min(...this.bufferManagers.map(T=>{var E,k;return(k=(E=T.getLiveSegmentsToLoadState(this.manifest))==null?void 0:E.to)!=null?k:I}))-I}this.liveLoadBufferLength$.getValue()!==b&&this.liveLoadBufferLength$.next(b)}));let p=0;this.representationSubscription.add(en({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(IR(1e3)).subscribe(async({liveLoadBufferLength:f,bufferLength:b})=>{if(ri(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,y=mu(this.manifestUrlString,2),I=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,S=Math.min(I,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),T=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,E=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,k=isFinite(f)?f:b,C=this.isActiveLowLatency$.getValue(),N=I<=this.tuning.live.activeLiveDelay&&y===0;this.isActiveLowLatency$.next(C&&N);let $="none";if(C?$="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&N?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(B=>B.proceedLowLatencyLive()),$="active_low_latency"):y!==0&&k<S?$="live_forward_buffering":k<S+E&&($="live_with_target_offset"),isFinite(f)&&(p=f>p?f:p),$==="live_forward_buffering"||$==="live_with_target_offset"){let B=p-(S+T),O=this.normolizeLiveOffset(Math.trunc(y+B/g)),R=Math.abs(O-y),w;!f||R<=this.tuning.dashCmafLive.offsetCalculationError?w=y:O>0&&R>this.tuning.dashCmafLive.offsetCalculationError?w=O:w=0,this.manifestUrlString=ie(this.manifestUrlString,w,2)}$!=="none"&&$!=="active_low_latency"&&(p=0,this.updateLive())}))}let l=si(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(ol(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=si(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(ol(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(si(this.forceEnded$,en({allBuffersFull:l,someBufferEnded:c}).pipe(sl(({allBuffersFull:p,someBufferEnded:f})=>p&&f))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{(p=this.source)==null||p.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:pt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(si(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.subscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>{var f;return(f=this.source)==null?void 0:f.addEventListener("sourceopen",p)}));let d=[(h=this.manifest.duration)!=null?h:0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{let f=[];return p.duration&&f.push(p.duration),Ae(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&f.push(p.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...d)/1e3,this.audioBufferManager&&uS(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(i=this.liveTextManager)==null||i.maintain(e),(this.videoBufferManager.gaps.length||(r=this.audioBufferManager)!=null&&r.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=nl(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:pt.WTF,message:"Error handling gaps",thrown:s})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Ks({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=ii.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator}),this.initTracerSubscription()}async seekLive(e){var i,r,s;ri(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=ie(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((i=this.videoBufferManager)==null?void 0:i.seekLive(this.manifest.streams.video)),await((r=this.audioBufferManager)==null?void 0:r.seekLive(this.manifest.streams.audio)),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))}initBuffer(){ri(this.element),this.state$.setState("running"),this.subscription.add(si(...ER.map(e=>ai(this.element,e)),ai(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:pt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(ai(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(ai(this.element,"waiting").subscribe(()=>{var t,i,r;this.element&&this.element.readyState===2&&!this.element.seeking&&Ni(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var f,b,g,y,I,S,T,E,k,C;if(!this.element)return;this.timeInWaiting+=1e3;let s={timeInWaiting:this.timeInWaiting},n=yR(),o=100,u=(b=(f=this.videoBufferManager)==null?void 0:f.lastDataObtainedTimestamp)!=null?b:0,l=(y=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?y:0,c=(S=(I=this.videoBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?S:0,d=(E=(T=this.audioBufferManager)==null?void 0:T.getForwardBufferDuration())!=null?E:0,h=c<o&&n-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&d<o&&n-l>this.tuning.dash.crashOnStallTWithoutDataTimeout;if(this.tuning.useNewProviderReinitLogic&&(h||p)&&this.timeInWaiting>this.tuning.dash.crashOnStallTWithoutDataTimeout||this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.timeInWaiting} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset),s.liveLastSeekOffset=this.liveLastSeekOffset;else{let N=this.element.currentTime*1e3;(k=this.videoBufferManager)==null||k.maintain(N),(C=this.audioBufferManager)==null||C.maintain(N),s.position=N}this.tracer.log("stallIntervalCallback",ma(s))};(t=this.videoBufferManager)==null||t.startAccumulateBuffer(),(i=this.audioBufferManager)==null||i.startAccumulateBuffer(),(r=this.stallWatchdogSubscription)==null||r.unsubscribe(),this.stallWatchdogSubscription=nl(1e3).subscribe(e,s=>{this.error$.next({id:"StallWatchdogCallback",category:this.tuning.useNewProviderReinitLogic?pt.NETWORK:pt.FATAL,message:"Can't restore DASH after stall.",thrown:s})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return r==null?void 0:r.switchTo(t,i)}seek(e,t){var r,s,n,o,u,l;ri(this.element),ri(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),Ni(this.element.buffered,i)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.startAccumulateBuffer(),this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.startAccumulateBuffer(),(l=this.audioBufferManager)==null||l.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",ma({requestedPosition:e,forcePrecise:t,position:i}))}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>r.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=vR(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.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 i=this.element.currentTime*1e3,r=[],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<=i&&o.to+s>i&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?r.push(1/0):r.push(o.to));if(r.length){let n=Math.max(...r)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t={...t,gapEnds:r,jumpTo:n,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",ma(t)))}}};var rn=class{constructor(e,t){this.fov=e,this.orientation=t}};var an=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var dS=`attribute vec2 a_vertex;
|
|
65
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var Gg=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==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],i),hours:e(r==null?void 0:r[6],i),minutes:e(r==null?void 0:r[7],i),seconds:e(r==null?void 0:r[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},ct=(a,e)=>{let t=a;t=(0,ju.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of Object.entries(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,ju.default)(t,n,(o,u)=>jg(s)?o:jg(u)?s:s.padStart(parseInt(u,10),"0"))}return t},Qg=(a,e)=>{var I,k,C,q,R,D,B,w,A,U,z,y,$,j,O,ae,_e,or,Wr,N,le,ye,ke,pt,ur,ht,Bt,lr,Qr,Il,El,xl,Pl,Al,wl,kl,Rl,$l,Ll,Ml,Cl,Dl,Bl,Ol,Vl,_l,Nl,Fl,Ul,ql,Hl,jl,Gl,Wl,Ql,Yl,zl,Kl,Jl,Xl;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(te=>{var ka,ft;return(ft=(ka=te.textContent)==null?void 0:ka.trim())!=null?ft:""}),u=(I=(0,Wg.default)(o,0))!=null?I:"",l=n.children,c=s.getAttribute("type")==="dynamic",d=s.getAttribute("availabilityStartTime"),h=d?new Date(d).getTime():void 0,p,f=s.getAttribute("mediaPresentationDuration"),b=n.getAttribute("duration"),g=s.getElementsByTagName("vk:Attrs")[0],v=g==null?void 0:g.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)p=Gg(f);else if(b){let te=Gg(b);Hg(te)&&(p=te)}else v&&(p=parseInt(v,10));let T=0,S=(C=(k=s.getAttribute("profiles"))==null?void 0:k.split(","))!=null?C:[];for(let te of l){let ka=(q=te.getAttribute("id"))!=null?q:"id"+(T++).toString(10),ft=(R=te.getAttribute("mimeType"))!=null?R:"",gn=(D=te.getAttribute("codecs"))!=null?D:"",Sn=(B=te.getAttribute("contentType"))!=null?B:ft==null?void 0:ft.split("/")[0],nv=(A=(w=te.getAttribute("profiles"))==null?void 0:w.split(","))!=null?A:[],Zl=(z=qg((U=te.getAttribute("lang"))!=null?U:""))!=null?z:{},ov=(j=($=(y=te.querySelector("Label"))==null?void 0:y.textContent)==null?void 0:$.trim())!=null?j:void 0,uv=te.querySelectorAll("Representation"),lv=te.querySelector("SegmentTemplate"),cv=(ae=(O=te.querySelector("Role"))==null?void 0:O.getAttribute("value"))!=null?ae:void 0,Yr=Sn,K={id:ka,language:Zl.language,isDefault:cv==="main",label:ov,codecs:gn,hdr:Yr==="video"&&Hu(gn),mime:ft,representations:[]};for(let G of uv){let dv=(_e=G.getAttribute("lang"))!=null?_e:void 0,pv=(or=G.getAttribute("label"))!=null?or:void 0,hv=(le=(N=(Wr=G.querySelector("BaseURL"))==null?void 0:Wr.textContent)==null?void 0:N.trim())!=null?le:"",Ra=new URL(hv||u,e).toString(),cr=(ye=G.getAttribute("mimeType"))!=null?ye:ft,$a=(pt=(ke=G.getAttribute("codecs"))!=null?ke:gn)!=null?pt:"",La;if(Sn==="text"){let mt=G.getAttribute("id")||"",Ma=((ur=Zl.privateuse)==null?void 0:ur.includes("x-auto"))||mt.includes("_auto"),Ot=G.querySelector("SegmentTemplate");if(Ot){let zr={representationId:(ht=G.getAttribute("id"))!=null?ht:void 0,bandwidth:(Bt=G.getAttribute("bandwidth"))!=null?Bt:void 0},Ca=parseInt((lr=G.getAttribute("bandwidth"))!=null?lr:"",10)/1e3,Da=(Il=parseInt((Qr=Ot.getAttribute("startNumber"))!=null?Qr:"",10))!=null?Il:1,dr=parseInt((El=Ot.getAttribute("timescale"))!=null?El:"",10),vn=(xl=Ot.querySelectorAll("SegmentTimeline S"))!=null?xl:[],pr=Ot.getAttribute("media");if(!pr)continue;let Ba=[],Oa=0,Va="",hr=0,Kr=Da,se=0;for(let Ne of vn){let Vt=parseInt((Pl=Ne.getAttribute("d"))!=null?Pl:"",10),Re=parseInt((Al=Ne.getAttribute("r"))!=null?Al:"",10)||0,bt=parseInt((wl=Ne.getAttribute("t"))!=null?wl:"",10);se=Number.isFinite(bt)?bt:se;let _t=Vt/dr*1e3,gt=se/dr*1e3;for(let Ye=0;Ye<Re+1;Ye++){let St=ct(pr,{...zr,segmentNumber:Kr.toString(10),segmentTime:(se+Ye*Vt).toString(10)}),fr=(gt!=null?gt:0)+Ye*_t,Xr=fr+_t;Kr++,Ba.push({time:{from:fr,to:Xr},url:St})}se+=(Re+1)*Vt,Oa+=(Re+1)*_t}hr=se/dr*1e3,Va=ct(pr,{...zr,segmentNumber:Kr.toString(10),segmentTime:se.toString(10)});let Jr={time:{from:hr,to:1/0},url:Va},tt={type:"template",baseUrl:Ra,segmentTemplateUrl:pr,initUrl:"",totalSegmentsDurationMs:Oa,segments:Ba,nextSegmentBeyondManifest:Jr,timescale:dr};La={id:mt,kind:"text",segmentReference:tt,profiles:[],duration:p,bitrate:Ca,mime:"",codecs:"",width:0,height:0,isAuto:Ma}}else La={id:mt,isAuto:Ma,kind:"text",url:Ra}}else{let mt=(Rl=(kl=G.getAttribute("contentType"))!=null?kl:cr==null?void 0:cr.split("/")[0])!=null?Rl:Sn,Ma=(Ll=($l=te.getAttribute("profiles"))==null?void 0:$l.split(","))!=null?Ll:[],Ot=parseInt((Ml=G.getAttribute("width"))!=null?Ml:"",10),zr=parseInt((Cl=G.getAttribute("height"))!=null?Cl:"",10),Ca=parseInt((Dl=G.getAttribute("bandwidth"))!=null?Dl:"",10)/1e3,Da=(Bl=G.getAttribute("frameRate"))!=null?Bl:"",dr=(Ol=G.getAttribute("quality"))!=null?Ol:void 0,vn=Da?Ug(Da):void 0,pr=(Vl=G.getAttribute("id"))!=null?Vl:"id"+(T++).toString(10),Ba=mt==="video"?`${zr}p`:mt==="audio"?`${Ca}Kbps`:$a,Oa=`${pr}@${Ba}`,Va=[...S,...nv,...Ma],hr,Kr=G.querySelector("SegmentBase"),se=(_l=G.querySelector("SegmentTemplate"))!=null?_l:lv;if(Kr){let tt=(Fl=(Nl=G.querySelector("SegmentBase Initialization"))==null?void 0:Nl.getAttribute("range"))!=null?Fl:"",[Ne,Vt]=tt.split("-").map(St=>parseInt(St,10)),Re={from:Ne,to:Vt},bt=(Ul=G.querySelector("SegmentBase"))==null?void 0:Ul.getAttribute("indexRange"),[_t,gt]=bt?bt.split("-").map(St=>parseInt(St,10)):[],Ye=bt?{from:_t,to:gt}:void 0;hr={type:"byteRange",url:Ra,initRange:Re,indexRange:Ye}}else if(se){let tt={representationId:(ql=G.getAttribute("id"))!=null?ql:void 0,bandwidth:(Hl=G.getAttribute("bandwidth"))!=null?Hl:void 0},Ne=parseInt((jl=se.getAttribute("timescale"))!=null?jl:"",10),Vt=(Gl=se.getAttribute("initialization"))!=null?Gl:"",Re=se.getAttribute("media"),bt=(Ql=parseInt((Wl=se.getAttribute("startNumber"))!=null?Wl:"",10))!=null?Ql:1,_t=ct(Vt,tt);if(!Re)throw new ReferenceError("No media attribute in SegmentTemplate");let gt=(Yl=se.querySelectorAll("SegmentTimeline S"))!=null?Yl:[],Ye=[],St=0,fr="",Xr=0;if(gt.length){let _a=bt,Fe=0;for(let mr of gt){let ze=parseInt((zl=mr.getAttribute("d"))!=null?zl:"",10),Nt=parseInt((Kl=mr.getAttribute("r"))!=null?Kl:"",10)||0,Na=parseInt((Jl=mr.getAttribute("t"))!=null?Jl:"",10);Fe=Number.isFinite(Na)?Na:Fe;let yn=ze/Ne*1e3,Tn=Fe/Ne*1e3;for(let Fa=0;Fa<Nt+1;Fa++){let mv=ct(Re,{...tt,segmentNumber:_a.toString(10),segmentTime:(Fe+Fa*ze).toString(10)}),ec=(Tn!=null?Tn:0)+Fa*yn,bv=ec+yn;_a++,Ye.push({time:{from:ec,to:bv},url:mv})}Fe+=(Nt+1)*ze,St+=(Nt+1)*yn}Xr=Fe/Ne*1e3,fr=ct(Re,{...tt,segmentNumber:_a.toString(10),segmentTime:Fe.toString(10)})}else if(Hg(p)){let Fe=parseInt((Xl=se.getAttribute("duration"))!=null?Xl:"",10)/Ne*1e3,mr=Math.ceil(p/Fe),ze=0;for(let Nt=1;Nt<mr;Nt++){let Na=ct(Re,{...tt,segmentNumber:Nt.toString(10),segmentTime:ze.toString(10)});Ye.push({time:{from:ze,to:ze+Fe},url:Na}),ze+=Fe}Xr=ze,fr=ct(Re,{...tt,segmentNumber:mr.toString(10),segmentTime:ze.toString(10)})}let fv={time:{from:Xr,to:1/0},url:fr};hr={type:"template",baseUrl:Ra,segmentTemplateUrl:Re,initUrl:_t,totalSegmentsDurationMs:St,segments:Ye,nextSegmentBeyondManifest:fv,timescale:Ne}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!mt||!cr)continue;let Jr={video:"video",audio:"audio",text:"text"}[mt];if(!Jr)continue;Yr||(Yr=Jr),La={id:Oa,kind:Jr,segmentReference:hr,profiles:Va,duration:p,bitrate:Ca,mime:cr,codecs:$a,width:Ot,height:zr,fps:vn,quality:dr}}K.language||(K.language=dv),K.label||(K.label=pv),K.mime||(K.mime=cr),K.codecs||(K.codecs=$a),K.hdr||(K.hdr=Yr==="video"&&Hu($a)),K.representations.push(La)}Yr&&i[Yr].push(K)}return{dynamic:c,liveAvailabilityStartTime:h,duration:p,streams:i,baseUrls:o}};var Qu=Ue(Br(),1);import{videoSizeToQuality as oR}from"@vkontakte/videoplayer-shared";var Yg=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s})=>{var o;let n=(o=s?xt(s):void 0)!=null?o:oR({width:e,height:t});return n&&{id:a,quality:n,bitrate:r,size:{width:e,height:t},fps:i}},zg=({id:a,bitrate:e})=>({id:a,bitrate:e}),Kg=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Jg=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Yu=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Qu.default)(r.split("."),0),isDefault:i}),zu=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Qu.default)(i.split("."),0)}),Ku=a=>"url"in a,Pe=a=>a.type==="template",sa=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var ua=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentSegmentLength$=new oa(0);this.onLastSegment$=new oa(!1);this.fullyBuffered$=new oa(!1);this.playingRepresentation$=new oa(void 0);this.playingRepresentationInit$=new oa(void 0);this.error$=new lR;this.gaps=[];this.subscription=new cR;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new xe;this.switchAbortController=new xe;this.destroyAbortController=new xe;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=er(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);ee(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.resetAccumulateBufferAfterStall(),this.startAccumulateBuffer(),this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new cg(this.sourceBuffer),this.subscription.add(Ju(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:kt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:kt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Ju(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:kt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,Bu(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=Ze(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),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);ee(r,"No init buffer for starting representation"),ee(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.switchToOld=er(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);ee(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(Ae(s)||Ae(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),ee(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(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();na(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=er(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=e==null?void 0:e.flatMap(c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(f=>f.id===c);d&&this.representations.set(c,d);let h=this.representations.get(c);if(!h||!Pe(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let r=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,i=this.representations.get(r);ee(i);let s=this.segments.get(r);ee(s,"No segments for starting representation");let n=this.initData.get(r);if(ee(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,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));var c;this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],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}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new xe,er(this.switchAbortController.signal,async function*(r,i=!1){this.switchingToRepresentationId=r;let s=this.representations.get(r);ee(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if(Ae(o)||Ae(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),ee(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer)){if(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();na(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))}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new xe,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,c;if(Ae(e)||Ae(this.downloadingRepresentationId)||Ae(this.playingRepresentationId)||Ae(this.sourceBuffer)||na(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(ee(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((l=i==null?void 0:i.time.to)!=null?l:0)-((c=i==null?void 0:i.time.from)!=null?c:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let h=Ze(this.sourceBuffer.buffered,e),p=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=i.time.to-e+100&&(s=p)}if(isFinite(this.bufferLimit)&&Bu(this.sourceBuffer.buffered)>=this.bufferLimit){let d=Ze(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if(o.includes(i))d="high";else{let h=(0,qr.default)(o,0);h&&h.time.from-i.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&Ze(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,qr.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;na(t.duration)&&t.duration-r>0&&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=e==null?void 0:e.streams[this.kind].flatMap(i=>i.representations).find(i=>i.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var r,i,s,n;let t=(r=e==null?void 0:e.streams[this.kind].flatMap(o=>o.representations))!=null?r:[];for(let o of t){if(!o||!Pe(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>({...h,status:"none",size:void 0})),l=(i=this.segments.get(o.id))!=null?i:[],c=(n=(s=(0,qr.default)(l,-1))==null?void 0:s.time.to)!=null?n:0,d=u==null?void 0:u.findIndex(h=>Math.floor(c)>=Math.floor(h.time.from)&&Math.floor(c)<=Math.floor(h.time.to));if(d===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(d+1);this.segments.set(o.id,[...l,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;ee(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}startAccumulateBuffer(){this.bufferAccumulation.enabled=!0}resetAccumulateBufferAfterStall(){var s;ee(this.playingRepresentationId);let e=(s=this.representations.get(this.playingRepresentationId))==null?void 0:s.duration;ee(e);let{shortVideoDuration:t,shortVideoBufferStallSizeMs:r,longVideoBufferStallSizeMs:i}=this.tuning.dash.accumulationBufferStallSize;this.bufferAccumulation={enabled:!1,targetBufferSizeMs:e<=t?r:i,accumulatedBufferSizeMs:0,accumulated:[]}}updateLowLatencyLiveIfNeeded(e){var t;for(let r of this.representations.values()){let i=r.segmentReference;if(!Pe(i))return;let s=(t=this.segments.get(r.id))!=null?t:[],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),!!!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=ct(i.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,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:d,time:{from:h,to:p}},f)=>{let b=h<=r&&p>=r,g=h>r||b||f===0&&r===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&h<=r+v||p<=r+v;return(d==="none"||d==="partially_ejected"&&g&&T&&this.sourceBuffer&&!(At(this.sourceBuffer.buffered,h)&&At(this.sourceBuffer.buffered,p)))&&g&&T});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,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=l||o<=c);d++){let h=s[d];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);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 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 er(o,async function*(){let c=Xu(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=Ws(),!c)return;let d=new DataView(c);if(!isFinite(i.segment.time.to)){let h=t.segmentReference.timescale,p=aa(t.mime);i.segment.time.to=p.getChunkEndTime(d,h)}u&&i.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),sa(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:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await er(n,async function*(){let u=Xu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Ju(window,"online").pipe(uR()).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=Ws(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),sa(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,i={from:(0,qr.default)(e,0).byte.from,to:(0,qr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Ws(),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:kt.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 i=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=Ws();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:kt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(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),c=aa(n.mime).parseFeedableSegmentChunk(l,this.isLive);c!=null&&c.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom: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){n();continue}let c=l.byte.from-r,d=l.byte.to-r,h=d-c+1,p=c<i,f=d<=i;if(!p)continue;let b=aa(o.mime),g=this.tuning.dash.enableSubSegmentBufferFeeding&&(Sg(b)||this.bufferAccumulation.targetBufferSizeMs===0);if(l.status==="downloading"&&f){l.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+c,h),T=this.getCurrentPosition();na(T)&&(this.bufferAccumulation.accumulatedBufferSizeMs=l.time.to-T,this.bufferAccumulation.accumulated.push({dataView:v,segmentProgress:u}),this.activeSegments.delete(u));let S=async({dataView:E,segmentProgress:I})=>{await this.sourceBufferTaskQueue.append(E,s)&&!s.aborted?this.onSegmentFullyAppended(I,t):n()};this.bufferAccumulation.enabled&&this.bufferAccumulation.accumulatedBufferSizeMs>this.bufferAccumulation.targetBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(S),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||Ae(T))&&(S({dataView:v,segmentProgress:u}),this.resetAccumulateBufferAfterStall())}else if(g&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(h,i-c),u.loadedBytes>u.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),T=u.loadedBytes===h?v:b.parseFeedableSegmentChunk(v);T!=null&&T.byteLength&&(l.status="partially_fed",u.feedingBytes+=T.byteLength,await this.sourceBufferTaskQueue.append(T,s)&&!s.aborted?(u.fedBytes+=T.byteLength,u.fedBytes===h&&this.onSegmentFullyAppended(u,t)):n())}}}onSegmentFullyAppended(e,t){var r;this.tuning.useSafariEndlessRequestBugfix&&(ee(this.sourceBuffer),At(this.sourceBuffer.buffered,e.segment.time.from,10)&&At(this.sourceBuffer.buffered,e.segment.time.to,10)||this.error$.next({id:"SafariEmptyAppendBuffer",category:kt.VIDEO_PIPELINE,message:"Safari 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",Ku(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let s of(r=this.segments.get(i.id))!=null?r:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");ee(this.sourceBuffer),this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment]),this.tuning.useNewPruneBufferStrategy&&this.pruneBuffer(this.getCurrentPosition(),1/0,!1)}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||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=Mu(()=>(0,Xg.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?er(this.destroyAbortController.signal,async function*(){let o=Xu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,aa(e.mime),i)).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 h=c;this.isLive&&Pe(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),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:kt.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||!this.playingRepresentationId||Ae(e)||this.sourceBuffer.updating)return!1;let i=[],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:h}=u[c],p=l[l.length-1];p.to>=d?p.to=Math.max(p.to,h):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push({...u.time}),i=n(i);let l=Ku(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let h of this.segments.values())for(let p of h)["none","partially_ejected"].includes(p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let h={time:{from:l,to:c},url:"",status:"none"};o(h)}}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 c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return i.length?(await Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!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||!this.sourceBuffer.buffered.length||Ae(e)?0:Ze(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(this.sourceBuffer)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){ee(this.sourceBuffer);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=Mu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:kt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Ae(this.sourceBuffer)||Ae(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(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?i.status="partially_ejected":this.gaps.some(c=>c.from===i.time.from||c.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var la=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Zg=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,i=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:i}};import{abortable as ca,assertNever as tS,fromEvent as rS,merge as dR,now as da,Subscription as pR,ValueSubject as Zu,flattenObject as Hr}from"@vkontakte/videoplayer-shared";var eS=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Qs=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Zu(void 0);this.lastConnectionReused$=new Zu(void 0);this.lastRequestFirstBytes$=new Zu(void 0);this.abortAllController=new xe;this.subscription=new pR;this.fetchManifest=ca(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=la(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=eS(r));let i=yield ut(r,{signal:this.abortAllController.signal}).catch(pa);return i?(t.log("success",Hr({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",Hr({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=ca(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}={}){var B,w;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 A=new URL(l,location.href);A.searchParams.append("bytes",`${r.from}-${r.to}`),l=A.toString();break}default:tS(t)}this.requestQuic&&(l=la(l));let h=this.abortAllController.signal,p;if(n){let A=new xe;if(p=dR(rS(this.abortAllController.signal,"abort"),rS(n,"abort")).subscribe(()=>{try{A.abort()}catch(U){pa(U)}}),this.abortAllController.signal.aborted||n.aborted)try{A.abort()}catch(U){pa(U)}h=A.signal}let f=da();d.log("startRequest",Hr({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:f}));let b=yield ut(l,{priority:s,headers:c,signal:h}).catch(pa),g=da();if(!b)return d.error("error",{message:"No response in request"}),d.end(),p==null||p.unsubscribe(),null;if((B=this.throughputEstimator)==null||B.addRawRtt(g-f),!b.ok||!b.body){p==null||p.unsubscribe();let A=`Fetch error ${b.status}: ${b.statusText}`;return d.error("error",{message:A}),d.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!i&&!o){p==null||p.unsubscribe();let A=da(),U={requestStartedAt:f,requestEndedAt:A,duration:A-f};return d.log("endRequest",Hr(U)),d.end(),b.arrayBuffer()}let[v,T]=b.body.tee(),S=v.getReader();o&&((w=this.throughputEstimator)==null||w.trackStream(T,u));let E=0,I=new Uint8Array(0),k=!1,C=A=>{p==null||p.unsubscribe(),k=!0,pa(A)},q=ca(h,async function*({done:A,value:U}){if(E===0&&this.lastRequestFirstBytes$.next(da()-f),h.aborted){p==null||p.unsubscribe();return}if(!A&&U){let z=new Uint8Array(I.length+U.length);z.set(I),z.set(U,I.length),I=z,E+=U.byteLength,i==null||i(new DataView(I.buffer),E),yield S==null?void 0:S.read().then(q,C)}}.bind(this));yield S==null?void 0:S.read().then(q,C),p==null||p.unsubscribe();let R=da(),D={failed:k,requestStartedAt:f,requestEndedAt:R,duration:R-f};return k?(d.error("endRequest",Hr(D)),d.end(),null):(d.log("endRequest",Hr(D)),d.end(),I.buffer)}.bind(this));this.fetchByteRangeRepresentation=ca(this.abortAllController.signal,async function*(e,t,r){var v;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,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,i),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 h=new DataView(d,i-n,s-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),f=(v=e.indexRange)!=null?v:t.getIndexRange(p);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 T=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!T)return null;b=new DataView(T)}let g=t.parseSegments(b,p,f);return{init:p,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=ca(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}=Zg(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,r))!=null?n:null;default:tS(i)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},pa=a=>{if(!sa(a))throw a};var tr=(a,e,t)=>t*e+(1-t)*a,el=(a,e)=>a.reduce((t,r)=>t+r,0)/e,iS=(a,e,t,r)=>{let i=0,s=t,n=el(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 hR,ValueSubject as aS}from"@vkontakte/videoplayer-shared";var Rt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new aS(e.initial),this.debounced$=new aS(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new oe(`raw_${t}`),this.smoothedSeries$=new oe(`smoothed_${t}`),this.reportedSeries$=new oe(`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)&&(hR(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 Ys=class extends Rt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=tr(this.slow,e,this.params.emaAlphaSlow),this.fast=tr(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var zs=class extends Rt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=el(this.pastMeasures,this.takenMeasures);this.emaSmoothed=tr(this.emaSmoothed,e,this.params.emaAlpha);let r=iS(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Ks=class extends Rt{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?tr(this.smoothed,t,this.params.emaAlpha):t}};var rr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new Ys({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new zs({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new Ks({initial:e,label:"liveEdgeDelay",...t})}};var tl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as fR,ValueSubject as mR}from"@vkontakte/videoplayer-shared";var ha=class a{constructor(e,t){this.currentRepresentation$=new mR(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!fR(e))for(let r of this.representations)for(let i of r){let s=i.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let 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!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Pe(t.segmentReference))}};var ER=["timeupdate","progress","play","seeked","stalled","waiting"],xR=["timeupdate","progress","loadeddata","playing","seeked"];var Xs=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new lS;this.representationSubscription=new lS;this.state$=new L("none");this.currentVideoRepresentation$=new ie(void 0);this.currentVideoRepresentationInit$=new ie(void 0);this.currentAudioRepresentation$=new ie(void 0);this.currentVideoSegmentLength$=new ie(0);this.currentAudioSegmentLength$=new ie(0);this.error$=new uS;this.lastConnectionType$=new ie(void 0);this.lastConnectionReused$=new ie(void 0);this.lastRequestFirstBytes$=new ie(void 0);this.currentLiveTextRepresentation$=new ie(null);this.isLive$=new ie(!1);this.liveDuration$=new ie(0);this.liveAvailabilityStartTime$=new ie(void 0);this.bufferLength$=new ie(0);this.liveLoadBufferLength$=new ie(0);this.livePositionFromPlayer$=new ie(0);this.isActiveLowLatency$=new ie(!1);this.timeInWaiting=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new uS;this.gapWatchdogActive=!1;this.destroyController=new xe;this.initManifest=rl(this.destroyController.signal,async function*(e,t,r){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=re(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:$t.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=rl(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:$t.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Qg(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=ag(e))!=null?n:{id:"ManifestParsing",category:$t.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let r=(u,l,c)=>{var d,h,p,f;return!!((h=(d=this.element)==null?void 0:d.canPlayType)!=null&&h.call(d,l)&&((f=(p=lt())==null?void 0:p.isTypeSupported)!=null&&f.call(p,`${l}; codecs="${c}"`))||u==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((o=t.duration)!=null?o:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:p,codecs:f})=>r(u,p,f)),d=new Set(c.map(({codecs:p})=>p)),h=ig(d);if(h&&(i[u]=c.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,f=i.video.some(g=>g.hdr),b=i.video.some(g=>!g.hdr);SR.isHDR&&p&&f?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s={...t,streams:i};return this.tracer.log("updateManifestEnd",fa(s)),s}.bind(this));this.initRepresentations=rl(this.destroyController.signal,async function*(e,t,r){var h;this.tracer.log("initRepresentationsStart",fa({initialVideo:e,initialAudio:t,sourceHls:r})),ir(this.manifest),ir(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(ar(p,"error").pipe(il(f=>{var b;return!!((b=this.element)!=null&&b.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:$t.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?Fb():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Bs())if(r){let p=document.createElement("source");i(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.tuning.dashCmafLive.lowLatency.isActive);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,f)=>[...p,...f.representations],[]);if(this.videoBufferManager=new ua("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],oS(t)){let p=this.manifest.streams.audio.reduce((f,b)=>[...f,...b.representations],[]);this.audioBufferManager=new ua("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}ha.isSupported(this.manifest.streams.text)&&!this.tuning.dashCmafLive.lowLatency.isActive&&(this.liveTextManager=new ha(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(al(1e3).subscribe(p=>{var f;if((f=this.element)!=null&&f.paused){let b=du(this.manifestUrlString,2);this.manifestUrlString=re(this.manifestUrlString,b+1e3,2)}}));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.timeInWaiting=0};if(this.representationSubscription.add(sr(...xR.map(p=>ar(this.element,p))).pipe(sl(p=>this.element?Ze(this.element.buffered,this.element.currentTime*1e3):0),nS(),TR(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(sr(ar(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(nS()).subscribe(f=>tl(this.element,1))),this.representationSubscription.add(Js({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(il(({bufferLength:f,isActiveLowLatency:b})=>b&&!!f)).subscribe(({bufferLength:f})=>this.liveEstimatedDelay.next(f))),this.representationSubscription.add(Js({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:f,isActiveLowLatency:b})=>{if(!b)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,S=f-g,E=1;Math.abs(S)>v&&(E=1+Math.sign(S)*T),tl(this.element,E)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var g,v;let b=0;if(f){let T=((v=(g=this.element)==null?void 0:g.currentTime)!=null?v:0)*1e3;b=Math.min(...this.bufferManagers.map(E=>{var I,k;return(k=(I=E.getLiveSegmentsToLoadState(this.manifest))==null?void 0:I.to)!=null?k:T}))-T}this.liveLoadBufferLength$.getValue()!==b&&this.liveLoadBufferLength$.next(b)}));let p=0;this.representationSubscription.add(Js({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(IR(1e3)).subscribe(async({liveLoadBufferLength:f,bufferLength:b})=>{if(ir(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,v=du(this.manifestUrlString,2),T=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,S=Math.min(T,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),E=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,I=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,k=isFinite(f)?f:b,C=this.isActiveLowLatency$.getValue(),q=T<=this.tuning.live.activeLiveDelay&&v===0;this.isActiveLowLatency$.next(C&&q);let R="none";if(C?R="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&q?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(D=>D.proceedLowLatencyLive()),R="active_low_latency"):v!==0&&k<S?R="live_forward_buffering":k<S+I&&(R="live_with_target_offset"),isFinite(f)&&(p=f>p?f:p),R==="live_forward_buffering"||R==="live_with_target_offset"){let D=p-(S+E),B=this.normolizeLiveOffset(Math.trunc(v+D/g)),w=Math.abs(B-v),A;!f||w<=this.tuning.dashCmafLive.offsetCalculationError?A=v:B>0&&w>this.tuning.dashCmafLive.offsetCalculationError?A=B:A=0,this.manifestUrlString=re(this.manifestUrlString,A,2)}R!=="none"&&R!=="active_low_latency"&&(p=0,this.updateLive())}))}let l=sr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(sl(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=sr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(sl(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(sr(this.forceEnded$,Js({allBuffersFull:l,someBufferEnded:c}).pipe(il(({allBuffersFull:p,someBufferEnded:f})=>p&&f))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{(p=this.source)==null||p.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:$t.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(sr(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.subscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>{var f;return(f=this.source)==null?void 0:f.addEventListener("sourceopen",p)}));let d=[(h=this.manifest.duration)!=null?h:0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{let f=[];return p.duration&&f.push(p.duration),Pe(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&f.push(p.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...d)/1e3,this.audioBufferManager&&oS(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,r,i;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(i=this.audioBufferManager)!=null&&i.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=al(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:$t.WTF,message:"Error handling gaps",thrown:s})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Qs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveEstimatedDelay=rr.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator}),this.initTracerSubscription()}async seekLive(e){var r,i,s;ir(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=re(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((i=this.audioBufferManager)==null?void 0:i.seekLive(this.manifest.streams.audio)),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))}initBuffer(){ir(this.element),this.state$.setState("running"),this.subscription.add(sr(...ER.map(e=>ar(this.element,e)),ar(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:$t.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(ar(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(ar(this.element,"waiting").subscribe(()=>{var t,r,i;this.element&&this.element.readyState===2&&!this.element.seeking&&At(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var f,b,g,v,T,S,E,I,k,C;if(!this.element)return;this.timeInWaiting+=1e3;let s={timeInWaiting:this.timeInWaiting},n=yR(),o=100,u=(b=(f=this.videoBufferManager)==null?void 0:f.lastDataObtainedTimestamp)!=null?b:0,l=(v=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?v:0,c=(S=(T=this.videoBufferManager)==null?void 0:T.getForwardBufferDuration())!=null?S:0,d=(I=(E=this.audioBufferManager)==null?void 0:E.getForwardBufferDuration())!=null?I:0,h=c<o&&n-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&d<o&&n-l>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((h||p)&&this.timeInWaiting>this.tuning.dash.crashOnStallTWithoutDataTimeout||this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.timeInWaiting} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset),s.liveLastSeekOffset=this.liveLastSeekOffset;else{let q=this.element.currentTime*1e3;(k=this.videoBufferManager)==null||k.maintain(q),(C=this.audioBufferManager)==null||C.maintain(q),s.position=q}this.tracer.log("stallIntervalCallback",fa(s))};(t=this.videoBufferManager)==null||t.startAccumulateBuffer(),(r=this.audioBufferManager)==null||r.startAccumulateBuffer(),(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=al(1e3).subscribe(e,s=>{this.error$.next({id:"StallWatchdogCallback",category:$t.NETWORK,message:"Can't restore DASH after stall.",thrown:s})}),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 i==null?void 0:i.switchTo(t,r)}seek(e,t){var i,s,n,o,u,l;ir(this.element),ir(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((i=this.videoBufferManager.findSegmentStartTime(e))!=null?i:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),At(this.element.buffered,r)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.startAccumulateBuffer(),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.startAccumulateBuffer(),(l=this.audioBufferManager)==null||l.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",fa({requestedPosition:e,forcePrecise:t,position:r}))}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>i.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=vR(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(r=>r.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.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",fa(t)))}}};var Zs=class{constructor(e,t){this.fov=e,this.orientation=t}};var en=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!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?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 cS=`attribute vec2 a_vertex;
|
|
66
66
|
attribute vec2 a_texel;
|
|
67
67
|
|
|
68
68
|
varying vec2 v_texel;
|
|
@@ -73,7 +73,7 @@ void main(void) {
|
|
|
73
73
|
// save texel vector to pass to fragment shader
|
|
74
74
|
v_texel = a_texel;
|
|
75
75
|
}
|
|
76
|
-
`;var
|
|
76
|
+
`;var dS=`#ifdef GL_ES
|
|
77
77
|
precision highp float;
|
|
78
78
|
precision highp int;
|
|
79
79
|
#else
|
|
@@ -116,5 +116,5 @@ void main(void) {
|
|
|
116
116
|
// sample using new coordinates
|
|
117
117
|
gl_FragColor = texture2D(u_texture, tc);
|
|
118
118
|
}
|
|
119
|
-
`;var sn=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new rn(this.params.fov,this.params.orientation),this.cameraRotationManager=new an(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(dS,this.gl.VERTEX_SHADER),i=this.createShader(pS,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,n=t-r,o=e+i,u=t-r,l=e+i,c=t+r,d=e-i,h=t+r;return[s,n,o,u,l,c,d,h]}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}};var ni=class{constructor(e){this.subscription=new OR;this.videoState=new M("stopped");this.elementSize$=new VR(void 0);this.textTracksManager=new De;this.droppedFramesManager=new Ms;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Rr;this.audioTrackSwitchHistory=new Rr;this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let l=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(r.position-l,r.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),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"),x(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"),x(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&x(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&x(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()):(i==null?void 0:i.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return RR(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new sn(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=pe(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Z(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 tn({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,i=me(this.video),r=this.constructor.name,s=o=>{e.error$.next({id:r,category:ul.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){var l;let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(hS(c=>!!c.length),mS()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:c})})),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(hS(CR),mS()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(fS(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Je(this.video,t.isLooped,r)),this.subscription.add(fe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ce(this.video,t.playbackRate,i.playbackRateState$,r)),s(BR(this.video),this.elementSize$),s(Oe(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),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($R(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let f of d.audio){p.push(Ju(f));let b=[];for(let g of f.representations){let y=Jg(g);b.push(y),this.audioTracksMap.set(y,{stream:f,representation:g})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(p)}let h=[];for(let p of d.video){h.push(Xu(p));let f=[];for(let b of p.representations){let g=Kg(b);g&&(f.push(g),this.videoTracksMap.set(g,{stream:p,representation:b}))}this.videoStreamsMap.set(p,f)}if(this.params.output.availableVideoStreams$.next(h),this.textTracksManager)for(let p of d.text)for(let f of p.representations){let b=Xg(p,f);this.textTracksMap.set(b,{stream:p,representation:f})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),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())},r));let n=c=>e.error$.next({id:"RepresentationSwitch",category:ul.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(nn(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.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,MR(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[p,f]=h,b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),c==="manifest_ready")this.player.initRepresentations(p.id,f==null?void 0:f.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(n),f){let g=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",f.id,g).catch(n)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSize$.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(ll()).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[h,{stream:p}]=d,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===p.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Xu(p))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(ll()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:p}]=d,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===p.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(Ju(p))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var d,h;if(c!=null&&c.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(h=this.params.tuning.spherical)!=null&&h.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),(l=this.textTracksManager)==null||l.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(fS(({to:c})=>c==="ready"),ll());this.subscription.add(nn(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(nn(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=nn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,DR(["init"])).pipe(LR(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var k,C,N,$,B,O,R,w,U,z,v,L,H,G,K,ue,tt,ft;let{desiredState:e,output:t}=this.params,i=e.autoVideoTrackSwitching.getState(),r=(k=e.videoTrack.getState())==null?void 0:k.id,n=[...this.videoTracksMap.keys()].find(({id:A})=>A===r),o=t.currentVideoTrack$.getValue(),u=(($=(N=e.videoStream.getState())!=null?N:n&&((C=this.videoTracksMap.get(n))==null?void 0:C.stream))!=null?$:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:A})=>A===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=Ze(this.video.buffered,this.video.currentTime*1e3),h=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,p=Math.min(d/Math.min(h,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),f=(B=e.audioStream.getState())!=null?B:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=(O=[...this.audioStreamsMap.keys()].find(({id:A})=>A===(f==null?void 0:f.id)))!=null?O:this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!i)if(this.params.tuning.useSeparateAudioVideoABR){let A=ks(n,c,(R=this.audioStreamsMap.get(b))!=null?R:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(w=A==null?void 0:A.bitrate)!=null?w:-1/0)}else{let A=Ys(n,c,(U=this.audioStreamsMap.get(b))!=null?U:[]);g=Math.max(g,(z=A==null?void 0:A.bitrate)!=null?z:-1/0)}if(o)if(this.params.tuning.useSeparateAudioVideoABR){let A=ks(o,c,(v=this.audioStreamsMap.get(b))!=null?v:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(L=A==null?void 0:A.bitrate)!=null?L:-1/0)}else{let A=Ys(o,c,(H=this.audioStreamsMap.get(b))!=null?H:[]);g=Math.max(g,(G=A==null?void 0:A.bitrate)!=null?G:-1/0)}}let y=kt(c,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:g,forwardBufferHealth:p,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),I=i?y!=null?y:n:n!=null?n:y,S;this.params.tuning.useSeparateAudioVideoABR?S=b&&Rb(I,c,(K=this.audioStreamsMap.get(b))!=null?K:[],{throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:p,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}):S=b&&Ys(I,c,(ue=this.audioStreamsMap.get(b))!=null?ue:[]);let T=(tt=this.videoTracksMap.get(I))==null?void 0:tt.representation,E=S&&((ft=this.audioTracksMap.get(S))==null?void 0:ft.representation);if(T&&E)return[T,E];if(T&&!E&&this.audioTracksMap.size===0)return[T,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ul.DOM,thrown:e}))}destroy(){var e;this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),(e=this.textTracksManager)==null||e.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),he(this.video),this.tracer.end()}};var ga=class extends ni{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as bS,interval as _R,map as NR}from"@vkontakte/videoplayer-shared";var Sa=class extends ni{constructor(e){super(e),this.liveOffset=new ot,this.textTracksManager=null}subscribe(){super.subscribe();let{output:e,observableVideo:t,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$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(bS({interval:_R(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var s;if(this.videoState.getState()==="playing"){let n=e.position$.getValue()+(r-1);n<=0&&e.position$.next(n),(s=this.liveOffset)==null||s.resetTo(-n*1e3)}})).add(bS({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(NR(({liveBufferTime:r,liveAvailabilityStartTime:s})=>r&&s?r+s:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(r=>{if(r){let s=Zg(r);this.params.output.availableTextTracks$.next([s])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,r)})}};var SS=Fe(Ps(),1);import{assertNever as va,assertNonNullable as gS,debounce as FR,ErrorCategory as on,filter as UR,isNonNullable as qR,isNullable as HR,map as un,merge as jR,Observable as GR,observableFrom as WR,Subscription as YR,videoSizeToQuality as QR}from"@vkontakte/videoplayer-shared";var Ye={};var Wi=(a,e)=>new GR(t=>{let i=(r,s)=>t.next(s);return a.on(e,i),()=>a.off(e,i)}),ya=class{constructor(e){this.subscription=new YR;this.videoState=new M("initializing");this.textTracksManager=new De;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((i==null?void 0:i.to)!=="paused"&&r.state==="requested"&&this.seek(r.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:va(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:va(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:va(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:va(e)}break;default:va(t)}};this.video=pe(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(Z(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),he(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:on.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,SS.default)(import("hls.js").then(r=>{e||(Ye.Hls=r.default,Ye.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){gS(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(){gS(Ye.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:on.WTF,message:"HlsJsProvider internal logic error",thrown:l})},r=me(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,i));s(r.timeUpdate$,t.position$),s(r.durationChange$,t.duration$),s(r.ended$,t.endedEvent$),s(r.looped$,t.loopedEvent$),s(r.error$,t.error$),s(r.isBuffering$,t.isBuffering$),s(r.currentBuffer$,t.currentBuffer$),s(r.loadStart$,t.firstBytesEvent$),s(r.loadedMetadata$,t.loadedMetadataEvent$),s(r.playing$,t.firstFrameEvent$),s(r.canplay$,t.canplay$),s(r.seeked$,t.seekedEvent$),s(r.inPiP$,t.inPiP$),s(r.inFullscreen$,t.inFullscreen$),this.subscription.add(Je(this.video,e.isLooped,i)),this.subscription.add(fe(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ce(this.video,e.playbackRate,r.playbackRateState$,i)),s(Oe(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(un(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Wi(this.hls,Ye.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:on.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),x(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),x(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),s(Wi(this.hls,Ye.Events.MANIFEST_PARSED).pipe(un(({levels:l})=>l.reduce((c,d)=>{var I,S;let h=d.name||d.height.toString(10),{width:p,height:f}=d,b=(S=wt((I=d.attrs.QUALITY)!=null?I:""))!=null?S:QR({width:p,height:f});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,y={id:h.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:p,height:f},fps:g};return this.trackLevels.set(h,{track:y,level:d}),c.push(y),c},[]))),t.availableVideoTracks$),s(Wi(this.hls,Ye.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let h=d.name,p=d.attrs.URI||"",f=d.lang;c.push({id:h,url:p,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(Wi(this.hls,Ye.Events.LEVEL_LOADING).pipe(un(({url:l})=>Z(l))),t.hostname$),s(Wi(this.hls,Ye.Events.FRAG_CHANGED),l=>{var h,p,f,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((h=c==null?void 0:c.endPTS)!=null?h:0)-((p=c==null?void 0:c.startPTS)!=null?p:0))*1e3),t.currentAudioSegmentLength$.next((((f=d==null?void 0:d.endPTS)!=null?f:0)-((b=d==null?void 0:d.startPTS)!=null?b: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:i}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=Wi(this.hls,Ye.Events.LEVEL_SWITCHED).pipe(un(({level:l})=>n(this.hls.levels[l])));o.pipe(UR(qR)).subscribe(t.currentVideoTrack$,i),this.subscription.add(xt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(HR(l))return;let c=(f=this.trackLevels.get(l.id))==null?void 0:f.level;if(!c)return;let d=this.hls.levels.indexOf(c),h=this.hls.currentLevel,p=this.hls.levels[h];!p||c.bitrate>p.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:i})),s(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=jR(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,WR(["init"])).pipe(FR(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:on.DOM,thrown:t}))||(this.videoState.setState("paused"),x(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"),x(this.params.desiredState.playbackState,"stopped",!0)}};var vS="X-Playback-Duration",cl=async a=>{var r;let e=await lt(a),t=await e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(vS)?parseInt(e.headers.get(vS),10):void 0};import{assertNever as e$,combine as t$,debounce as i$,ErrorCategory as cn,filter as r$,filterChanged as a$,isNonNullable as TS,isNullable as dn,map as IS,merge as s$,observableFrom as n$,Subscription as o$,ValueSubject as hl,VideoQuality as u$}from"@vkontakte/videoplayer-shared";var pl=Fe($o(),1);import{videoSizeToQuality as zR,getExponentialDelay as KR}from"@vkontakte/videoplayer-shared";var JR=a=>{let e=null;if(a.QUALITY&&(e=wt(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=zR({width:t,height:i})}return e!=null?e:null},XR=(a,e)=>{var s,n;let t=a.split(`
|
|
120
|
-
`),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,pl.default)(l[1].split(",").map(I=>I.split("="))),h=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,p=JR(d),f;d.BANDWIDTH&&(f=parseInt(d.BANDWIDTH,10)/1e3||void 0),!f&&d["AVERAGE-BANDWIDTH"]&&(f=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,g;if(d.RESOLUTION){let[I,S]=d.RESOLUTION.split("x").map(T=>parseInt(T,10));I&&S&&(g={width:I,height:S})}let y=new URL(t[++o],e).toString();p&&i.push({id:h,quality:p,url:y,bandwidth:f,size:g,fps:b})}if(c){let d=(0,pl.default)(c[1].split(",").map(b=>b.split("=")).map(([b,g])=>[b,g.replace(/^"|"$/g,"")])),h=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=d.LANGUAGE,f=d.NAME;h&&p&&r.push({type:"internal",id:p,label:f,language:p,url:h,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},ZR=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),dl=0,yS=async(a,e=a,t)=>{let r=await(await lt(a)).text();dl+=1;try{let{qualityManifests:s,textTracks:n}=XR(r,e);return{qualityManifests:s,textTracks:n}}catch(s){if(dl<=t.manifestRetryMaxCount)return await ZR(KR(dl-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),yS(a,e,t)}return{qualityManifests:[],textTracks:[]}},ln=yS;var Ta=class{constructor(e){this.subscription=new o$;this.videoState=new M("stopped");this.textTracksManager=new De;this.manifests$=new hl([]);this.liveOffset=new ot;this.manifestStartTime$=new hl(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?x(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),x(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&(x(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return e$(t)}};var t;this.params=e,this.video=pe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:u$.INVARIANT,url:this.params.source.url},ln(ie(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:i})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:cn.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:cn.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Z(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new hl((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(d=(c=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:cn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=me(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(fe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ce(this.video,t.playbackRate,r.playbackRateState$,i)),s(Oe(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(a$(),IS(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&TS(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(p=>p.id===d);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Z(h.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(t$({startTime:this.manifestStartTime$.pipe(r$(TS)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(IS(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let n=s$(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,n$(["init"])).pipe(i$(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),he(this.video)}prepare(){var o,u;let e=this.selectManifest();if(dn(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:l,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[d,h]of[[l,"mq"],[c,"lq"]]){let p=String(parseFloat(d||""));h&&d&&r.searchParams.set(h,p)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ie(r.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),cl(n).then(l=>{var c;if(!dn(l))this.maxSeekBackTime$.next(l);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if(dn(d)||!isFinite(d))try{lt(n).then(h=>h.text()).then(h=>{var f;let p=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:f[1];if(p){let b=new URL(p,n).toString();cl(b).then(g=>{dn(g)||this.maxSeekBackTime$.next(g)})}})}catch(h){}}})}playIfAllowed(){be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:cn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}};import{assertNever as l$,debounce as c$,ErrorCategory as fl,fromEvent as ml,isNonNullable as d$,isNullable as p$,map as ES,merge as xS,observableFrom as PS,Subscription as h$,ValueSubject as f$,VideoQuality as m$,clientChecker as b$}from"@vkontakte/videoplayer-shared";var Ia=class{constructor(e){this.subscription=new h$;this.videoState=new M("stopped");this.textTracksManager=new De;this.manifests$=new f$([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?x(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return l$(t)}};this.params=e,this.video=pe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:m$.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(Z(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),ln(ie(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:fl.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(d=(c=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:fl.WTF,message:"HlsProvider internal logic error",thrown:o})},r=me(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(ES(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Je(this.video,t.isLooped,i)),this.subscription.add(fe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ce(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var d;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&&d$(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(f=>f.id===h);if(p){this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Z(p.url));let f=this.params.desiredState.playbackRate.getState(),b=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(f!==b){let g=this.params.output.element$.getValue();g&&(this.params.desiredState.playbackRate.setState(f),g.playbackRate=f)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(ES(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!b$.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(xS(ml(o,"addtrack"),ml(o,"removetrack"),ml(o,"change"),PS(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}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(c$(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),he(this.video)}prepare(){var s,n;let e=this.selectManifest();if(p$(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:i)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&r.searchParams.set(c,d)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:fl.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as g$,assertNonNullable as AS,debounce as S$,ErrorCategory as wS,isHigher as v$,isHigherOrEqual as y$,isInvariantQuality as kS,isLowerOrEqual as T$,isNonNullable as I$,merge as E$,observableFrom as x$,Subscription as P$,map as A$}from"@vkontakte/videoplayer-shared";var Ea=class{constructor(e){this.subscription=new P$;this.videoState=new M("stopped");this.trackUrls={};this.textTracksManager=new De;this.syncPlayback=()=>{var u,l,c;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(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:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((c=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:c.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((i==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?x(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return g$(e)}};this.params=e,this.video=pe(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:wS.WTF,message:"MpegProvider internal logic error",thrown:o})},r=me(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(A$(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Je(this.video,t.isLooped,i)),this.subscription.add(fe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ce(this.video,t.playbackRate,r.playbackRateState$,i)),s(Oe(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&I$(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=E$(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,x$(["init"])).pipe(S$(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),he(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;AS(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];AS(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ca(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Z(t))}playIfAllowed(){be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:wS.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var r,s,n,o;let t,i=e;if(e&&((r=this.params.output.currentVideoTrack$.getValue())==null?void 0:r.quality)!==e){let u=(s=Object.values(this.trackUrls).find(d=>!kS(d.track.quality)&&T$(d.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,c=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&c&&y$(c.quality,u.quality)&&(t=u),!t){let d=Object.values(this.trackUrls).filter(p=>!kS(p.track.quality)&&v$(p.track.quality,e)),h=d.length;h&&(t=d[h-1].track)}t&&(i=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(l=>l.track);t=kt(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput: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:i})}};import{assertNever as $S,debounce as $$,merge as LS,observableFrom as L$,Subscription as M$,map as MS,ValueSubject as C$,ErrorCategory as gl,VideoQuality as D$}from"@vkontakte/videoplayer-shared";import{ErrorCategory as w$}from"@vkontakte/videoplayer-shared";var RS=["stun:videostun.mycdn.me:80"],k$=1e3,R$=3,bl=()=>null,pn=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=bl;this.externalStopCallback=bl;this.externalErrorCallback=bl;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:RS}]};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:w$.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),k$)}normalizeOptions(e={}){let t={stunServerList:RS,maxRetryNumber:R$,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var xa=class{constructor(e){this.videoState=new M("stopped");this.maxSeekBackTime$=new C$(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(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"),x(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return $S(e)}};this.subscription=new M$,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=pe(e.container,e.tuning),this.liveStreamClient=new pn(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),he(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:gl.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};LS(this.videoState.stateChangeStarted$.pipe(MS(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(MS(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let r=me(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(r.timeUpdate$,e.liveTime$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(Oe(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(fe(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return $S(n.to)}},i)).add(LS(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,L$(["init"])).pipe($$(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Z(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:D$.INVARIANT}),this.video.srcObject=e,x(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:gl.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:gl.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Pa=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 wa,assertNonNullable as $t,ErrorCategory as fn,filter as _S,isNonNullable as NS,isNullable as U$,map as q$,merge as H$,once as j$,Subject as Te,Subscription as FS,ValueSubject as D,flattenObject as US}from"@vkontakte/videoplayer-shared";import{Observable as B$,map as CS,Subscription as O$,Subject as V$}from"@vkontakte/videoplayer-shared";var DS=a=>new B$(e=>{let t=new O$,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(CS(({from:l,to:c})=>`${l}-${c}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(CS(({type:l})=>l!==void 0)),n=new V$,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as BS,Subscription as _$,combine as N$,filter as OS,once as VS}from"@vkontakte/videoplayer-shared";var Aa=null,hn=null;function Sl(){return Aa||(Aa=new(window.AudioContext||window.webkitAudioContext)),hn||(hn=new GainNode(Aa,{gain:1}),hn.connect(Aa.destination)),{audioCtx:Aa,gainNode:hn}}import{clientChecker as F$}from"@vkontakte/videoplayer-shared";var Yi=class Yi{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.audioContextInit=!1;this.subscriptions=new _$;this.lastAudioContextResumeId=0;this.subscriptions.add(this.provider$.pipe(OS(s=>!!s.type),VS()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){F$.isSafari&&e!=="MPEG"||this.subscriptions.add(N$({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(OS(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),VS()).subscribe(({video:t})=>this.initAudioContextOnce(t)))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){let{volumeMultiplier:t}=this,{audioCtx:i,gainNode:r}=Sl(),s=(Math.random()+1)*999999;this.lastAudioContextResumeId=s,i.resume().then(()=>{var n;if(s!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${Yi.errorId} destroyed`);r.gain.value=t;try{new MediaElementAudioSourceNode(i,{mediaElement:e}).connect(r),this.audioContextInit=!0}catch(o){this.volumeMultiplierError$.next({id:Yi.errorId,category:BS.VIDEO_PIPELINE,message:(n=o==null?void 0:o.message)!=null?n:"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:o})}}).catch(n=>{var o;this.volumeMultiplierError$.next({id:Yi.errorId,category:BS.VIDEO_PIPELINE,message:(o=n==null?void 0:n.message)!=null?o:"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){if(this.audioContextInit){let{gainNode:e}=Sl();e.gain.value=1}this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};Yi.errorId="VolumeMultiplierManager";var Qi=Yi;var G$={chunkDuration:5e3,maxParallelRequests:5},ka=class{constructor(e){this.current$=new D({type:void 0});this.providerError$=new Te;this.noAvailableProvidersError$=new Te;this.volumeMultiplierError$=new Te;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 Te,warning$:new Te,willSeekEvent$:new Te,soundProhibitedEvent$:new Te,seekedEvent$:new Te,loopedEvent$:new Te,endedEvent$:new Te,firstBytesEvent$:new Te,loadedMetadataEvent$:new Te,firstFrameEvent$:new Te,canplay$:new Te,isLive$:new D(void 0),isLowLatency$:new D(!1),canChangePlaybackSpeed$:new D(!0),liveTime$:new D(void 0),liveBufferTime$: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("")};this.subscription=new FS;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=rg([...sg(this.params.tuning),...ag(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(l=>NS(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!r.includes(l)),...t.filter(l=>r.includes(l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",US(s)),this.screenFormatsIterator=new Pa(s);let n=[...Bu(!0),...Bu(!1)];this.chromecastFormatsIterator=new Pa(n.filter(l=>NS(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Qi.isSupported()&&(this.volumeMultiplierManager=new Qi(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(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(U$(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:fn.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}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 wa(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r}=this.params,s=this.providerOutput,n={container:i,source:null,desiredState:r,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 ga({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return $t(o),new Sa({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return $t(o),_i||!this.params.tuning.useHlsJs?new Ia({...n,source:o}):new ya({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return $t(o),new Ta({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return $t(o),new Ea({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return $t(o),new Fb({...n,source:o,config:{...G$,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return $t(o),new xa({container:i,source:o,desiredState:r,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 wa(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return $t(o),new Pr({connection:o,meta:s,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return wa(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return wa(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 wa(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,qS.default)(Object.entries(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new FS,t=!1,i=0;return e.add(H$(this.providerOutput.error$.pipe(_S(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),DS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(q$(r=>({id:`ProviderHangup:${r}`,category:fn.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(_S(({to:s})=>s==="playing"),j$()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let s=this.current$.getValue().destination,n={error:r,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===fn.NETWORK,u=r.category===fn.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c},this.params.tuning.useNewProviderReinitLogic?c?(i++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN"):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):c?(i++,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",US(n))})),e}};import{fromEvent as mn,once as W$,combine as Y$,Subscription as HS,ValueSubject as vl,map as Q$,filter as z$,isNonNullable as bn,now as we,safeStorage as yl}from"@vkontakte/videoplayer-shared";var K$=5e3,jS="one_video_throughput",GS="one_video_rtt",ht=window.navigator.connection,WS=()=>{let a=ht==null?void 0:ht.downlink;if(bn(a)&&a!==10)return a*1e3},YS=()=>{let a=ht==null?void 0:ht.rtt;if(bn(a)&&a!==3e3)return a},QS=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},Tl=class a{constructor(e){this.subscription=new HS;this.concurrentDownloads=new Set;var r,s;this.tuningConfig=e;let t=a.load(jS)||(e.useBrowserEstimation?WS():void 0)||K$,i=(s=(r=a.load(GS))!=null?r:e.useBrowserEstimation?YS():void 0)!=null?s:0;if(this.throughput$=new vl(t),this.rtt$=new vl(i),this.rttAdjustedThroughput$=new vl(QS(t,i,e.rttPenaltyRequestSize)),this.throughput=ii.getSmoothedValue(t,-1,e),this.rtt=ii.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=WS();u&&this.throughput.next(u);let l=YS();bn(l)&&this.rtt.next(l)};ht&&"onchange"in ht&&this.subscription.add(mn(ht,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{yl.set(jS,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{yl.set(GS,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Y$({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(Q$(({throughput:n,rtt:o})=>QS(n,o,e.rttPenaltyRequestSize)),z$(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=we(),r=new HS;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(mn(e,"progress").pipe(W$()).subscribe(s=>{t=s.loaded,i=we()}));break;case 1:case 0:r.add(mn(e,"loadstart").subscribe(()=>{t=0,i=we()}));break}r.add(mn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=we(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=we(),n=0,o=we(),u=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(r,we()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=we();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=d.byteLength,s=we()}else n+=d.byteLength;o=we()}else r+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&we()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,we()-o,this.concurrentDownloads.size),n=0,o=we());await(i==null?void 0:i.read().then(l,u))}};this.concurrentDownloads.add(e),i==null||i.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(a.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=yl.get(e);if(bn(t))return(i=parseInt(t,10))!=null?i:void 0}},zS=Tl;import{fillWithDefault as J$,VideoQuality as KS}from"@vkontakte/videoplayer-shared";var JS={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:1.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:1.2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:1,limitByContainer:!0,containerSizeFactor:1.5,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:3e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:KS.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:KS.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,enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{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:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",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,accumulationBufferStallSizeMs:0,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!0,useNewPartialSegmentFeeding:!0,useNewSwitchTo:!1,useSeparateAudioVideoABR:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,useNewProviderReinitLogic:!0,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},XS=a=>{var e;return{...J$(a,JS),configName:[...(e=a.configName)!=null?e:[],...JS.configName]}};import{assertNonNullable as gn,combine as Lt,ErrorCategory as Sn,filter as oe,filterChanged as _,fromEvent as El,isNonNullable as aL,isNullable as sL,Logger as nL,map as V,mapTo as iv,merge as Mt,now as vn,once as et,Subject as q,Subscription as rv,tap as av,ValueSubject as P,isHigher as oL,isInvariantQuality as sv,flattenObject as Ct,throttle as xl,getTraceSubscriptionMethod as nv,Tracer as uL}from"@vkontakte/videoplayer-shared";import{merge as X$,map as Z$,filter as ZS,isNonNullable as eL}from"@vkontakte/videoplayer-shared";var Il=({seekState:a,position$:e})=>X$(a.stateChangeEnded$.pipe(Z$(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),ZS(eL)),e.pipe(ZS(()=>a.getState().state==="none")));import{assertNonNullable as tL}from"@vkontakte/videoplayer-shared";var ev=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return tL(e,`Wrong container or containerId {${a.container}}`),e};import{filter as iL,once as rL}from"@vkontakte/videoplayer-shared";var tv=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(iL(r=>r.length>0),rL()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(a)};var yn=class{constructor(e={configName:[]},t=uL.createRootTracer(!1)){this.subscription=new rv;this.logger=new nL;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;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),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 P("stopped"),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableVideoStreams$:new P([]),currentVideoStream$:new P(void 0),availableQualities$:new P([]),availableQualitiesFps$:new P({}),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),availableAudioStreams$:new P([]),currentAudioStream$:new P(void 0),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new q,ready$:new q,started$:new q,playing$:new q,paused$:new q,stopped$:new q,willStart$:new q,willResume$:new q,willPause$:new q,willStop$:new q,willDestruct$:new q,watchCoverageRecord$:new q,watchCoverageLive$:new q,managedError$:new q,fatalError$:new q,ended$:new q,looped$:new q,seeked$:new q,willSeek$:new q,autoplaySoundProhibited$:new q,firstBytes$:new q,loadedMetadata$:new q,firstFrame$:new q,canplay$:new q,log$:new q};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:vb};if(this.initLogs(),this.tuning=XS(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ja({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new zS(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,s)=>{let n=Reflect.get(i,r,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(h=>JSON.stringify(h,(p,f)=>{let b=typeof f;return["number","string","boolean"].includes(b)?f:f===null?null:`<${b}>`})),c=`Player.${String(r)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:Sn.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var r,s,n;this.config=e;let{container:t,...i}=e;return this.tracer.log("initVideo",Ct(i)),this.domContainer=ev(e),this.chromecastInitializer.contentId=(r=e.meta)==null?void 0:r.videoId,this.providerContainer=new ka({sources:e.sources,meta:(s=e.meta)!=null?s:{},failoverHosts:(n=e.failoverHosts)!=null?n:[],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.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end()}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&&!Dr()?(this.tracer.log("request play from hidden tab"),El(document,"visibilitychange").pipe(et()).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 i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;return e>=i&&!r&&(s=i-.1),this.tracer.log("seekTime",{duration:i,isLive:r,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){gn(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.providerContainer.providerOutput.availableVideoTracks$.pipe(oe(i=>i.length>0),et()).subscribe(i=>{this.setVideoTrackIdByQuality(i,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",Ct(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var i;gn(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.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",Ct(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return tv(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}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 i=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.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 i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}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(sL(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return aL(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Mt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(V(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(V(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(V(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(V(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(V(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(oe(({from:e})=>e==="stopped"),et()).subscribe(()=>{this.initedAt=vn(),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",Ct(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Sn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(et()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Ct(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(V(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(V(n=>n.destination),_()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(V(n=>n.map(({quality:o})=>o).sort((o,u)=>sv(o)?1:sv(u)?-1:oL(u,o)?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(_()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(_((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(_((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(_()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(_()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(_()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(V(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(Lt({hasLiveOffsetByPaused:Mt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(V(n=>n.to),_(),V(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(Lt({atLiveEdge:Lt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Il({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(V(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),_(),av(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(V(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Lt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(V(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),_(),av(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(V(n=>n.muted),_()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(V(n=>n.volume),_()).subscribe(this.info.volume$)).add(Il({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Mt(e.providerOutput.endedEvent$.pipe(iv(!0)),e.providerOutput.seekedEvent$.pipe(iv(!1))).pipe(_()).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(V(n=>({id:n?`No${n}`:"NoProviders",category:Sn.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.firstBytesEvent$.pipe(et(),V(n=>n!=null?n:vn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(et(),V(()=>vn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(et(),V(()=>vn()-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 P(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new P(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(oe(({to:n})=>n==="playing"),et()).subscribe(()=>i.next(!1)));let r=0,s=Mt(e.providerOutput.isBuffering$,t,i).pipe(V(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),_());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(Mt(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Mt(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(V(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new rv;this.subscription.add(t),this.subscription.add(e.current$.pipe(_((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(oe(i=>i.length>0),et()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t,i=(r=this.desiredState.videoTrack.getState())==null?void 0:r.quality;i&&(t=e.find(({quality:s})=>s===i),t||this.setAutoQuality(!0)),t||(t=kt(e,{container:this.domContainer.getBoundingClientRect(),throughput: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(Mt(this.desiredState.videoTrack.stateChangeStarted$.pipe(V(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(V(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(V(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(V(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(V(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(V(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(V(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(V(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(V(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;gn(this.providerContainer),gn(e),Sb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>gb(i)),this.providerContainer.current$.subscribe(({type:i})=>kr("provider",i)),e.duration$.subscribe(i=>kr("duration",i)),e.availableVideoTracks$.pipe(oe(i=>!!i.length),et()).subscribe(i=>kr("tracks",i)),this.events.fatalError$.subscribe(new ne("fatalError")),this.events.managedError$.subscribe(new ne("managedError")),e.position$.subscribe(new ne("position")),e.currentVideoTrack$.pipe(V(i=>i==null?void 0:i.quality)).subscribe(new ne("quality")),this.info.currentBuffer$.subscribe(new ne("buffer")),e.isBuffering$.subscribe(new ne("isBuffering"))].forEach(i=>this.subscription.add(i)),kr("codecs",ig())}initTracerSubscription(){let e=nv(this.tracer.log.bind(this.tracer)),t=nv(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(_()).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(Lt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(oe(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),_((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(oe(i=>i>0),_()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(oe(i=>i>0),_()).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(Lt({currentBuffer:this.info.currentBuffer$.pipe(oe(i=>i.end>0),_((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(_())}).pipe(xl(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(_()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(_()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(_()).subscribe(e("canChangePlaybackSpeed"))).add(Lt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(oe(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),xl(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(_(),oe(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(_(),oe(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(_()).subscribe(e("muted"))).add(this.info.volume$.pipe(_()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(_(),oe(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Lt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(oe(({throughputEstimation:i,rtt:r})=>!!i&&!!r),xl(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(_(),oe(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Sn.DOM,message:String(r)})})};this.subscription.add(Mt(El(document,"visibilitychange"),El(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",Ct({quality:t,availableTracks:Ct(e),track:Ct(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as cW,Observable as dW,Subject as pW,ValueSubject as hW,VideoQuality as fW}from"@vkontakte/videoplayer-shared";var mW=`@vkontakte/videoplayer-core@${sc}`;export{qa as ChromecastState,An as HttpConnectionType,dW as Observable,ce as PlaybackState,yn as Player,mW as SDK_VERSION,pW as Subject,cW as Subscription,wn as Surface,sc as VERSION,hW as ValueSubject,It as VideoFormat,fW as VideoQuality};
|
|
119
|
+
`;var tn=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 Zs(this.params.fov,this.params.orientation),this.cameraRotationManager=new en(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(cS,this.gl.VERTEX_SHADER),r=this.createShader(dS,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,c=t+i,d=e-r,h=t+i;return[s,n,o,u,l,c,d,h]}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}};var nr=class{constructor(e){this.subscription=new OR;this.videoState=new L("stopped");this.elementSize$=new VR(void 0);this.textTracksManager=new De;this.droppedFramesManager=new Ls;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=()=>{var n,o,u;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==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let l=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(i.position-l,i.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),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"),x(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"),x(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&x(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&x(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==null?void 0:r.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return RR(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new tn(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((i=e.projectionData)==null?void 0:i.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=pe(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(X(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 Xs({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=me(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:nl.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(){var l;let{output:e,desiredState:t,observableVideo:r,genericErrorListener:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(pS(c=>!!c.length),fS()).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})})),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(pS(CR),fS()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(hS(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(Je(this.video,t.isLooped,i)),this.subscription.add(fe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ce(this.video,t.playbackRate,r.playbackRateState$,i)),s(BR(this.video),this.elementSize$),s(Oe(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),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($R(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let f of d.audio){p.push(Yu(f));let b=[];for(let g of f.representations){let v=zg(g);b.push(v),this.audioTracksMap.set(v,{stream:f,representation:g})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(p)}let h=[];for(let p of d.video){h.push(zu(p));let f=[];for(let b of p.representations){let g=Yg(b);g&&(f.push(g),this.videoTracksMap.set(g,{stream:p,representation:b}))}this.videoStreamsMap.set(p,f)}if(this.params.output.availableVideoStreams$.next(h),this.textTracksManager)for(let p of d.text)for(let f of p.representations){let b=Kg(p,f);this.textTracksMap.set(b,{stream:p,representation:f})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),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())},i));let n=c=>e.error$.next({id:"RepresentationSwitch",category:nl.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(rn(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.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,MR(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[p,f]=h,b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),c==="manifest_ready")this.player.initRepresentations(p.id,f==null?void 0:f.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(n),f){let g=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",f.id,g).catch(n)}},i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSize$.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(ol()).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[h,{stream:p}]=d,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===p.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(zu(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(ol()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:p}]=d,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===p.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(Yu(p))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var d,h;if(c!=null&&c.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(h=this.params.tuning.spherical)!=null&&h.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)),(l=this.textTracksManager)==null||l.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(hS(({to:c})=>c==="ready"),ol());this.subscription.add(rn(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(rn(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=rn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,DR(["init"])).pipe(LR(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var k,C,q,R,D,B,w,A,U,z,y,$,j;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(k=e.videoTrack.getState())==null?void 0:k.id,n=[...this.videoTracksMap.keys()].find(({id:O})=>O===i),o=t.currentVideoTrack$.getValue(),u=((R=(q=e.videoStream.getState())!=null?q:n&&((C=this.videoTracksMap.get(n))==null?void 0:C.stream))!=null?R:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:O})=>O===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=Ze(this.video.buffered,this.video.currentTime*1e3),h=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,p=Math.min(d/Math.min(h,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),f=(D=e.audioStream.getState())!=null?D:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=(B=[...this.audioStreamsMap.keys()].find(({id:O})=>O===(f==null?void 0:f.id)))!=null?B:this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r){let O=ws(n,c,(w=this.audioStreamsMap.get(b))!=null?w:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(A=O==null?void 0:O.bitrate)!=null?A:-1/0)}if(o){let O=ws(o,c,(U=this.audioStreamsMap.get(b))!=null?U:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(z=O==null?void 0:O.bitrate)!=null?z:-1/0)}}let v=Pt(c,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:g,forwardBufferHealth:p,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),T=r?v!=null?v:n:n!=null?n:v,S=b&&Ab(T,c,(y=this.audioStreamsMap.get(b))!=null?y:[],{throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:p,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),E=($=this.videoTracksMap.get(T))==null?void 0:$.representation,I=S&&((j=this.audioTracksMap.get(S))==null?void 0:j.representation);if(E&&I)return[E,I];if(E&&!I&&this.audioTracksMap.size===0)return[E,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:nl.DOM,thrown:e}))}destroy(){var e;this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),(e=this.textTracksManager)==null||e.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),he(this.video),this.tracer.end()}};var ba=class extends nr{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 _R,map as NR}from"@vkontakte/videoplayer-shared";var ga=class extends nr{constructor(e){super(e),this.liveOffset=new nt,this.textTracksManager=null}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(mS({interval:_R(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:i})=>{var s;if(this.videoState.getState()==="playing"){let n=e.position$.getValue()+(i-1);n<=0&&e.position$.next(n),(s=this.liveOffset)==null||s.resetTo(-n*1e3)}})).add(mS({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(NR(({liveBufferTime:i,liveAvailabilityStartTime:s})=>i&&s?i+s:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(i=>{if(i){let s=Jg(i);this.params.output.availableTextTracks$.next([s])}}))}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(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,i)})}};var gS=Ue(xs(),1);import{assertNever as Sa,assertNonNullable as bS,debounce as FR,ErrorCategory as an,filter as UR,isNonNullable as qR,isNullable as HR,map as sn,merge as jR,Observable as GR,observableFrom as WR,Subscription as QR,videoSizeToQuality as YR}from"@vkontakte/videoplayer-shared";var Qe={};var jr=(a,e)=>new GR(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),va=class{constructor(e){this.subscription=new QR;this.videoState=new L("initializing");this.textTracksManager=new De;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==null?void 0: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:Sa(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Sa(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Sa(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Sa(e)}break;default:Sa(t)}};this.video=pe(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(X(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),he(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:an.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||(Qe.Hls=i.default,Qe.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){bS(Qe.Hls,"hls.js not loaded"),this.hls=new Qe.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){bS(Qe.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:an.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=me(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,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(Je(this.video,e.isLooped,r)),this.subscription.add(fe(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ce(this.video,e.playbackRate,i.playbackRateState$,r)),s(Oe(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(sn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(jr(this.hls,Qe.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:an.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(e.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(jr(this.hls,Qe.Events.MANIFEST_PARSED).pipe(sn(({levels:l})=>l.reduce((c,d)=>{var T,S;let h=d.name||d.height.toString(10),{width:p,height:f}=d,b=(S=xt((T=d.attrs.QUALITY)!=null?T:""))!=null?S:YR({width:p,height:f});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,v={id:h.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:p,height:f},fps:g};return this.trackLevels.set(h,{track:v,level:d}),c.push(v),c},[]))),t.availableVideoTracks$),s(jr(this.hls,Qe.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let h=d.name,p=d.attrs.URI||"",f=d.lang;c.push({id:h,url:p,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(jr(this.hls,Qe.Events.LEVEL_LOADING).pipe(sn(({url:l})=>X(l))),t.hostname$),s(jr(this.hls,Qe.Events.FRAG_CHANGED),l=>{var h,p,f,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((h=c==null?void 0:c.endPTS)!=null?h:0)-((p=c==null?void 0:c.startPTS)!=null?p:0))*1e3),t.currentAudioSegmentLength$.next((((f=d==null?void 0:d.endPTS)!=null?f:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(Tt(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=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=jr(this.hls,Qe.Events.LEVEL_SWITCHED).pipe(sn(({level:l})=>n(this.hls.levels[l])));o.pipe(UR(qR)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Tt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(HR(l))return;let c=(f=this.trackLevels.get(l.id))==null?void 0:f.level;if(!c)return;let d=this.hls.levels.indexOf(c),h=this.hls.currentLevel,p=this.hls.levels[h];!p||c.bitrate>p.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{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=jR(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,WR(["init"])).pipe(FR(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 be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:an.DOM,thrown:t}))||(this.videoState.setState("paused"),x(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"),x(this.params.desiredState.playbackState,"stopped",!0)}};var SS="X-Playback-Duration",ul=async a=>{var i;let e=await ut(a),t=await e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(SS)?parseInt(e.headers.get(SS),10):void 0};import{assertNever as e$,combine as t$,debounce as r$,ErrorCategory as on,filter as i$,filterChanged as a$,isNonNullable as yS,isNullable as un,map as TS,merge as s$,observableFrom as n$,Subscription as o$,ValueSubject as dl,VideoQuality as u$}from"@vkontakte/videoplayer-shared";var cl=Ue(Ao(),1);import{videoSizeToQuality as zR,getExponentialDelay as KR}from"@vkontakte/videoplayer-shared";var JR=a=>{let e=null;if(a.QUALITY&&(e=xt(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=zR({width:t,height:r})}return e!=null?e:null},XR=(a,e)=>{var s,n;let t=a.split(`
|
|
120
|
+
`),r=[],i=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,cl.default)(l[1].split(",").map(T=>T.split("="))),h=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,p=JR(d),f;d.BANDWIDTH&&(f=parseInt(d.BANDWIDTH,10)/1e3||void 0),!f&&d["AVERAGE-BANDWIDTH"]&&(f=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,g;if(d.RESOLUTION){let[T,S]=d.RESOLUTION.split("x").map(E=>parseInt(E,10));T&&S&&(g={width:T,height:S})}let v=new URL(t[++o],e).toString();p&&r.push({id:h,quality:p,url:v,bandwidth:f,size:g,fps:b})}if(c){let d=(0,cl.default)(c[1].split(",").map(b=>b.split("=")).map(([b,g])=>[b,g.replace(/^"|"$/g,"")])),h=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=d.LANGUAGE,f=d.NAME;h&&p&&i.push({type:"internal",id:p,label:f,language:p,url:h,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},ZR=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),ll=0,vS=async(a,e=a,t)=>{let i=await(await ut(a)).text();ll+=1;try{let{qualityManifests:s,textTracks:n}=XR(i,e);return{qualityManifests:s,textTracks:n}}catch(s){if(ll<=t.manifestRetryMaxCount)return await ZR(KR(ll-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),vS(a,e,t)}return{qualityManifests:[],textTracks:[]}},nn=vS;var ya=class{constructor(e){this.subscription=new o$;this.videoState=new L("stopped");this.textTracksManager=new De;this.manifests$=new dl([]);this.liveOffset=new nt;this.manifestStartTime$=new dl(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"),x(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((i==null?void 0:i.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?x(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),x(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==null?void 0:i.to)==="playing"&&x(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(i==null?void 0:i.to)==="paused"&&(x(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return e$(t)}};var t;this.params=e,this.video=pe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:u$.INVARIANT,url:this.params.source.url},nn(re(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:r})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:on.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:on.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(X(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new dl((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:on.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=me(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(fe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ce(this.video,t.playbackRate,i.playbackRateState$,r)),s(Oe(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(a$(),TS(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(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&yS(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(p=>p.id===d);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(X(h.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(i.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(t$({startTime:this.manifestStartTime$.pipe(i$(yS)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(TS(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=s$(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,n$(["init"])).pipe(r$(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),he(this.video)}prepare(){var o,u;let e=this.selectManifest();if(un(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:l,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[d,h]of[[l,"mq"],[c,"lq"]]){let p=String(parseFloat(d||""));h&&d&&i.searchParams.set(h,p)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=re(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),ul(n).then(l=>{var c;if(!un(l))this.maxSeekBackTime$.next(l);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if(un(d)||!isFinite(d))try{ut(n).then(h=>h.text()).then(h=>{var f;let p=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:f[1];if(p){let b=new URL(p,n).toString();ul(b).then(g=>{un(g)||this.maxSeekBackTime$.next(g)})}})}catch(h){}}})}playIfAllowed(){be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:on.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()}};import{assertNever as l$,debounce as c$,ErrorCategory as pl,fromEvent as hl,isNonNullable as d$,isNullable as p$,map as IS,merge as ES,observableFrom as xS,Subscription as h$,ValueSubject as f$,VideoQuality as m$,clientChecker as b$}from"@vkontakte/videoplayer-shared";var Ta=class{constructor(e){this.subscription=new h$;this.videoState=new L("stopped");this.textTracksManager=new De;this.manifests$=new f$([]);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"),x(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((i==null?void 0:i.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?x(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),x(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==null?void 0:i.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return l$(t)}};this.params=e,this.video=pe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:m$.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(X(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),nn(re(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(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(h=>h.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=me(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(IS(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Je(this.video,t.isLooped,r)),this.subscription.add(fe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ce(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(i.loadedMetadata$.subscribe(()=>{var d;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&&d$(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(f=>f.id===h);if(p){this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(X(p.url));let f=this.params.desiredState.playbackRate.getState(),b=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(f!==b){let g=this.params.output.element$.getValue();g&&(this.params.desiredState.playbackRate.setState(f),g.playbackRate=f)}}}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(IS(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!b$.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(ES(hl(o,"addtrack"),hl(o,"removetrack"),hl(o,"change"),xS(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=ES(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,xS(["init"])).pipe(c$(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),he(this.video)}prepare(){var s,n;let e=this.selectManifest();if(p$(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}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(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}};import{assertNever as g$,assertNonNullable as PS,debounce as S$,ErrorCategory as AS,isHigher as v$,isHigherOrEqual as y$,isInvariantQuality as wS,isLowerOrEqual as T$,isNonNullable as I$,merge as E$,observableFrom as x$,Subscription as P$,map as A$}from"@vkontakte/videoplayer-shared";var Ia=class{constructor(e){this.subscription=new P$;this.videoState=new L("stopped");this.trackUrls={};this.textTracksManager=new De;this.syncPlayback=()=>{var u,l,c;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"),x(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:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((c=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:c.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?x(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),x(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==null?void 0:r.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return g$(e)}};this.params=e,this.video=pe(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(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(Object.values(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:AS.WTF,message:"MpegProvider internal logic error",thrown:o})},i=me(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(A$(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Je(this.video,t.isLooped,r)),this.subscription.add(fe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ce(this.video,t.playbackRate,i.playbackRateState$,r)),s(Oe(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&I$(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=E$(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,x$(["init"])).pipe(S$(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),he(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;PS(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];PS(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=la(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(X(t))}playIfAllowed(){be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:AS.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var i,s,n,o;let t,r=e;if(e&&((i=this.params.output.currentVideoTrack$.getValue())==null?void 0:i.quality)!==e){let u=(s=Object.values(this.trackUrls).find(d=>!wS(d.track.quality)&&T$(d.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,c=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&c&&y$(c.quality,u.quality)&&(t=u),!t){let d=Object.values(this.trackUrls).filter(p=>!wS(p.track.quality)&&v$(p.track.quality,e)),h=d.length;h&&(t=d[h-1].track)}t&&(r=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(l=>l.track);t=Pt(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput: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 RS,debounce as $$,merge as $S,observableFrom as L$,Subscription as M$,map as LS,ValueSubject as C$,ErrorCategory as ml,VideoQuality as D$}from"@vkontakte/videoplayer-shared";import{ErrorCategory as w$}from"@vkontakte/videoplayer-shared";var kS=["stun:videostun.mycdn.me:80"],k$=1e3,R$=3,fl=()=>null,ln=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=fl;this.externalStopCallback=fl;this.externalErrorCallback=fl;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:kS}]};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:w$.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(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),k$)}normalizeOptions(e={}){let t={stunServerList:kS,maxRetryNumber:R$,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ea=class{constructor(e){this.videoState=new L("stopped");this.maxSeekBackTime$=new C$(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"),x(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"),x(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==null?void 0:r.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return RS(e)}};this.subscription=new M$,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=pe(e.container,e.tuning),this.liveStreamClient=new ln(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),he(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:ml.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};$S(this.videoState.stateChangeStarted$.pipe(LS(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(LS(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=me(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(Oe(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(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.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(fe(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 RS(n.to)}},r)).add($S(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,L$(["init"])).pipe($$(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(X(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:D$.INVARIANT}),this.video.srcObject=e,x(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:ml.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ml.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var xa=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 Aa,assertNonNullable as Lt,ErrorCategory as cn,filter as VS,isNonNullable as _S,isNullable as q$,map as H$,merge as j$,once as G$,Subject as ve,Subscription as NS,ValueSubject as M,flattenObject as FS}from"@vkontakte/videoplayer-shared";import{Observable as B$,map as MS,Subscription as O$,Subject as V$}from"@vkontakte/videoplayer-shared";var CS=a=>new B$(e=>{let t=new O$,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(MS(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(MS(({type:l})=>l!==void 0)),n=new V$,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 _$,Subscription as N$,combine as F$,filter as BS,once as OS}from"@vkontakte/videoplayer-shared";function DS(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as U$}from"@vkontakte/videoplayer-shared";var Pa=class Pa{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new xe;this.subscriptions=new N$;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(BS(s=>!!s.type),OS()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){U$.isSafari&&e!=="MPEG"||this.subscriptions.add(F$({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(BS(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),OS()).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=DS();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){var t;this.volumeMultiplierError$.next({id:Pa.errorId,category:_$.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Pa.errorId} exception`,thrown:e})}};Pa.errorId="VolumeMultiplierManager";var Gr=Pa;var W$={chunkDuration:5e3,maxParallelRequests:5},wa=class{constructor(e){this.current$=new M({type:void 0});this.providerError$=new ve;this.noAvailableProvidersError$=new ve;this.volumeMultiplierError$=new ve;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 ve,warning$:new ve,willSeekEvent$:new ve,soundProhibitedEvent$:new ve,seekedEvent$:new ve,loopedEvent$:new ve,endedEvent$:new ve,firstBytesEvent$:new ve,loadedMetadataEvent$:new ve,firstFrameEvent$:new ve,canplay$:new ve,isLive$:new M(void 0),isLowLatency$:new M(!1),canChangePlaybackSpeed$:new M(!0),liveTime$:new M(void 0),liveBufferTime$: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("")};this.subscription=new NS;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=eg([...rg(this.params.tuning),...tg(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(l=>_S(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!i.includes(l)),...t.filter(l=>i.includes(l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",FS(s)),this.screenFormatsIterator=new xa(s);let n=[...Lu(!0),...Lu(!1)];this.chromecastFormatsIterator=new xa(n.filter(l=>_S(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Gr.isSupported()&&(this.volumeMultiplierManager=new Gr(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(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(q$(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:cn.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 Aa(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 Lt(o),new ba({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Lt(o),new ga({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Lt(o),Nr||!this.params.tuning.useHlsJs?new Ta({...n,source:o}):new va({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Lt(o),new ya({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Lt(o),new Ia({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Lt(o),new Vb({...n,source:o,config:{...W$,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Lt(o),new Ea({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 Aa(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 Lt(o),new Ei({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 Aa(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Aa(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 Aa(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,US.default)(Object.entries(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new NS,t=!1,r=0;return e.add(j$(this.providerOutput.error$.pipe(VS(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),CS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(H$(i=>({id:`ProviderHangup:${i}`,category:cn.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(VS(({to:s})=>s==="playing"),G$()).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===cn.NETWORK,u=i.category===cn.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!=null?s:"SCREEN")}this.tracer.error("providerError",FS(n))})),e}};import{fromEvent as dn,once as Q$,combine as Y$,Subscription as qS,ValueSubject as bl,map as z$,filter as K$,isNonNullable as pn,now as we,safeStorage as gl}from"@vkontakte/videoplayer-shared";var J$=5e3,HS="one_video_throughput",jS="one_video_rtt",dt=window.navigator.connection,GS=()=>{let a=dt==null?void 0:dt.downlink;if(pn(a)&&a!==10)return a*1e3},WS=()=>{let a=dt==null?void 0:dt.rtt;if(pn(a)&&a!==3e3)return a},QS=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},Sl=class a{constructor(e){this.subscription=new qS;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(HS)||(e.useBrowserEstimation?GS():void 0)||J$,r=(s=(i=a.load(jS))!=null?i:e.useBrowserEstimation?WS():void 0)!=null?s:0;if(this.throughput$=new bl(t),this.rtt$=new bl(r),this.rttAdjustedThroughput$=new bl(QS(t,r,e.rttPenaltyRequestSize)),this.throughput=rr.getSmoothedValue(t,-1,e),this.rtt=rr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=GS();u&&this.throughput.next(u);let l=WS();pn(l)&&this.rtt.next(l)};dt&&"onchange"in dt&&this.subscription.add(dn(dt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{gl.set(HS,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{gl.set(jS,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Y$({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(z$(({throughput:n,rtt:o})=>QS(n,o,e.rttPenaltyRequestSize)),K$(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=we(),i=new qS;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(dn(e,"progress").pipe(Q$()).subscribe(s=>{t=s.loaded,r=we()}));break;case 1:case 0:i.add(dn(e,"loadstart").subscribe(()=>{t=0,r=we()}));break}i.add(dn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=we(),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=we(),n=0,o=we(),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(i,we()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=we();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=d.byteLength,s=we()}else n+=d.byteLength;o=we()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&we()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,we()-o,this.concurrentDownloads.size),n=0,o=we());await(r==null?void 0:r.read().then(l,u))}};this.concurrentDownloads.add(e),r==null||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){var r;let t=gl.get(e);if(pn(t))return(r=parseInt(t,10))!=null?r:void 0}},YS=Sl;import{fillWithDefault as X$,VideoQuality as zS}from"@vkontakte/videoplayer-shared";var KS={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:1.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:1.2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:1,limitByContainer:!0,containerSizeFactor:1.5,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:3e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:zS.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:zS.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,accumulationBufferStallSize:{shortVideoDuration:2*6e4,shortVideoBufferStallSizeMs:0,longVideoBufferStallSizeMs:0},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{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:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",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:!1,useNewPruneBufferStrategy:!1,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1},JS=a=>{var e;return{...X$(a,KS),configName:[...(e=a.configName)!=null?e:[],...KS.configName]}};import{assertNonNullable as hn,combine as Mt,ErrorCategory as fn,filter as ue,filterChanged as _,fromEvent as yl,isNonNullable as sL,isNullable as nL,Logger as oL,map as V,mapTo as tv,merge as Ct,now as mn,once as et,Subject as H,Subscription as rv,tap as iv,ValueSubject as P,isHigher as uL,isInvariantQuality as av,flattenObject as Dt,throttle as Tl,getTraceSubscriptionMethod as sv,Tracer as lL}from"@vkontakte/videoplayer-shared";import{merge as Z$,map as eL,filter as XS,isNonNullable as tL}from"@vkontakte/videoplayer-shared";var vl=({seekState:a,position$:e})=>Z$(a.stateChangeEnded$.pipe(eL(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),XS(tL)),e.pipe(XS(()=>a.getState().state==="none")));import{assertNonNullable as rL}from"@vkontakte/videoplayer-shared";var ZS=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return rL(e,`Wrong container or containerId {${a.container}}`),e};import{filter as iL,once as aL}from"@vkontakte/videoplayer-shared";var ev=(a,e,t,r)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(iL(i=>i.length>0),aL()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var bn=class{constructor(e={configName:[]},t=lL.createRootTracer(!1)){this.subscription=new rv;this.logger=new oL;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new L("stopped"),seekState:new L({state:"none"}),volume:new L({volume:1,muted:!1}),videoTrack:new L(void 0),videoStream:new L(void 0),audioStream:new L(void 0),autoVideoTrackSwitching:new L(!0),autoVideoTrackLimits:new L({}),isLooped:new L(!1),playbackRate:new L(1),externalTextTracks:new L([]),internalTextTracks:new L([]),currentTextTrack:new L(void 0),textTrackCuesSettings:new L({}),cameraOrientation:new L({x:0,y:0})};this.info={playbackState$:new P("stopped"),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableVideoStreams$:new P([]),currentVideoStream$:new P(void 0),availableQualities$:new P([]),availableQualitiesFps$:new P({}),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),availableAudioStreams$:new P([]),currentAudioStream$:new P(void 0),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new H,ready$:new H,started$:new H,playing$:new H,paused$:new H,stopped$:new H,willStart$:new H,willResume$:new H,willPause$:new H,willStop$:new H,willDestruct$:new H,watchCoverageRecord$:new H,watchCoverageLive$:new H,managedError$:new H,fatalError$:new H,ended$:new H,looped$:new H,seeked$:new H,willSeek$:new H,autoplaySoundProhibited$:new H,firstBytes$:new H,loadedMetadata$:new H,firstFrame$:new H,canplay$:new H,log$:new H};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:bb};if(this.initLogs(),this.tuning=JS(e),this.tracer=t,e.initialPlaybackRate&&this.info.currentPlaybackRate$.next(e.initialPlaybackRate),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ha({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new YS(this.tuning.throughputEstimator),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(h=>JSON.stringify(h,(p,f)=>{let b=typeof f;return["number","string","boolean"].includes(b)?f:f===null?null:`<${b}>`})),c=`Player.${String(i)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:fn.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var i,s,n;this.config=e;let{container:t,...r}=e;return this.tracer.log("initVideo",Dt(r)),this.domContainer=ZS(e),this.chromecastInitializer.contentId=(i=e.meta)==null?void 0:i.videoId,this.providerContainer=new wa({sources:e.sources,meta:(s=e.meta)!=null?s:{},failoverHosts:(n=e.failoverHosts)!=null?n:[],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.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end()}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"),yl(document,"visibilitychange").pipe(et()).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-.1),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){hn(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(ue(r=>r.length>0),et()).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",Dt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;hn(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.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",Dt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return ev(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}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(nL(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return sL(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,r;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((r=e==null?void 0:e.provider)!=null&&r.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(Ct(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(V(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(V(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(V(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(V(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(V(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(ue(({from:e})=>e==="stopped"),et()).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",Dt(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:fn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(et()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Dt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(V(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(V(n=>n.destination),_()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(V(n=>n.map(({quality:o})=>o).sort((o,u)=>av(o)?1:av(u)?-1:uL(u,o)?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(_()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(_((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(_((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(_()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(_()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(_()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(V(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(Mt({hasLiveOffsetByPaused:Ct(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(V(n=>n.to),_(),V(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(Mt({atLiveEdge:Mt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:vl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(V(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),_(),iv(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(V(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Mt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(V(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),_(),iv(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(V(n=>n.muted),_()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(V(n=>n.volume),_()).subscribe(this.info.volume$)).add(vl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Ct(e.providerOutput.endedEvent$.pipe(tv(!0)),e.providerOutput.seekedEvent$.pipe(tv(!1))).pipe(_()).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(V(n=>({id:n?`No${n}`:"NoProviders",category:fn.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.firstBytesEvent$.pipe(et(),V(n=>n!=null?n:mn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(et(),V(()=>mn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(et(),V(()=>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 P(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new P(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(ue(({to:n})=>n==="playing"),et()).subscribe(()=>r.next(!1)));let i=0,s=Ct(e.providerOutput.isBuffering$,t,r).pipe(V(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),_());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(Ct(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Ct(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(V(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new rv;this.subscription.add(t),this.subscription.add(e.current$.pipe(_((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ue(r=>r.length>0),et()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i,s;let t;this.wasSetStartedQuality=!0;let r=(s=this.explicitInitialQuality)!=null?s:(i=this.desiredState.videoTrack.getState())==null?void 0:i.quality;r&&(t=e.find(({quality:n})=>n===r),t||this.setAutoQuality(!0)),t||(t=Pt(e,{container:this.domContainer.getBoundingClientRect(),throughput: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(Ct(this.desiredState.videoTrack.stateChangeStarted$.pipe(V(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(V(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(V(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(V(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(V(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(V(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(V(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(V(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(V(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;hn(this.providerContainer),hn(e),mb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>fb(r)),this.providerContainer.current$.subscribe(({type:r})=>Ai("provider",r)),e.duration$.subscribe(r=>Ai("duration",r)),e.availableVideoTracks$.pipe(ue(r=>!!r.length),et()).subscribe(r=>Ai("tracks",r)),this.events.fatalError$.subscribe(new oe("fatalError")),this.events.managedError$.subscribe(new oe("managedError")),e.position$.subscribe(new oe("position")),e.currentVideoTrack$.pipe(V(r=>r==null?void 0:r.quality)).subscribe(new oe("quality")),this.info.currentBuffer$.subscribe(new oe("buffer")),e.isBuffering$.subscribe(new oe("isBuffering"))].forEach(r=>this.subscription.add(r)),Ai("codecs",Zb())}initTracerSubscription(){let e=sv(this.tracer.log.bind(this.tracer)),t=sv(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(_()).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(Mt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(ue(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),_((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(ue(r=>r>0),_()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(ue(r=>r>0),_()).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(Mt({currentBuffer:this.info.currentBuffer$.pipe(ue(r=>r.end>0),_((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(_())}).pipe(Tl(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(_()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(_()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(_()).subscribe(e("canChangePlaybackSpeed"))).add(Mt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(ue(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),Tl(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(_(),ue(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(_(),ue(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(_()).subscribe(e("muted"))).add(this.info.volume$.pipe(_()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(_(),ue(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Mt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(ue(({throughputEstimation:r,rtt:i})=>!!r&&!!i),Tl(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(_(),ue(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==null||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:fn.DOM,message:String(i)})})};this.subscription.add(Ct(yl(document,"visibilitychange"),yl(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&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",Dt({quality:t,availableTracks:Dt(e),track:Dt(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 gW,Observable as SW,Subject as vW,ValueSubject as yW,VideoQuality as TW}from"@vkontakte/videoplayer-shared";var IW=`@vkontakte/videoplayer-core@${rc}`;export{Ua as ChromecastState,In as HttpConnectionType,SW as Observable,ce as PlaybackState,bn as Player,IW as SDK_VERSION,vW as Subject,gW as Subscription,En as Surface,rc as VERSION,yW as ValueSubject,vt as VideoFormat,TW as VideoQuality};
|