@vkontakte/videoplayer-core 2.0.115-dev.c6f77ae4.0 → 2.0.116-dev.48c29cc5.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 +18 -18
- package/es2015.esm.js +18 -18
- package/es2018.cjs.js +19 -19
- package/es2018.esm.js +19 -19
- package/esnext.cjs.js +19 -19
- package/esnext.esm.js +19 -19
- package/evergreen.esm.js +19 -19
- package/package.json +2 -2
- package/types/player/Player.d.ts +1 -1
- package/types/player/types.d.ts +1 -1
- package/types/providers/DashProvider/lib/buffer.d.ts +3 -0
- package/types/providers/DashProvider/lib/types.d.ts +1 -0
- package/types/utils/tuningConfig.d.ts +3 -0
package/es2018.esm.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.116-dev.48c29cc5.0
|
|
3
|
+
* Tue, 29 Oct 2024 05:59:16 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-116/doc/
|
|
5
5
|
*/
|
|
6
|
-
var Sv=Object.create;var sc=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&&sc(a,r,{get:()=>e[r],enumerable:!(i=vv(e,r))||i.enumerable});return a};var ze=(a,e,t)=>(t=a!=null?Sv(Tv(a)):{},Ev(e||!a||!a.__esModule?sc(t,"default",{value:a,enumerable:!0}):t,a));var Ee=m((xL,hc)=>{"use strict";hc.exports=function(a){try{return!!a()}catch(e){return!0}}});var er=m((PL,fc)=>{"use strict";var Lv=Ee();fc.exports=!Lv(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var de=m((AL,gc)=>{"use strict";var mc=er(),bc=Function.prototype,Rn=bc.call,Mv=mc&&bc.bind.bind(Rn,Rn);gc.exports=mc?Mv:function(a){return function(){return Rn.apply(a,arguments)}}});var pi=m((wL,vc)=>{"use strict";var Sc=de(),Cv=Sc({}.toString),Dv=Sc("".slice);vc.exports=function(a){return Dv(Cv(a),8,-1)}});var Tc=m((kL,yc)=>{"use strict";var Bv=de(),Ov=Ee(),Vv=pi(),$n=Object,_v=Bv("".split);yc.exports=Ov(function(){return!$n("z").propertyIsEnumerable(0)})?function(a){return Vv(a)==="String"?_v(a,""):$n(a)}:$n});var hi=m((RL,Ic)=>{"use strict";Ic.exports=function(a){return a==null}});var tr=m(($L,Ec)=>{"use strict";var Nv=hi(),Fv=TypeError;Ec.exports=function(a){if(Nv(a))throw new Fv("Can't call method on "+a);return a}});var fi=m((LL,xc)=>{"use strict";var qv=Tc(),Uv=tr();xc.exports=function(a){return qv(Uv(a))}});var Ln=m((ML,Pc)=>{"use strict";Pc.exports=function(){}});var _t=m((CL,Ac)=>{"use strict";Ac.exports={}});var Y=m((Mn,wc)=>{"use strict";var ir=function(a){return a&&a.Math===Math&&a};wc.exports=ir(typeof globalThis=="object"&&globalThis)||ir(typeof window=="object"&&window)||ir(typeof self=="object"&&self)||ir(typeof global=="object"&&global)||ir(typeof Mn=="object"&&Mn)||function(){return this}()||Function("return this")()});var W=m((DL,kc)=>{"use strict";var Cn=typeof document=="object"&&document.all;kc.exports=typeof Cn=="undefined"&&Cn!==void 0?function(a){return typeof a=="function"||a===Cn}:function(a){return typeof a=="function"}});var Lc=m((BL,$c)=>{"use strict";var Hv=Y(),jv=W(),Rc=Hv.WeakMap;$c.exports=jv(Rc)&&/native code/.test(String(Rc))});var Re=m((OL,Mc)=>{"use strict";var Gv=W();Mc.exports=function(a){return typeof a=="object"?a!==null:Gv(a)}});var $e=m((VL,Cc)=>{"use strict";var Wv=Ee();Cc.exports=!Wv(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var ja=m((_L,Bc)=>{"use strict";var Yv=Y(),Dc=Re(),Dn=Yv.document,Qv=Dc(Dn)&&Dc(Dn.createElement);Bc.exports=function(a){return Qv?Dn.createElement(a):{}}});var Bn=m((NL,Oc)=>{"use strict";var zv=$e(),Kv=Ee(),Jv=ja();Oc.exports=!zv&&!Kv(function(){return Object.defineProperty(Jv("div"),"a",{get:function(){return 7}}).a!==7})});var On=m((FL,Vc)=>{"use strict";var Xv=$e(),Zv=Ee();Vc.exports=Xv&&Zv(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Ke=m((qL,_c)=>{"use strict";var ey=Re(),ty=String,iy=TypeError;_c.exports=function(a){if(ey(a))return a;throw new iy(ty(a)+" is not an object")}});var xe=m((UL,Nc)=>{"use strict";var ry=er(),Ga=Function.prototype.call;Nc.exports=ry?Ga.bind(Ga):function(){return Ga.apply(Ga,arguments)}});var Wa=m((HL,Fc)=>{"use strict";Fc.exports={}});var rt=m((jL,Uc)=>{"use strict";var Vn=Wa(),_n=Y(),ay=W(),qc=function(a){return ay(a)?a:void 0};Uc.exports=function(a,e){return arguments.length<2?qc(Vn[a])||qc(_n[a]):Vn[a]&&Vn[a][e]||_n[a]&&_n[a][e]}});var rr=m((GL,Hc)=>{"use strict";var sy=de();Hc.exports=sy({}.isPrototypeOf)});var mi=m((WL,Wc)=>{"use strict";var ny=Y(),jc=ny.navigator,Gc=jc&&jc.userAgent;Wc.exports=Gc?String(Gc):""});var Fn=m((YL,Xc)=>{"use strict";var Jc=Y(),Nn=mi(),Yc=Jc.process,Qc=Jc.Deno,zc=Yc&&Yc.versions||Qc&&Qc.version,Kc=zc&&zc.v8,Fe,Ya;Kc&&(Fe=Kc.split("."),Ya=Fe[0]>0&&Fe[0]<4?1:+(Fe[0]+Fe[1]));!Ya&&Nn&&(Fe=Nn.match(/Edge\/(\d+)/),(!Fe||Fe[1]>=74)&&(Fe=Nn.match(/Chrome\/(\d+)/),Fe&&(Ya=+Fe[1])));Xc.exports=Ya});var qn=m((QL,ed)=>{"use strict";var Zc=Fn(),oy=Ee(),uy=Y(),ly=uy.String;ed.exports=!!Object.getOwnPropertySymbols&&!oy(function(){var a=Symbol("symbol detection");return!ly(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Zc&&Zc<41})});var Un=m((zL,td)=>{"use strict";var cy=qn();td.exports=cy&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Hn=m((KL,id)=>{"use strict";var dy=rt(),py=W(),hy=rr(),fy=Un(),my=Object;id.exports=fy?function(a){return typeof a=="symbol"}:function(a){var e=dy("Symbol");return py(e)&&hy(e.prototype,my(a))}});var ar=m((JL,rd)=>{"use strict";var by=String;rd.exports=function(a){try{return by(a)}catch(e){return"Object"}}});var at=m((XL,ad)=>{"use strict";var gy=W(),Sy=ar(),vy=TypeError;ad.exports=function(a){if(gy(a))return a;throw new vy(Sy(a)+" is not a function")}});var sr=m((ZL,sd)=>{"use strict";var yy=at(),Ty=hi();sd.exports=function(a,e){var t=a[e];return Ty(t)?void 0:yy(t)}});var od=m((eM,nd)=>{"use strict";var jn=xe(),Gn=W(),Wn=Re(),Iy=TypeError;nd.exports=function(a,e){var t,i;if(e==="string"&&Gn(t=a.toString)&&!Wn(i=jn(t,a))||Gn(t=a.valueOf)&&!Wn(i=jn(t,a))||e!=="string"&&Gn(t=a.toString)&&!Wn(i=jn(t,a)))return i;throw new Iy("Can't convert object to primitive value")}});var qe=m((tM,ud)=>{"use strict";ud.exports=!0});var dd=m((iM,cd)=>{"use strict";var ld=Y(),Ey=Object.defineProperty;cd.exports=function(a,e){try{Ey(ld,a,{value:e,configurable:!0,writable:!0})}catch(t){ld[a]=e}return e}});var nr=m((rM,fd)=>{"use strict";var xy=qe(),Py=Y(),Ay=dd(),pd="__core-js_shared__",hd=fd.exports=Py[pd]||Ay(pd,{});(hd.versions||(hd.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 Yn=m((aM,bd)=>{"use strict";var md=nr();bd.exports=function(a,e){return md[a]||(md[a]=e||{})}});var or=m((sM,gd)=>{"use strict";var wy=tr(),ky=Object;gd.exports=function(a){return ky(wy(a))}});var Ue=m((nM,Sd)=>{"use strict";var Ry=de(),$y=or(),Ly=Ry({}.hasOwnProperty);Sd.exports=Object.hasOwn||function(e,t){return Ly($y(e),t)}});var Qn=m((oM,vd)=>{"use strict";var My=de(),Cy=0,Dy=Math.random(),By=My(1 .toString);vd.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+By(++Cy+Dy,36)}});var se=m((uM,Td)=>{"use strict";var Oy=Y(),Vy=Yn(),yd=Ue(),_y=Qn(),Ny=qn(),Fy=Un(),bi=Oy.Symbol,zn=Vy("wks"),qy=Fy?bi.for||bi:bi&&bi.withoutSetter||_y;Td.exports=function(a){return yd(zn,a)||(zn[a]=Ny&&yd(bi,a)?bi[a]:qy("Symbol."+a)),zn[a]}});var Pd=m((lM,xd)=>{"use strict";var Uy=xe(),Id=Re(),Ed=Hn(),Hy=sr(),jy=od(),Gy=se(),Wy=TypeError,Yy=Gy("toPrimitive");xd.exports=function(a,e){if(!Id(a)||Ed(a))return a;var t=Hy(a,Yy),i;if(t){if(e===void 0&&(e="default"),i=Uy(t,a,e),!Id(i)||Ed(i))return i;throw new Wy("Can't convert object to primitive value")}return e===void 0&&(e="number"),jy(a,e)}});var Kn=m((cM,Ad)=>{"use strict";var Qy=Pd(),zy=Hn();Ad.exports=function(a){var e=Qy(a,"string");return zy(e)?e:e+""}});var Nt=m(kd=>{"use strict";var Ky=$e(),Jy=Bn(),Xy=On(),Qa=Ke(),wd=Kn(),Zy=TypeError,Jn=Object.defineProperty,eT=Object.getOwnPropertyDescriptor,Xn="enumerable",Zn="configurable",eo="writable";kd.f=Ky?Xy?function(e,t,i){if(Qa(e),t=wd(t),Qa(i),typeof e=="function"&&t==="prototype"&&"value"in i&&eo in i&&!i[eo]){var r=eT(e,t);r&&r[eo]&&(e[t]=i.value,i={configurable:Zn in i?i[Zn]:r[Zn],enumerable:Xn in i?i[Xn]:r[Xn],writable:!1})}return Jn(e,t,i)}:Jn:function(e,t,i){if(Qa(e),t=wd(t),Qa(i),Jy)try{return Jn(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 ur=m((pM,Rd)=>{"use strict";Rd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var gi=m((hM,$d)=>{"use strict";var tT=$e(),iT=Nt(),rT=ur();$d.exports=tT?function(a,e,t){return iT.f(a,e,rT(1,t))}:function(a,e,t){return a[e]=t,a}});var za=m((fM,Md)=>{"use strict";var aT=Yn(),sT=Qn(),Ld=aT("keys");Md.exports=function(a){return Ld[a]||(Ld[a]=sT(a))}});var Ka=m((mM,Cd)=>{"use strict";Cd.exports={}});var ao=m((bM,Od)=>{"use strict";var nT=Lc(),Bd=Y(),oT=Re(),uT=gi(),to=Ue(),io=nr(),lT=za(),cT=Ka(),Dd="Object already initialized",ro=Bd.TypeError,dT=Bd.WeakMap,Ja,lr,Xa,pT=function(a){return Xa(a)?lr(a):Ja(a,{})},hT=function(a){return function(e){var t;if(!oT(e)||(t=lr(e)).type!==a)throw new ro("Incompatible receiver, "+a+" required");return t}};nT||io.state?(He=io.state||(io.state=new dT),He.get=He.get,He.has=He.has,He.set=He.set,Ja=function(a,e){if(He.has(a))throw new ro(Dd);return e.facade=a,He.set(a,e),e},lr=function(a){return He.get(a)||{}},Xa=function(a){return He.has(a)}):(Ft=lT("state"),cT[Ft]=!0,Ja=function(a,e){if(to(a,Ft))throw new ro(Dd);return e.facade=a,uT(a,Ft,e),e},lr=function(a){return to(a,Ft)?a[Ft]:{}},Xa=function(a){return to(a,Ft)});var He,Ft;Od.exports={set:Ja,get:lr,has:Xa,enforce:pT,getterFor:hT}});var so=m((gM,Fd)=>{"use strict";var fT=er(),Nd=Function.prototype,Vd=Nd.apply,_d=Nd.call;Fd.exports=typeof Reflect=="object"&&Reflect.apply||(fT?_d.bind(Vd):function(){return _d.apply(Vd,arguments)})});var no=m((SM,qd)=>{"use strict";var mT=pi(),bT=de();qd.exports=function(a){if(mT(a)==="Function")return bT(a)}});var Gd=m(jd=>{"use strict";var Ud={}.propertyIsEnumerable,Hd=Object.getOwnPropertyDescriptor,gT=Hd&&!Ud.call({1:2},1);jd.f=gT?function(e){var t=Hd(this,e);return!!t&&t.enumerable}:Ud});var Qd=m(Yd=>{"use strict";var ST=$e(),vT=xe(),yT=Gd(),TT=ur(),IT=fi(),ET=Kn(),xT=Ue(),PT=Bn(),Wd=Object.getOwnPropertyDescriptor;Yd.f=ST?Wd:function(e,t){if(e=IT(e),t=ET(t),PT)try{return Wd(e,t)}catch(i){}if(xT(e,t))return TT(!vT(yT.f,e,t),e[t])}});var oo=m((TM,zd)=>{"use strict";var AT=Ee(),wT=W(),kT=/#|\.prototype\./,cr=function(a,e){var t=$T[RT(a)];return t===MT?!0:t===LT?!1:wT(e)?AT(e):!!e},RT=cr.normalize=function(a){return String(a).replace(kT,".").toLowerCase()},$T=cr.data={},LT=cr.NATIVE="N",MT=cr.POLYFILL="P";zd.exports=cr});var dr=m((IM,Jd)=>{"use strict";var Kd=no(),CT=at(),DT=er(),BT=Kd(Kd.bind);Jd.exports=function(a,e){return CT(a),e===void 0?a:DT?BT(a,e):function(){return a.apply(e,arguments)}}});var Le=m((EM,Zd)=>{"use strict";var pr=Y(),OT=so(),VT=no(),_T=W(),NT=Qd().f,FT=oo(),Si=Wa(),qT=dr(),vi=gi(),Xd=Ue();nr();var UT=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};Zd.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?pr:r?pr[t]:pr[t]&&pr[t].prototype,o=i?Si:Si[t]||vi(Si,t,{})[t],u=o.prototype,c,l,d,p,h,f,b,g,y;for(p in e)c=FT(i?p:t+(r?".":"#")+p,a.forced),l=!c&&n&&Xd(n,p),f=o[p],l&&(a.dontCallGetSet?(y=NT(n,p),b=y&&y.value):b=n[p]),h=l&&b?b:e[p],!(!c&&!s&&typeof f==typeof h)&&(a.bind&&l?g=qT(h,pr):a.wrap&&l?g=UT(h):s&&_T(h)?g=VT(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&vi(g,"sham",!0),vi(o,p,g),s&&(d=t+"Prototype",Xd(Si,d)||vi(Si,d,{}),vi(Si[d],p,h),a.real&&u&&(c||!u[p])&&vi(u,p,h)))}});var ip=m((xM,tp)=>{"use strict";var uo=$e(),HT=Ue(),ep=Function.prototype,jT=uo&&Object.getOwnPropertyDescriptor,lo=HT(ep,"name"),GT=lo&&function(){}.name==="something",WT=lo&&(!uo||uo&&jT(ep,"name").configurable);tp.exports={EXISTS:lo,PROPER:GT,CONFIGURABLE:WT}});var ap=m((PM,rp)=>{"use strict";var YT=Math.ceil,QT=Math.floor;rp.exports=Math.trunc||function(e){var t=+e;return(t>0?QT:YT)(t)}});var Za=m((AM,sp)=>{"use strict";var zT=ap();sp.exports=function(a){var e=+a;return e!==e||e===0?0:zT(e)}});var op=m((wM,np)=>{"use strict";var KT=Za(),JT=Math.max,XT=Math.min;np.exports=function(a,e){var t=KT(a);return t<0?JT(t+e,0):XT(t,e)}});var lp=m((kM,up)=>{"use strict";var ZT=Za(),eI=Math.min;up.exports=function(a){var e=ZT(a);return e>0?eI(e,9007199254740991):0}});var es=m((RM,cp)=>{"use strict";var tI=lp();cp.exports=function(a){return tI(a.length)}});var hp=m(($M,pp)=>{"use strict";var iI=fi(),rI=op(),aI=es(),dp=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}};pp.exports={includes:dp(!0),indexOf:dp(!1)}});var bp=m((LM,mp)=>{"use strict";var sI=de(),co=Ue(),nI=fi(),oI=hp().indexOf,uI=Ka(),fp=sI([].push);mp.exports=function(a,e){var t=nI(a),i=0,r=[],s;for(s in t)!co(uI,s)&&co(t,s)&&fp(r,s);for(;e.length>i;)co(t,s=e[i++])&&(~oI(r,s)||fp(r,s));return r}});var po=m((MM,gp)=>{"use strict";gp.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var vp=m((CM,Sp)=>{"use strict";var lI=bp(),cI=po();Sp.exports=Object.keys||function(e){return lI(e,cI)}});var Tp=m(yp=>{"use strict";var dI=$e(),pI=On(),hI=Nt(),fI=Ke(),mI=fi(),bI=vp();yp.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 ho=m((BM,Ip)=>{"use strict";var gI=rt();Ip.exports=gI("document","documentElement")});var go=m((OM,Rp)=>{"use strict";var SI=Ke(),vI=Tp(),Ep=po(),yI=Ka(),TI=ho(),II=ja(),EI=za(),xp=">",Pp="<",mo="prototype",bo="script",wp=EI("IE_PROTO"),fo=function(){},kp=function(a){return Pp+bo+xp+a+Pp+"/"+bo+xp},Ap=function(a){a.write(kp("")),a.close();var e=a.parentWindow.Object;return a=null,e},xI=function(){var a=II("iframe"),e="java"+bo+":",t;return a.style.display="none",TI.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(kp("document.F=Object")),t.close(),t.F},ts,is=function(){try{ts=new ActiveXObject("htmlfile")}catch(e){}is=typeof document!="undefined"?document.domain&&ts?Ap(ts):xI():Ap(ts);for(var a=Ep.length;a--;)delete is[mo][Ep[a]];return is()};yI[wp]=!0;Rp.exports=Object.create||function(e,t){var i;return e!==null?(fo[mo]=SI(e),i=new fo,fo[mo]=null,i[wp]=e):i=is(),t===void 0?i:vI.f(i,t)}});var Lp=m((VM,$p)=>{"use strict";var PI=Ee();$p.exports=!PI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var vo=m((_M,Cp)=>{"use strict";var AI=Ue(),wI=W(),kI=or(),RI=za(),$I=Lp(),Mp=RI("IE_PROTO"),So=Object,LI=So.prototype;Cp.exports=$I?So.getPrototypeOf:function(a){var e=kI(a);if(AI(e,Mp))return e[Mp];var t=e.constructor;return wI(t)&&e instanceof t?t.prototype:e instanceof So?LI:null}});var yi=m((NM,Dp)=>{"use strict";var MI=gi();Dp.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:MI(a,e,t),a}});var Eo=m((FM,Vp)=>{"use strict";var CI=Ee(),DI=W(),BI=Re(),OI=go(),Bp=vo(),VI=yi(),_I=se(),NI=qe(),Io=_I("iterator"),Op=!1,st,yo,To;[].keys&&(To=[].keys(),"next"in To?(yo=Bp(Bp(To)),yo!==Object.prototype&&(st=yo)):Op=!0);var FI=!BI(st)||CI(function(){var a={};return st[Io].call(a)!==a});FI?st={}:NI&&(st=OI(st));DI(st[Io])||VI(st,Io,function(){return this});Vp.exports={IteratorPrototype:st,BUGGY_SAFARI_ITERATORS:Op}});var rs=m((qM,Np)=>{"use strict";var qI=se(),UI=qI("toStringTag"),_p={};_p[UI]="z";Np.exports=String(_p)==="[object z]"});var hr=m((UM,Fp)=>{"use strict";var HI=rs(),jI=W(),as=pi(),GI=se(),WI=GI("toStringTag"),YI=Object,QI=as(function(){return arguments}())==="Arguments",zI=function(a,e){try{return a[e]}catch(t){}};Fp.exports=HI?as:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=zI(e=YI(a),WI))=="string"?t:QI?as(e):(i=as(e))==="Object"&&jI(e.callee)?"Arguments":i}});var Up=m((HM,qp)=>{"use strict";var KI=rs(),JI=hr();qp.exports=KI?{}.toString:function(){return"[object "+JI(this)+"]"}});var fr=m((jM,jp)=>{"use strict";var XI=rs(),ZI=Nt().f,eE=gi(),tE=Ue(),iE=Up(),rE=se(),Hp=rE("toStringTag");jp.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(tE(r,Hp)||ZI(r,Hp,{configurable:!0,value:e}),i&&!XI&&eE(r,"toString",iE))}});var Wp=m((GM,Gp)=>{"use strict";var aE=Eo().IteratorPrototype,sE=go(),nE=ur(),oE=fr(),uE=_t(),lE=function(){return this};Gp.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 Qp=m((WM,Yp)=>{"use strict";var cE=de(),dE=at();Yp.exports=function(a,e,t){try{return cE(dE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(i){}}});var Kp=m((YM,zp)=>{"use strict";var pE=Re();zp.exports=function(a){return pE(a)||a===null}});var Xp=m((QM,Jp)=>{"use strict";var hE=Kp(),fE=String,mE=TypeError;Jp.exports=function(a){if(hE(a))return a;throw new mE("Can't set "+fE(a)+" as a prototype")}});var xo=m((zM,Zp)=>{"use strict";var bE=Qp(),gE=Re(),SE=tr(),vE=Xp();Zp.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 ch=m((KM,lh)=>{"use strict";var yE=Le(),TE=xe(),ss=qe(),oh=ip(),IE=W(),EE=Wp(),eh=vo(),th=xo(),xE=fr(),PE=gi(),Po=yi(),AE=se(),ih=_t(),uh=Eo(),wE=oh.PROPER,kE=oh.CONFIGURABLE,rh=uh.IteratorPrototype,ns=uh.BUGGY_SAFARI_ITERATORS,mr=AE("iterator"),ah="keys",br="values",sh="entries",nh=function(){return this};lh.exports=function(a,e,t,i,r,s,n){EE(t,e,i);var o=function(y){if(y===r&&p)return p;if(!ns&&y&&y in l)return l[y];switch(y){case ah:return function(){return new t(this,y)};case br:return function(){return new t(this,y)};case sh:return function(){return new t(this,y)}}return function(){return new t(this)}},u=e+" Iterator",c=!1,l=a.prototype,d=l[mr]||l["@@iterator"]||r&&l[r],p=!ns&&d||o(r),h=e==="Array"&&l.entries||d,f,b,g;if(h&&(f=eh(h.call(new a)),f!==Object.prototype&&f.next&&(!ss&&eh(f)!==rh&&(th?th(f,rh):IE(f[mr])||Po(f,mr,nh)),xE(f,u,!0,!0),ss&&(ih[u]=nh))),wE&&r===br&&d&&d.name!==br&&(!ss&&kE?PE(l,"name",br):(c=!0,p=function(){return TE(d,this)})),r)if(b={values:o(br),keys:s?p:o(ah),entries:o(sh)},n)for(g in b)(ns||c||!(g in l))&&Po(l,g,b[g]);else yE({target:e,proto:!0,forced:ns||c},b);return(!ss||n)&&l[mr]!==p&&Po(l,mr,p,{name:r}),ih[e]=p,b}});var ph=m((JM,dh)=>{"use strict";dh.exports=function(a,e){return{value:a,done:e}}});var wo=m((XM,gh)=>{"use strict";var RE=fi(),Ao=Ln(),hh=_t(),mh=ao(),$E=Nt().f,LE=ch(),os=ph(),ME=qe(),CE=$e(),bh="Array Iterator",DE=mh.set,BE=mh.getterFor(bh);gh.exports=LE(Array,"Array",function(a,e){DE(this,{type:bh,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,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 fh=hh.Arguments=hh.Array;Ao("keys");Ao("values");Ao("entries");if(!ME&&CE&&fh.name!=="values")try{$E(fh,"name",{value:"values"})}catch(a){}});var vh=m((ZM,Sh)=>{"use strict";var OE=se(),VE=_t(),_E=OE("iterator"),NE=Array.prototype;Sh.exports=function(a){return a!==void 0&&(VE.Array===a||NE[_E]===a)}});var ko=m((eC,Th)=>{"use strict";var FE=hr(),yh=sr(),qE=hi(),UE=_t(),HE=se(),jE=HE("iterator");Th.exports=function(a){if(!qE(a))return yh(a,jE)||yh(a,"@@iterator")||UE[FE(a)]}});var Eh=m((tC,Ih)=>{"use strict";var GE=xe(),WE=at(),YE=Ke(),QE=ar(),zE=ko(),KE=TypeError;Ih.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 Ah=m((iC,Ph)=>{"use strict";var JE=xe(),xh=Ke(),XE=sr();Ph.exports=function(a,e,t){var i,r;xh(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 xh(i),t}});var ls=m((rC,$h)=>{"use strict";var ZE=dr(),ex=xe(),tx=Ke(),ix=ar(),rx=vh(),ax=es(),wh=rr(),sx=Eh(),nx=ko(),kh=Ah(),ox=TypeError,us=function(a,e){this.stopped=a,this.result=e},Rh=us.prototype;$h.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),c,l,d,p,h,f,b,g=function(I){return c&&kh(c,"normal",I),new us(!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)c=a.iterator;else if(n)c=a;else{if(l=nx(a),!l)throw new ox(ix(a)+" is not iterable");if(rx(l)){for(d=0,p=ax(a);p>d;d++)if(h=y(a[d]),h&&wh(Rh,h))return h;return new us(!1)}c=sx(a,l)}for(f=s?a.next:c.next;!(b=ex(f,c)).done;){try{h=y(b.value)}catch(I){kh(c,"throw",I)}if(typeof h=="object"&&h&&wh(Rh,h))return h}return new us(!1)}});var Mh=m((aC,Lh)=>{"use strict";var ux=$e(),lx=Nt(),cx=ur();Lh.exports=function(a,e,t){ux?lx.f(a,e,cx(0,t)):a[e]=t}});var Ch=m(()=>{"use strict";var dx=Le(),px=ls(),hx=Mh();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 Bh=m((oC,Dh)=>{"use strict";wo();Ch();var fx=Wa();Dh.exports=fx.Object.fromEntries});var Vh=m((uC,Oh)=>{"use strict";Oh.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 Nh=m(()=>{"use strict";wo();var mx=Vh(),bx=Y(),gx=fr(),_h=_t();for(cs in mx)gx(bx[cs],cs),_h[cs]=_h.Array;var cs});var qh=m((dC,Fh)=>{"use strict";var Sx=Bh();Nh();Fh.exports=Sx});var Ro=m((pC,Uh)=>{"use strict";var vx=qh();Uh.exports=vx});var Hh=m(()=>{"use strict"});var $o=m((mC,jh)=>{"use strict";var gr=Y(),yx=mi(),Tx=pi(),ds=function(a){return yx.slice(0,a.length)===a};jh.exports=function(){return ds("Bun/")?"BUN":ds("Cloudflare-Workers")?"CLOUDFLARE":ds("Deno/")?"DENO":ds("Node.js/")?"NODE":gr.Bun&&typeof Bun.version=="string"?"BUN":gr.Deno&&typeof Deno.version=="object"?"DENO":Tx(gr.process)==="process"?"NODE":gr.window&&gr.document?"BROWSER":"REST"}()});var ps=m((bC,Gh)=>{"use strict";var Ix=$o();Gh.exports=Ix==="NODE"});var Yh=m((gC,Wh)=>{"use strict";var Ex=Nt();Wh.exports=function(a,e,t){return Ex.f(a,e,t)}});var Kh=m((SC,zh)=>{"use strict";var xx=rt(),Px=Yh(),Ax=se(),wx=$e(),Qh=Ax("species");zh.exports=function(a){var e=xx(a);wx&&e&&!e[Qh]&&Px(e,Qh,{configurable:!0,get:function(){return this}})}});var Xh=m((vC,Jh)=>{"use strict";var kx=rr(),Rx=TypeError;Jh.exports=function(a,e){if(kx(e,a))return a;throw new Rx("Incorrect invocation")}});var Mo=m((yC,Zh)=>{"use strict";var $x=de(),Lx=W(),Lo=nr(),Mx=$x(Function.toString);Lx(Lo.inspectSource)||(Lo.inspectSource=function(a){return Mx(a)});Zh.exports=Lo.inspectSource});var nf=m((TC,sf)=>{"use strict";var Cx=de(),Dx=Ee(),ef=W(),Bx=hr(),Ox=rt(),Vx=Mo(),tf=function(){},rf=Ox("Reflect","construct"),Co=/^\s*(?:class|function)\b/,_x=Cx(Co.exec),Nx=!Co.test(tf),Sr=function(e){if(!ef(e))return!1;try{return rf(tf,[],e),!0}catch(t){return!1}},af=function(e){if(!ef(e))return!1;switch(Bx(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Nx||!!_x(Co,Vx(e))}catch(t){return!0}};af.sham=!0;sf.exports=!rf||Dx(function(){var a;return Sr(Sr.call)||!Sr(Object)||!Sr(function(){a=!0})||a})?af:Sr});var uf=m((IC,of)=>{"use strict";var Fx=nf(),qx=ar(),Ux=TypeError;of.exports=function(a){if(Fx(a))return a;throw new Ux(qx(a)+" is not a constructor")}});var Do=m((EC,cf)=>{"use strict";var lf=Ke(),Hx=uf(),jx=hi(),Gx=se(),Wx=Gx("species");cf.exports=function(a,e){var t=lf(a).constructor,i;return t===void 0||jx(i=lf(t)[Wx])?e:Hx(i)}});var pf=m((xC,df)=>{"use strict";var Yx=de();df.exports=Yx([].slice)});var ff=m((PC,hf)=>{"use strict";var Qx=TypeError;hf.exports=function(a,e){if(a<e)throw new Qx("Not enough arguments");return a}});var Bo=m((AC,mf)=>{"use strict";var zx=mi();mf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(zx)});var jo=m((wC,xf)=>{"use strict";var Pe=Y(),Kx=so(),Jx=dr(),bf=W(),Xx=Ue(),Ef=Ee(),gf=ho(),Zx=pf(),Sf=ja(),eP=ff(),tP=Bo(),iP=ps(),qo=Pe.setImmediate,Uo=Pe.clearImmediate,rP=Pe.process,Oo=Pe.Dispatch,aP=Pe.Function,vf=Pe.MessageChannel,sP=Pe.String,Vo=0,vr={},yf="onreadystatechange",yr,qt,_o,No;Ef(function(){yr=Pe.location});var Ho=function(a){if(Xx(vr,a)){var e=vr[a];delete vr[a],e()}},Fo=function(a){return function(){Ho(a)}},Tf=function(a){Ho(a.data)},If=function(a){Pe.postMessage(sP(a),yr.protocol+"//"+yr.host)};(!qo||!Uo)&&(qo=function(e){eP(arguments.length,1);var t=bf(e)?e:aP(e),i=Zx(arguments,1);return vr[++Vo]=function(){Kx(t,void 0,i)},qt(Vo),Vo},Uo=function(e){delete vr[e]},iP?qt=function(a){rP.nextTick(Fo(a))}:Oo&&Oo.now?qt=function(a){Oo.now(Fo(a))}:vf&&!tP?(_o=new vf,No=_o.port2,_o.port1.onmessage=Tf,qt=Jx(No.postMessage,No)):Pe.addEventListener&&bf(Pe.postMessage)&&!Pe.importScripts&&yr&&yr.protocol!=="file:"&&!Ef(If)?(qt=If,Pe.addEventListener("message",Tf,!1)):yf in Sf("script")?qt=function(a){gf.appendChild(Sf("script"))[yf]=function(){gf.removeChild(this),Ho(a)}}:qt=function(a){setTimeout(Fo(a),0)});xf.exports={set:qo,clear:Uo}});var wf=m((kC,Af)=>{"use strict";var Pf=Y(),nP=$e(),oP=Object.getOwnPropertyDescriptor;Af.exports=function(a){if(!nP)return Pf[a];var e=oP(Pf,a);return e&&e.value}});var Go=m((RC,Rf)=>{"use strict";var kf=function(){this.head=null,this.tail=null};kf.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}}};Rf.exports=kf});var Lf=m(($C,$f)=>{"use strict";var uP=mi();$f.exports=/ipad|iphone|ipod/i.test(uP)&&typeof Pebble!="undefined"});var Cf=m((LC,Mf)=>{"use strict";var lP=mi();Mf.exports=/web0s(?!.*chrome)/i.test(lP)});var Ff=m((MC,Nf)=>{"use strict";var Ii=Y(),cP=wf(),Df=dr(),Wo=jo().set,dP=Go(),pP=Bo(),hP=Lf(),fP=Cf(),Yo=ps(),Bf=Ii.MutationObserver||Ii.WebKitMutationObserver,Of=Ii.document,Vf=Ii.process,hs=Ii.Promise,Ko=cP("queueMicrotask"),Ti,Qo,zo,fs,_f;Ko||(Tr=new dP,Ir=function(){var a,e;for(Yo&&(a=Vf.domain)&&a.exit();e=Tr.get();)try{e()}catch(t){throw Tr.head&&Ti(),t}a&&a.enter()},!pP&&!Yo&&!fP&&Bf&&Of?(Qo=!0,zo=Of.createTextNode(""),new Bf(Ir).observe(zo,{characterData:!0}),Ti=function(){zo.data=Qo=!Qo}):!hP&&hs&&hs.resolve?(fs=hs.resolve(void 0),fs.constructor=hs,_f=Df(fs.then,fs),Ti=function(){_f(Ir)}):Yo?Ti=function(){Vf.nextTick(Ir)}:(Wo=Df(Wo,Ii),Ti=function(){Wo(Ir)}),Ko=function(a){Tr.head||Ti(),Tr.add(a)});var Tr,Ir;Nf.exports=Ko});var Uf=m((CC,qf)=>{"use strict";qf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var ms=m((DC,Hf)=>{"use strict";Hf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Ut=m((BC,jf)=>{"use strict";var mP=Y();jf.exports=mP.Promise});var Ei=m((OC,Qf)=>{"use strict";var bP=Y(),Er=Ut(),gP=W(),SP=oo(),vP=Mo(),yP=se(),Gf=$o(),TP=qe(),Jo=Fn(),Wf=Er&&Er.prototype,IP=yP("species"),Xo=!1,Yf=gP(bP.PromiseRejectionEvent),EP=SP("Promise",function(){var a=vP(Er),e=a!==String(Er);if(!e&&Jo===66||TP&&!(Wf.catch&&Wf.finally))return!0;if(!Jo||Jo<51||!/native code/.test(a)){var t=new Er(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[IP]=i,Xo=t.then(function(){})instanceof i,!Xo)return!0}return!e&&(Gf==="BROWSER"||Gf==="DENO")&&!Yf});Qf.exports={CONSTRUCTOR:EP,REJECTION_EVENT:Yf,SUBCLASSING:Xo}});var xi=m((VC,Kf)=>{"use strict";var zf=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=zf(e),this.reject=zf(t)};Kf.exports.f=function(a){return new PP(a)}});var mm=m(()=>{"use strict";var AP=Le(),wP=qe(),vs=ps(),It=Y(),ki=xe(),Jf=yi(),Xf=xo(),kP=fr(),RP=Kh(),$P=at(),Ss=W(),LP=Re(),MP=Xh(),CP=Do(),rm=jo().set,ru=Ff(),DP=Uf(),BP=ms(),OP=Go(),am=ao(),ys=Ut(),au=Ei(),sm=xi(),Ts="Promise",nm=au.CONSTRUCTOR,VP=au.REJECTION_EVENT,_P=au.SUBCLASSING,Zo=am.getterFor(Ts),NP=am.set,Pi=ys&&ys.prototype,Ht=ys,bs=Pi,om=It.TypeError,eu=It.document,su=It.process,tu=sm.f,FP=tu,qP=!!(eu&&eu.createEvent&&It.dispatchEvent),um="unhandledrejection",UP="rejectionhandled",Zf=0,lm=1,HP=2,nu=1,cm=2,gs,em,jP,tm,dm=function(a){var e;return LP(a)&&Ss(e=a.then)?e:!1},pm=function(a,e){var t=e.value,i=e.state===lm,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,c,l;try{r?(i||(e.rejection===cm&&WP(e),e.rejection=nu),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),l=!0)),u===a.promise?n(new om("Promise-chain cycle")):(c=dm(u))?ki(c,u,s,n):s(u)):n(t)}catch(d){o&&!l&&o.exit(),n(d)}},hm=function(a,e){a.notified||(a.notified=!0,ru(function(){for(var t=a.reactions,i;i=t.get();)pm(i,a);a.notified=!1,e&&!a.rejection&&GP(a)}))},fm=function(a,e,t){var i,r;qP?(i=eu.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),It.dispatchEvent(i)):i={promise:e,reason:t},!VP&&(r=It["on"+a])?r(i):a===um&&DP("Unhandled promise rejection",t)},GP=function(a){ki(rm,It,function(){var e=a.facade,t=a.value,i=im(a),r;if(i&&(r=BP(function(){vs?su.emit("unhandledRejection",t,e):fm(um,e,t)}),a.rejection=vs||im(a)?cm:nu,r.error))throw r.value})},im=function(a){return a.rejection!==nu&&!a.parent},WP=function(a){ki(rm,It,function(){var e=a.facade;vs?su.emit("rejectionHandled",e):fm(UP,e,a.value)})},Ai=function(a,e,t){return function(i){a(e,i,t)}},wi=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=HP,hm(a,!0))},iu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new om("Promise can't be resolved itself");var i=dm(e);i?ru(function(){var r={done:!1};try{ki(i,e,Ai(iu,r,a),Ai(wi,r,a))}catch(s){wi(r,s,a)}}):(a.value=e,a.state=lm,hm(a,!1))}catch(r){wi({done:!1},r,a)}}};if(nm&&(Ht=function(e){MP(this,bs),$P(e),ki(gs,this);var t=Zo(this);try{e(Ai(iu,t),Ai(wi,t))}catch(i){wi(t,i)}},bs=Ht.prototype,gs=function(e){NP(this,{type:Ts,done:!1,notified:!1,parent:!1,reactions:new OP,rejection:!1,state:Zf,value:void 0})},gs.prototype=Jf(bs,"then",function(e,t){var i=Zo(this),r=tu(CP(this,Ht));return i.parent=!0,r.ok=Ss(e)?e:!0,r.fail=Ss(t)&&t,r.domain=vs?su.domain:void 0,i.state===Zf?i.reactions.add(r):ru(function(){pm(r,i)}),r.promise}),em=function(){var a=new gs,e=Zo(a);this.promise=a,this.resolve=Ai(iu,e),this.reject=Ai(wi,e)},sm.f=tu=function(a){return a===Ht||a===jP?new em(a):FP(a)},!wP&&Ss(ys)&&Pi!==Object.prototype)){tm=Pi.then,_P||Jf(Pi,"then",function(e,t){var i=this;return new Ht(function(r,s){ki(tm,i,r,s)}).then(e,t)},{unsafe:!0});try{delete Pi.constructor}catch(a){}Xf&&Xf(Pi,bs)}AP({global:!0,constructor:!0,wrap:!0,forced:nm},{Promise:Ht});kP(Ht,Ts,!1,!0);RP(Ts)});var ym=m((FC,vm)=>{"use strict";var YP=se(),gm=YP("iterator"),Sm=!1;try{bm=0,ou={next:function(){return{done:!!bm++}},return:function(){Sm=!0}},ou[gm]=function(){return this},Array.from(ou,function(){throw 2})}catch(a){}var bm,ou;vm.exports=function(a,e){try{if(!e&&!Sm)return!1}catch(r){return!1}var t=!1;try{var i={};i[gm]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch(r){}return t}});var uu=m((qC,Tm)=>{"use strict";var QP=Ut(),zP=ym(),KP=Ei().CONSTRUCTOR;Tm.exports=KP||!zP(function(a){QP.all(a).then(void 0,function(){})})});var Im=m(()=>{"use strict";var JP=Le(),XP=xe(),ZP=at(),eA=xi(),tA=ms(),iA=ls(),rA=uu();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=[],c=0,l=1;iA(e,function(d){var p=c++,h=!1;l++,XP(o,t,d).then(function(f){h||(h=!0,u[p]=f,--l||r(u))},s)}),--l||r(u)});return n.error&&s(n.value),i.promise}})});var xm=m(()=>{"use strict";var aA=Le(),sA=qe(),nA=Ei().CONSTRUCTOR,cu=Ut(),oA=rt(),uA=W(),lA=yi(),Em=cu&&cu.prototype;aA({target:"Promise",proto:!0,forced:nA,real:!0},{catch:function(a){return this.then(void 0,a)}});!sA&&uA(cu)&&(lu=oA("Promise").prototype.catch,Em.catch!==lu&&lA(Em,"catch",lu,{unsafe:!0}));var lu});var Pm=m(()=>{"use strict";var cA=Le(),dA=xe(),pA=at(),hA=xi(),fA=ms(),mA=ls(),bA=uu();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 Am=m(()=>{"use strict";var gA=Le(),SA=xi(),vA=Ei().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 du=m((KC,wm)=>{"use strict";var yA=Ke(),TA=Re(),IA=xi();wm.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 $m=m(()=>{"use strict";var EA=Le(),xA=rt(),km=qe(),PA=Ut(),Rm=Ei().CONSTRUCTOR,AA=du(),wA=xA("Promise"),kA=km&&!Rm;EA({target:"Promise",stat:!0,forced:km||Rm},{resolve:function(e){return AA(kA&&this===wA?PA:this,e)}})});var Lm=m(()=>{"use strict";mm();Im();xm();Pm();Am();$m()});var Bm=m(()=>{"use strict";var RA=Le(),$A=qe(),Is=Ut(),LA=Ee(),Cm=rt(),Dm=W(),MA=Do(),Mm=du(),CA=yi(),hu=Is&&Is.prototype,DA=!!Is&&LA(function(){hu.finally.call({then:function(){}},function(){})});RA({target:"Promise",proto:!0,real:!0,forced:DA},{finally:function(a){var e=MA(this,Cm("Promise")),t=Dm(a);return this.then(t?function(i){return Mm(e,a()).then(function(){return i})}:a,t?function(i){return Mm(e,a()).then(function(){throw i})}:a)}});!$A&&Dm(Is)&&(pu=Cm("Promise").prototype.finally,hu.finally!==pu&&CA(hu,"finally",pu,{unsafe:!0}));var pu});var Es=m((rD,Om)=>{"use strict";var BA=rt();Om.exports=BA});var _m=m((aD,Vm)=>{"use strict";Hh();Lm();Bm();var OA=Es();Vm.exports=OA("Promise","finally")});var Fm=m((sD,Nm)=>{"use strict";var VA=_m();Nm.exports=VA});var xs=m((nD,qm)=>{"use strict";var _A=Fm();qm.exports=_A});var pb=m(()=>{"use strict";var hw=Le(),fw=or(),mw=es(),bw=Za(),gw=Ln();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 fb=m((m0,hb)=>{"use strict";pb();var Sw=Es();hb.exports=Sw("Array","at")});var bb=m((b0,mb)=>{"use strict";var vw=fb();mb.exports=vw});var wr=m((g0,gb)=>{"use strict";var yw=bb();gb.exports=yw});var Ig=m(()=>{"use strict"});var Eg=m(()=>{"use strict"});var Pg=m((S_,xg)=>{"use strict";var wk=Re(),kk=pi(),Rk=se(),$k=Rk("match");xg.exports=function(a){var e;return wk(a)&&((e=a[$k])!==void 0?!!e:kk(a)==="RegExp")}});var wg=m((v_,Ag)=>{"use strict";var Lk=hr(),Mk=String;Ag.exports=function(a){if(Lk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return Mk(a)}});var Rg=m((y_,kg)=>{"use strict";var Ck=Ke();kg.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 Mg=m((T_,Lg)=>{"use strict";var Dk=xe(),Bk=Ue(),Ok=rr(),Vk=Rg(),$g=RegExp.prototype;Lg.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in $g)&&!Bk(a,"flags")&&Ok($g,a)?Dk(Vk,a):e}});var Dg=m((I_,Cg)=>{"use strict";var Hu=de(),_k=or(),Nk=Math.floor,qu=Hu("".charAt),Fk=Hu("".replace),Uu=Hu("".slice),qk=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Uk=/\$([$&'`]|\d{1,2})/g;Cg.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=Uk;return r!==void 0&&(r=_k(r),u=qk),Fk(s,u,function(c,l){var d;switch(qu(l,0)){case"$":return"$";case"&":return a;case"`":return Uu(e,0,t);case"'":return Uu(e,n);case"<":d=r[Uu(l,1,-1)];break;default:var p=+l;if(p===0)return c;if(p>o){var h=Nk(p/10);return h===0?c:h<=o?i[h-1]===void 0?qu(l,1):i[h-1]+qu(l,1):c}d=i[p-1]}return d===void 0?"":d})}});var Vg=m(()=>{"use strict";var Hk=Le(),jk=xe(),Gu=de(),Bg=tr(),Gk=W(),Wk=hi(),Yk=Pg(),Ni=wg(),Qk=sr(),zk=Mg(),Kk=Dg(),Jk=se(),Xk=qe(),Zk=Jk("replace"),eR=TypeError,ju=Gu("".indexOf),tR=Gu("".replace),Og=Gu("".slice),iR=Math.max;Hk({target:"String",proto:!0},{replaceAll:function(e,t){var i=Bg(this),r,s,n,o,u,c,l,d,p,h,f=0,b="";if(!Wk(e)){if(r=Yk(e),r&&(s=Ni(Bg(zk(e))),!~ju(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(Ni(i),e,t)}for(o=Ni(i),u=Ni(e),c=Gk(t),c||(t=Ni(t)),l=u.length,d=iR(1,l),p=ju(o,u);p!==-1;)h=c?Ni(t(u,p,o)):Kk(u,o,p,[],void 0,t),b+=Og(o,f,p)+h,f=p+l,p=p+d>o.length?-1:ju(o,u,p+d);return f<o.length&&(b+=Og(o,f)),b}})});var Ng=m((P_,_g)=>{"use strict";Ig();Eg();Vg();var rR=Es();_g.exports=rR("String","replaceAll")});var qg=m((A_,Fg)=>{"use strict";var aR=Ng();Fg.exports=aR});var Hg=m((w_,Ug)=>{"use strict";var sR=qg();Ug.exports=sR});var nc="2.0.115-dev.c6f77ae4.0";var ce=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(ce||{}),Tt=(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))(Tt||{});var qa=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(qa||{}),Pn=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Pn||{});var An=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(An||{});import{assertNever as pc,assertNonNullable as xv,isNonNullable as Ua,ValueSubject as wn,Subject as Pv,Subscription as Av,merge as wv,observableFrom as kv,fromEvent as uc,map as lc,tap as cc,filterChanged as Rv,isNullable as kn,ErrorCategory as dc}from"@vkontakte/videoplayer-shared";var oc=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 Ha=class{constructor(e){this.connection$=new wn(void 0);this.castState$=new wn("NOT_AVAILABLE");this.errorEvent$=new Pv;this.realCastState$=new wn("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=Ua((s=window.chrome)==null?void 0:s.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},r||oc("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:dc.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(){Ua(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();kn(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();kn(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(uc(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 pc(r.sessionState)}})).add(wv(uc(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(cc(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),lc(r=>r.castState)),kv([i.getCastState()])).pipe(Rv(),lc($v),cc(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let s=r==="CONNECTED",n=Ua(this.connection$.getValue());if(s&&!n){let c=i.getCurrentSession();xv(c);let l=c.getCastDevice(),d=(u=(o=c.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(kn(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:c,castDevice:l}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?Ua(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:dc.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 pc(a)}};var qS=ze(Ro(),1);var Jm=ze(xs(),1);import{assertNever as Um}from"@vkontakte/videoplayer-shared";var te=(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},fu=(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 Ps,merge as Hm}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$=Hm(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Hm(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 jm=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 Ri,assertNonNullable as jt,debounce as Gm,ErrorCategory as Wm,fromEvent as Gt,isNonNullable as Ym,map as Qm,merge as zm,observableFrom as qA,Subject as UA,Subscription as mu,timeout as HA,getHighestQuality as jA}from"@vkontakte/videoplayer-shared";var GA=5,WA=5,YA=500,Km=7e3,xr=class{constructor(e){this.subscription=new mu;this.loadMediaTimeoutSubscription=new mu;this.videoState=new L("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:Ri(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:Ri(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:Ri(e)}break}default:Ri(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(jm(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 mu;this.subscription.add(e),this.subscription.add(zm(this.videoState.stateChangeStarted$.pipe(Qm(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Qm(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 UA;e.add(r.pipe(Gm(YA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Gt(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(Gt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Gt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Gt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(Gt(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:Ri(n)}}),t(Gt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(Gt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=zm(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,qA(["init"])).pipe(Gm(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 c;let t=this.params.source,i,r,s;switch(e){case"MPEG":{let l=t[e];jt(l);let d=jA(Object.keys(l));jt(d);let p=l[d];jt(p),i=p,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];jt(l),i=l.url,r="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=t[e];jt(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];jt(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];jt(l),i=te(l.url),r="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",d=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Wm.VIDEO_PIPELINE,message:l,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Ri(e)}let n=new chrome.cast.media.MediaInfo((c=this.params.meta.videoId)!=null?c:i,r);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return Ym(o)&&(n.metadata.title=o),Ym(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(Km).subscribe(()=>s(`timeout(${Km})`)))});(0,Jm.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:Wm.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{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 Xm=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 bu=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)}},gu=window.WeakMap?new WeakMap:new bu,Su=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?Zm(t):(t=document.createElement("video"),a.appendChild(t)),gu.set(t,i);let r=new KA;return r.add(JA(t,e)),Su.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=Su.get(a);e==null||e.unsubscribe(),Su.delete(a);let t=gu.get(a);gu.delete(a),t?Zm(a):Xm(a)};import{assertNonNullable as Pr,isNonNullable as Xe,isNullable as ew,fromEvent as $i,merge as eb,observableFrom as tb,filterChanged as ib,map as Ar,Subject as rb,Subscription as tw,ValueSubject as iw,ErrorCategory as rw}from"@vkontakte/videoplayer-shared";import{isNonNullable as vu,isNullable as XA,Subscription as ZA}from"@vkontakte/videoplayer-shared";var As=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=XA(r),c=new ZA;return r&&c.add(r.subscribe(l=>{let d=a.getState();i(l,d)&&a.setState(l)},s)),i(o,n)||(t(n),u&&a.setState(n)),c.add(a.stateChangeStarted$.subscribe(l=>{t(l.to),u&&a.setState(l.to)},s)),c},Je=(a,e,t)=>As(e,()=>a.loop,i=>{vu(i)&&(a.loop=i)},{onError:t}),fe=(a,e,t,i)=>As(e,()=>({muted:a.muted,volume:a.volume}),r=>{vu(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}),Me=(a,e,t,i)=>As(e,()=>a.playbackRate,r=>{vu(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),Et=As;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},yu=class a{constructor(){this.available$=new rb;this.current$=new iw(void 0);this.error$=new rb;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(Et(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(Ar(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Et(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(Ar(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Et(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(Et(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Pr(this.video);let{textTracks:e}=this.video;this.subscription.add($i(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(eb($i(e,"addtrack"),$i(e,"removetrack"),tb(["init"])).pipe(Ar(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),ib((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add(eb($i(e,"change"),tb(["init"])).pipe(Ar(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Ar(i=>i&&this.htmlTextTrackToITextTrack(i).id),ib()).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($i(e,"addtrack").subscribe(i=>{var s,n;(s=i.track)==null||s.addEventListener("cuechange",t);let r=o=>{var c,l,d,p,h;let u=(l=(c=o.target)==null?void 0:c.cues)!=null?l:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add($i(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){Pr(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,c,l;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:(c=this.externalTracks.get(r))==null?void 0:c.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(l=this.internalTracks.get(r))==null?void 0:l.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){Pr(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){Pr(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){Pr(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)}},Ce=yu;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 ab=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},Tu=a=>{let e=ab(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},sb=a=>{let e=ab(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as De,map as xt,merge as ob,filterChanged as ow,isNonNullable as ub,Subject as uw,filter as lb,mapTo as cb,combine as lw,once as cw,ErrorCategory as dw,ValueSubject as db,clientChecker as pw}from"@vkontakte/videoplayer-shared";var nw=3,nb=(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=>De(a,S).pipe(cb(void 0)),i=ob(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(S=>De(a,S))).pipe(xt(S=>S.type==="ended"?a.readyState<2:a.readyState<3),ow()),r=ob(De(a,"progress"),De(a,"timeupdate")).pipe(xt(()=>nb(a.buffered,a.currentTime))),s=pw.isSafari?lw({play:e("play").pipe(cw()),playing:e("playing")}).pipe(cb(void 0)):e("playing"),n=De(a,"volumechange").pipe(xt(()=>({muted:a.muted,volume:a.volume}))),o=De(a,"ratechange").pipe(xt(()=>a.playbackRate)),u=De(a,"error").pipe(lb(()=>!!(a.error||a.played.length)),xt(()=>{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}})),c=De(a,"timeupdate").pipe(xt(()=>a.currentTime)),l=new uw,d=.3,p;c.subscribe(S=>{a.loop&&ub(p)&&ub(S)&&p>=a.duration-d&&S<=d&&l.next(p),p=S});let h=e("pause").pipe(lb(()=>!a.error&&p!==a.duration)),f=De(a,"enterpictureinpicture"),b=De(a,"leavepictureinpicture"),g=new db(sb(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let y=new db(Tu(a));return De(a,"fullscreenchange").pipe(xt(()=>Tu(a))).subscribe(y),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:l,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:De(a,"durationchange").pipe(xt(()=>a.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:y}};import{VideoQuality as Pt}from"@vkontakte/videoplayer-shared";var At=a=>{switch(a){case"mobile":return Pt.Q_144P;case"lowest":return Pt.Q_240P;case"low":return Pt.Q_360P;case"sd":case"medium":return Pt.Q_480P;case"hd":case"high":return Pt.Q_720P;case"fullhd":case"full":return Pt.Q_1080P;case"quadhd":case"quad":return Pt.Q_1440P;case"ultrahd":case"ultra":return Pt.Q_2160P}};var Wt=ze(wr(),1);import{isNonNullable as X,isNullable as Eu,now as Pb,isHigher as xu,isHigherOrEqual as Tb,isInvariantQuality as Ib,isLower as Eb,isLowerOrEqual as Pu,videoSizeToQuality as Tw,assertNotEmptyArray as Ab,assertNonNullable as Iw}from"@vkontakte/videoplayer-shared";var Iu=!1,ut={},Sb=a=>{Iu=a},vb=()=>{ut={}},yb=a=>{a(ut)},kr=(a,e)=>{var t;Iu&&(ut.meta=(t=ut.meta)!=null?t:{},ut.meta[a]=e)},ne=class{constructor(e){this.name=e}next(e){var i,r;if(!Iu)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"),wb=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var Au=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Rr=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Pb()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},kb='Assertion "ABR Tracks is empty array" failed',ws=(a,e,t,i)=>{var u;let r=[...e].sort(Au(1)),s=[...t].sort(Au(1)),n=s.filter(c=>X(c.bitrate)&&X(a.bitrate)?a.bitrate/c.bitrate>i:!0),o=(u=(0,Wt.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Wt.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,Wt.default)(n,-1):(0,Wt.default)(s,0)},xb=a=>"quality"in a,Rb=(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]&&Pb()-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=xb(o)?"video":"audio",c=xb(o)?o.quality:o.bitrate;return e({message:`
|
|
7
|
-
[last ${u} selected] ${
|
|
8
|
-
`}),o}return i==null||i.recordSwitch(t),t},
|
|
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:`
|
|
7
|
+
[last ${u} selected] ${l}
|
|
8
|
+
`}),o}return i==null||i.recordSwitch(t),t},kt=(a,{container:e,throughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,abrLogger:h})=>{var O,R,w,U,z;Pb(a,wb);let p=(O=window.devicePixelRatio)!=null?O:1,f=i.usePixelRatio?i.pixelRatioMultiplier*(p-1)+1:1,b=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*f*i.containerSizeFactor,height:e.height*f*i.containerSizeFactor},g=b&&Tw(b),y=i.considerPlaybackRate&&X(o)?o:1,I=a.filter(v=>!Tb(v.quality)).sort((v,L)=>Pu(v.quality,L.quality)?-1:1),S=(R=(0,Yt.default)(I,-1))==null?void 0:R.quality,T=(w=(0,Yt.default)(I,0))==null?void 0:w.quality,E=xu(r)||X(r.min)&&X(r.max)&&Ib(r.max,r.min)||X(r.min)&&T&&Pu(r.min,T)||X(r.max)&&S&&Ib(r.max,S),k=y*Ab(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),C={},$=I.filter(v=>{if(!(g?Au(v.quality,g):!0))return C[v.quality]="FitsContainer",!1;if(!(X(t)&&isFinite(t)&&X(v.bitrate)?t-s>=v.bitrate*k:!0))return C[v.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&X(i.minBufferToSwitchUp)&&u&&!Tb(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&Pu(v.quality,u.quality))return C[v.quality]="Buffer",!1;if(!!d&&yb(v.quality,d))return C[v.quality]="DroppedFramesLimit",!1;let ue=E||(xu(r.max)||Au(v.quality,r.max))&&(xu(r.min)||yb(v.quality,r.min)),tt=X(c)&&!c?Au(v.quality,i.backgroundVideoQualityLimit):!0;return!ue||!tt?(C[v.quality]="FitsQualityLimits",!1):!0})[0];$&&$.bitrate&&Ew.next($.bitrate);let B=(U=$!=null?$:I[Math.ceil((I.length-1)/2)])!=null?U:a[0];return B.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
11
|
${a.map(v=>`{ id: ${v.id}, quality: ${v.quality}, bitrate: ${v.bitrate} }`).join(`
|
|
12
12
|
`)}
|
|
13
13
|
|
|
14
14
|
[tuning]
|
|
15
|
-
${Object.entries(i!=null?i:{}).map(([v
|
|
15
|
+
${Object.entries(i!=null?i:{}).map(([v,L])=>`${v}: ${L}`).join(`
|
|
16
16
|
`)}
|
|
17
17
|
|
|
18
18
|
[limit params]
|
|
@@ -22,7 +22,7 @@ var Sv=Object.create;var sc=Object.defineProperty;var vv=Object.getOwnPropertyDe
|
|
|
22
22
|
playbackRate: ${o},
|
|
23
23
|
playbackRateFactor: ${y},
|
|
24
24
|
forwardBufferHealth: ${n},
|
|
25
|
-
bitrateFactor: ${
|
|
25
|
+
bitrateFactor: ${k},
|
|
26
26
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
27
27
|
droppedVideoMaxQualityLimit: ${d},
|
|
28
28
|
limitsAreInvalid: ${E},
|
|
@@ -30,12 +30,12 @@ var Sv=Object.create;var sc=Object.defineProperty;var vv=Object.getOwnPropertyDe
|
|
|
30
30
|
minQualityLimit: ${r==null?void 0:r.min},
|
|
31
31
|
|
|
32
32
|
[limited video tracks]
|
|
33
|
-
${Object.entries(
|
|
33
|
+
${Object.entries(C).map(([v,L])=>`${v}: ${L}`).join(`
|
|
34
34
|
`)||"All tracks are available"}
|
|
35
35
|
|
|
36
|
-
[best video track] ${
|
|
37
|
-
[selected video track] ${
|
|
38
|
-
`}),
|
|
36
|
+
[best video track] ${$==null?void 0:$.quality}
|
|
37
|
+
[selected video track] ${B==null?void 0:B.quality}
|
|
38
|
+
`}),kb(i,h,B,l)},Rb=(a,e,t,{throughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u})=>{var b;Pb(t,wb);let l=r.considerPlaybackRate&&X(s)?s:1,c=[...t].sort(wu(-1)),d=a.bitrate;Iw(d);let h=l*Ab(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),p,f=ks(a,e,t,r.minVideoAudioRatio);return X(i)&&isFinite(i)&&(p=c.find(g=>X(g.bitrate)&&X(f==null?void 0:f.bitrate)?i-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(`
|
|
@@ -49,20 +49,20 @@ var Sv=Object.create;var sc=Object.defineProperty;var vv=Object.getOwnPropertyDe
|
|
|
49
49
|
throughput: ${i},
|
|
50
50
|
reserve: ${d},
|
|
51
51
|
playbackRate: ${s},
|
|
52
|
-
playbackRateFactor: ${
|
|
52
|
+
playbackRateFactor: ${l},
|
|
53
53
|
forwardBufferHealth: ${n},
|
|
54
|
-
bitrateFactor: ${
|
|
54
|
+
bitrateFactor: ${h},
|
|
55
55
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
56
56
|
|
|
57
|
-
[selected audio track] ${
|
|
58
|
-
`}),h&&Rb(r,u,h,o)};var Z=a=>new URL(a).hostname;import{assertNever as Ob,assertNonNullable as Vb,combine as jw,debounce as Gw,ErrorCategory as _b,filter as Nb,filterChanged as Ww,isNonNullable as Lu,map as Ms,merge as Fb,observableFrom as Yw,once as Qw,Subscription as zw,ValueSubject as Mu,videoQualityToHeight as Kw,videoSizeToQuality as Jw}from"@vkontakte/videoplayer-shared";var Lb=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(!Lb(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{await a.play()}catch(r){return Lb(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as Rs,isNullable as Aw,assertNonNullable as Mr}from"@vkontakte/videoplayer-shared";import{isNonNullable as Mb,assertNonNullable as ks,now as xw}from"@vkontakte/videoplayer-shared";function ee(){return xw()}function wu(a){return ee()-a}function ku(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 c=n.indexOf("?")>-1?"&":"?";return u&&(n+=c+"lowLat=1",c="&"),o&&(n+=c+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Cb(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function Li(a,e,t,i){let r=window.XMLHttpRequest,s,n,o,u=!1,c=0,l,d,p=!1,h="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;ks(l);let w=wu(l),k;if(w<b){k=b-w,setTimeout(g,k);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new r,R()},y=w=>(s=w,_),I=w=>(d=w,_),S=()=>(h="json",_),T=()=>{if(!u){if(--c>=0){g(),i&&i();return}u=!0,d&&d(),t&&t()}},E=w=>(p=w,_),R=()=>{l=ee(),n=new r,n.open("get",a);let w=0,k,q=0,z=()=>(ks(l),Math.max(l,Math.max(k||0,q||0)));if(s&&n.addEventListener("progress",v=>{let $=ee();s.updateChunk&&v.loaded>w&&(s.updateChunk(z(),v.loaded-w),w=v.loaded,k=$)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>T())),n.addEventListener("load",()=>{if(u)return;ks(n);let v=n.status;if(v>=200&&v<300){if(n.response.byteLength&&s){let $=n.response.byteLength-w;$&&s.updateChunk&&s.updateChunk(z(),$)}n.responseType==="json"&&!Object.values(n.response).length?T():(d&&d(),e(n.response))}else T()}),n.addEventListener("error",()=>{T()}),p){let v=()=>{ks(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(q=ee(),n.removeEventListener("readystatechange",v))};n.addEventListener("readystatechange",v)}return n.responseType=h,n.send(),_},_={withBitrateReporting:y,withParallel:E,withJSONResponse:S,withRetryCount:w=>(c=w,_),withRetryInterval:(w,k)=>(Mb(w)&&(b=w),Mb(k)&&(f=k),_),withTimeout:w=>(o=w,_),withFinally:I,send:R,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return _}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=Li(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 $s=1e4,Ru=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=ku(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=ku(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,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||Rs(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=()=>{Cb(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(Ru,$s,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,c=null,l=!1,d=()=>{let T=s&&(!l||l===this.rep);return T||t("Not running!"),T},p=(T,E,R)=>{u&&u.abort(),u=Li(this.urlResolver.resolve(T,!1),E,R,()=>this._retryCallback()).withTimeout($s).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ru).withFinally(()=>{u=null}).send()},h=(T,E,R)=>{Mr(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(T,!1),E,R,()=>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 R=ee()-1e4,M=0;for(let D=0;D<this.bufferStates.length;D++){let O=this.bufferStates[D];T=Math.min(T,O.buf),O.ts<R&&M++}this.bufferStates.splice(0,M),t(`update playback rate; minBuffer=${T} drop=${M} jitter=${this.sourceJitter}`);let C=T-$w;this.sourceJitter>=0?C-=this.sourceJitter/2:this.sourceJitter-=1,C>3?f(1.15):C>1?f(1.1):C>.3?f(1.05):f(1)}},y=T=>{let E,R=()=>E&&E.start?E.start.length:0,M=v=>E.start[v]/1e3,C=v=>E.dur[v]/1e3,D=v=>E.fragIndex+v,O=(v,$)=>({chunkIdx:D(v),startTS:M(v),dur:C(v),discontinuity:$}),_=()=>{let v=0;if(E&&E.dur){let $=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,H=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,G=$;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 O(v,!0)},w=v=>{let $=R();if(!($<=0)){if(Rs(v)){for(let H=0;H<$;H++)if(M(H)>v)return O(H)}return _()}},k=v=>{let $=R(),H=v?v.chunkIdx+1:0,G=H-E.fragIndex;if(!($<=0)){if(!v||G<0||G-$>Rw)return t(`Resync: offset=${G} bChunks=${$} chunk=`+JSON.stringify(v)),_();if(!(G>=$))return O(H-E.fragIndex,!1)}},q=(v,$,H)=>{c&&c.abort(),c=Li(this.urlResolver.resolve(v,!0,this.lowLatency),$,H,()=>this._retryCallback()).withTimeout($s).withRetryCount(Ru).withFinally(()=>{c=null}).withJSONResponse().send()};return{seek:(v,$)=>{q(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(w($))},()=>this._handleNetworkError())},nextChunk:k}},I=()=>{s=!1,o&&o.abort(),u&&u.abort(),c&&c.abort(),Mr(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:T=>{let{videoElement:E,logger:R}=this.params,M=y(e.jidxUrl),C,D,O,_,w=0,k,q,z,v=()=>{k&&(clearTimeout(k),k=void 0);let A=Math.max(Lw,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),le=w+A,Ie=ee(),we=Math.min(1e4,le-Ie);w=Ie;let mt=()=>{c||d()&&M.seek(()=>{d()&&(w=ee(),$(),v())})};we>0?k=window.setTimeout(()=>{this.paused?v():mt()},we):mt()},$=()=>{let A;for(;A=M.nextChunk(_);)_=A,tt(A);let le=M.nextChunk(O);if(le){if(O&&le.discontinuity){R("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,we,mt,ai=bt=>{window.setTimeout(()=>{d()&&H(A,le)},bt)};if(this.sourceBuffer.updating)R("Source buffer is updating; delaying appendBuffer"),ai(100);else{let bt=ee(),Ct=E.currentTime;!this.paused&&E.buffered.length>1&&q===Ct&&bt-z>500&&(R("Stall suspected; trying to fix"),this._fixupStall()),q!==Ct&&(q=Ct,z=bt);let si=this._getBufferSizeSec();if(si>30)R(`Buffered ${si} seconds; delaying appendBuffer`),ai(2e3);else try{this.sourceBuffer.appendBuffer(A),this.videoPlayStarted?(this.bufferStates.push({ts:bt,buf:si}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),le&&le()}catch(Yi){if(Yi.name==="QuotaExceededError")R("QuotaExceededError; delaying appendBuffer"),mt=this.sourceBuffer.buffered.length,mt!==0&&(Ie=this.sourceBuffer.buffered.start(0),we=Ct,we-Ie>4&&this.sourceBuffer.remove(Ie,we-3)),ai(1e3);else throw Yi}}},G=()=>{D&&C&&(R([`Appending chunk, sz=${D.byteLength}:`,JSON.stringify(O)]),H(D,function(){D=null,$()}))},K=A=>e.fragUrlTemplate.replace("%%id%%",A.chunkIdx),ue=A=>{d()&&h(K(A),(le,Ie)=>{if(d()){if(Ie/=1e3,D=le,O=A,n=A.startTS,Ie){let we=Math.min(10,A.dur/Ie);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*we:we}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,()=>{C=!0,G()}))};s=!0,M.seek(A=>{if(d()){if(w=ee(),!A){v();return}_=A,!Aw(T)||A.startTS>T?ue(A):(O=A,$())}},T),e.cachedHeader?ft(e.cachedHeader):p(e.headerUrl,ft,()=>this._handleNetworkError())},stop:I,getTimestampSec:()=>n},l}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),Rs(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 Rs(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=d=>{if(!this.autoQuality)return;let p,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),f=d/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let f=ee();if(this.chunkRateEstimator.addInterval(p,f,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,c=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&wu(n)<3e4)return;i(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&c(),h},notifySwitch:d=>{let p=ee();d<o&&(n=p),o=d}}}_fetchManifest(e,t,i){this.manifestRequest=Li(this.urlResolver.resolve(e,!0),t,i,()=>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:i,videoElement:r}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,c)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=c,o.push(u))}),o.sort(function(u,c){return u.video&&c.video?c.video.height-u.video.height:c.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 Db,fromEvent as Cw,interval as Dw,isHigher as Bw,isInvariantQuality as Ow,isLower as Vw,merge as _w,Subject as Bb,Subscription as Nw}from"@vkontakte/videoplayer-shared";var $u=class{constructor(){this.onDroopedVideoFramesLimit$=new Bb;this.subscription=new Nw;this.playing=!1;this.tracks=[];this.forceChecker$=new Bb;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(Db(()=>this.playing),Db(()=>{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}},Ls=$u;import{map as Fw,Observable as qw}from"@vkontakte/videoplayer-shared";import{fromEvent as Uw}from"@vkontakte/videoplayer-shared";var Dr=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var Hw=(a,e)=>new qw(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=Uw(document,"visibilitychange").pipe(Fw(n=>!document.hidden||Dr())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe}}),Be=Hw;var Xw=["paused","playing","ready"],Zw=["paused","playing","ready"],Br=class{constructor(e){this.subscription=new zw;this.videoState=new L("stopped");this.representations$=new Mu([]);this.textTracksManager=new Ce;this.droppedFramesManager=new Ls;this.maxSeekBackTime$=new Mu(1/0);this.zeroTime$=new Mu(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:_b.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let c=(t=u.name)!=null?t:u.index.toString(10),l=(i=At(u.name))!=null?i:Jw(u.video),d=u.bitrate/1e3,p={...u.video};if(!l)continue;let h={id:c,quality:l,bitrate:d,size:p};o.push({track:h,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),Lu(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(te(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(te(this.params.source.url,u))}return;default:return Ob(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:_b.WTF,message:"DashLiveProvider internal logic error",thrown:r})};Fb(this.videoState.stateChangeStarted$.pipe(Ms(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Ms(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(Ms(r=>r.map(({track:s})=>s)),Nb(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(),Ms(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(jw({zeroTime:this.zeroTime$.pipe(Nb(Lu)),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(Me(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(Be(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 Ob(r.to)}},t)).add(Fb(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 c,l,d,p,h,f;let e=this.representations$.getValue(),t=(l=(c=this.params.desiredState.videoTrack.getTransition())==null?void 0:c.to)!=null?l:this.params.desiredState.videoTrack.getState(),i=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&Lu(t)?t:wt(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=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.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;Vb(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;Vb(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(te(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var qb=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 ol,filter as hS,filterChanged as ul,fromEvent as MR,isNonNullable as CR,map as fS,merge as sn,observableFrom as DR,observeElementSize as BR,once as mS,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,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}},Mi=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)}},Or=class{constructor(){Object.defineProperty(this,"signal",{value:new Mi,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",Mi.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 Cu(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!Ds({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(c,l){let d;l&&l.signal&&(d=l.signal,delete l.signal);let p=new t(c,l);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,c)=>{let l=s&&s.prototype.isPrototypeOf(u)?u.signal:c?c.signal:void 0;if(l){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(l.aborted)return Promise.reject(d);let p=new Promise((h,f)=>{l.addEventListener("abort",()=>f(d),{once:!0})});return c&&c.signal&&delete c.signal,Promise.race([p,n(u,c)])}return n(u,c)},Request:s}}var Vr=Ds({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Ub=Vr?Cu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,lt=Vr?Ub.fetch:window.fetch,FB=Vr?Ub.Request:window.Request,je=Vr?Or:window.AbortController,qB=Vr?Mi:window.AbortSignal;var Hs=ze(wr(),1);var ct=()=>window.ManagedMediaSource||window.MediaSource,Bs=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Hb=()=>{var a,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},jb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Gs,clientChecker as js}from"@vkontakte/videoplayer-shared";var Oe=document.createElement("video"),ik='video/mp4; codecs="avc1.42000a,mp4a.40.2"',rk='video/mp4; codecs="hev1.1.6.L93.B0"',tg='video/webm; codecs="vp09.00.10.08"',ig='video/webm; codecs="av01.0.00M.08"',ak='audio/mp4; codecs="mp4a.40.2"',sk='audio/webm; codecs="opus"',Gb,Wb,Yt={mms:Bs(),mse:Hb(),hls:!!((Gb=Oe.canPlayType)!=null&&Gb.call(Oe,"application/x-mpegurl")||(Wb=Oe.canPlayType)!=null&&Wb.call(Oe,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Yb,Qb,ge={mp4:!!((Yb=Oe.canPlayType)!=null&&Yb.call(Oe,"video/mp4")),webm:!!((Qb=Oe.canPlayType)!=null&&Qb.call(Oe,"video/webm")),cmaf:!0},Vs,zb,_s,Kb,Ns,Jb,Fs,Xb,qs,Zb,Us,eg,Se={h264:!!((zb=(Vs=ct())==null?void 0:Vs.isTypeSupported)!=null&&zb.call(Vs,ik)),h265:!!((Kb=(_s=ct())==null?void 0:_s.isTypeSupported)!=null&&Kb.call(_s,rk)),vp9:!!((Jb=(Ns=ct())==null?void 0:Ns.isTypeSupported)!=null&&Jb.call(Ns,tg)),av1:!!((Xb=(Fs=ct())==null?void 0:Fs.isTypeSupported)!=null&&Xb.call(Fs,ig)),aac:!!((Zb=(qs=ct())==null?void 0:qs.isTypeSupported)!=null&&Zb.call(qs,ak)),opus:!!((eg=(Us=ct())==null?void 0:Us.isTypeSupported)!=null&&eg.call(Us,sk))},Ci=(Se.h264||Se.h265)&&Se.aac,Qt,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:ig}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:tg}})]);Qt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{nk()}catch(a){console.error(a)}var Di=Yt.hls&&ge.mp4,rg=()=>Object.keys(Se).filter(a=>Se[a]),ag=(a,e=!1,t=!1)=>{let i=Yt.mse||Yt.mms&&t;return a.filter(r=>{switch(r){case"DASH_SEP":return i&&ge.mp4&&Ci;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&&Ci||ge.webm&&(Se.vp9||Se.av1)&&(Se.opus||Se.aac));case"DASH_LIVE":return Yt.mse&&ge.mp4&&Ci;case"DASH_LIVE_CMAF":return i&&ge.mp4&&Ci&&ge.cmaf;case"DASH_ONDEMAND":return i&&ge.mp4&&Ci;case"HLS":case"HLS_ONDEMAND":return Di||e&&Yt.mse&&ge.mp4&&Ci;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Di;case"MPEG":return ge.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Yt.webrtc&&Yt.ws&&Se.h264&&(ge.mp4||ge.webm);default:return Gs(r)}})},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 Qt?Qt[t].smooth?[t,e]:Qt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Qt?Qt[t].powerEfficient?[t,e]:Qt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Gs(a)}return[e,t]},sg=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...Os(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(js.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",...Os(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Os(a),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Os(a),...r,"HLS","HLS_ONDEMAND"];default:Gs(e)}return Di?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},ng=({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=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 Di&&!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"]},Du=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],og=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 i=(0,Hs.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,Hs.default)(e.value.split("."),0)};import{ErrorCategory as _r}from"@vkontakte/videoplayer-shared";var ug=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 Bi=(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 rl,assertNonNullable as ii,clientChecker as SR,combine as Zs,ErrorCategory as pt,filter as al,filterChanged as oS,flattenObject as ma,fromEvent as Ui,getTraceSubscriptionMethod as vR,interval as sl,isNonNullable as uS,map as nl,merge as Hi,now as yR,Subject as lS,Subscription as cS,tap as TR,throttle as IR,ValueSubject as ie}from"@vkontakte/videoplayer-shared";var Fi=ze(wr(),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),lg=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),cg=!lg(window.requestIdleCallback)||!lg(window.cancelIdleCallback),Bu=cg?ok:window.requestIdleCallback,tO=cg?uk:window.cancelIdleCallback;var eS=ze(xs(),1);import{assertNever as lk,ErrorCategory as dg,clientChecker as Ou,Subject as pg}from"@vkontakte/videoplayer-shared";var ck=16,hg=!1;try{hg=Ou.isSafari&&!!Ou.macVersion&&Ou.macVersion<=ck}catch(a){console.error(a)}var Vu=class{constructor(e){this.bufferFull$=new pg;this.error$=new pg;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:dg.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;hg&&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:dg.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)}}},fg=Vu;var _u=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 Xt,assertNonNullable as ve,ErrorCategory as Zt,fromEvent as Xu,getExponentialDelay as Zu,isNonNullable as oa,isNullable as ye,now as Qs,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 Oi=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 qr=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ur=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 zt=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,c=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:c})}}};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:qr,moof:Ur,mdat:Hr,sidx:zt,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:Oi},Kt=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 Oi(t,new a)}};var Vi=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 zt(a,new Kt),t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,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 Kt().parse(a),r=new Vi(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],c=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,c,d)},Sk=(a,e)=>{let i=new Kt().parse(a),s=new Vi(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"),c=0;return u.sampleDuration.length?c=u.sampleDuration.reduce((d,p)=>d+p,0):c=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+c)/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 Kt().parse(a),r=new Vi(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},mg={validateData:mk,parseInit:vk,getIndexRange:()=>{},parseSegments:bk,parseFeedableSegmentChunk:gk,getSegmentEndTime:Sk};import{assertNonNullable as Fu,isNonNullable as vg,isNullable as Tk}from"@vkontakte/videoplayer-shared";import{assertNever as yk}from"@vkontakte/videoplayer-shared";var bg={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"}},gg=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 bg,s=r?bg[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),c=n&255>>o,l=aa(u),d=c*2**((o-1)*8)+l,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},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},Ge=(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)}},Jt=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=gg(i);if(!e(r))return;r.type==="master"&&Jt(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},Sg=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=gg(a);return Jt(r.value,({tag:s,type:n,value:o})=>(s===17143?e=Ge(o,n):s===17026?t=Ge(o,n):s===17029&&(i=Ge(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var yg=[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,c,l=!1,d=0;return Jt(a,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=Ge(f,h);c=aa(g)}else p!==21420&&(c=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?i=Ge(f,h):p===17545?r=Ge(f,h):p===21420&&c===475249515?u=Ge(f,h):p===374648427?Jt(f,({tag:g,type:y,value:I})=>g===30321?(l=Ge(I,y)===1,!1):!0):s&&n&&yg.includes(p)&&(o=!0),!o}),Fu(e,"Failed to parse webm Segment start"),Fu(t,"Failed to parse webm Segment end"),Fu(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:l,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=>vg(o.time)&&vg(o.position),s=[],n;return Jt(a,({tag:o,type:u,value:c})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=Ge(c,u));break;case 183:break;case 241:n&&(n.position=Ge(c,u));break;default:t&&yg.includes(o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((o,u)=>{let{time:c,position:l}=o,d=s[u+1];return{status:"none",time:{from:c,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},Ak=a=>{let e=0,t=!1;try{Jt(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},Tg={validateData:Sg,parseInit:Ek,getIndexRange:xk,parseSegments:Pk,parseFeedableSegmentChunk:Ak};var _i=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Tg;case"mp4":return mg}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Yu=ze(Hg(),1);var Wu=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 Wg,isNullable as Yg}from"@vkontakte/videoplayer-shared";var jg=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Gg=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(c=>{s[c[0]]=c.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 c=o[u];(typeof c=="undefined"||c==="")&&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})+",l=`^(?:(?<langtag>${`
|
|
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>${`
|
|
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(l,"i")}var Qg=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,Yu.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,Yu.default)(t,n,(o,u)=>Yg(s)?o:Yg(u)?s:s.padStart(parseInt(u,10),"0"))}return t},zg=(a,e)=>{var T,E,R,M,C,D,O,_,w,k,q,z,v,$,H,G,K,ue,tt,ft,A,le,Ie,we,mt,ai,bt,Ct,si,Yi,xl,Pl,Al,wl,kl,Rl,$l,Ll,Ml,Cl,Dl,Bl,Ol,Vl,_l,Nl,Fl,ql,Ul,Hl,jl,Gl,Wl,Yl,Ql,zl,Kl,Jl,Xl,Zl,ec,tc,ic;let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=s.getElementsByTagName("Period")[0],o=(R=(E=(T=s.querySelector("BaseURL"))==null?void 0:T.textContent)==null?void 0:E.trim())!=null?R:"",u=n.children,c=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),d=l?new Date(l).getTime():void 0,p,h=s.getAttribute("mediaPresentationDuration"),f=n.getAttribute("duration"),b=s.getElementsByTagName("vk:Attrs")[0],g=b==null?void 0:b.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=Qg(h);else if(f){let re=Qg(f);Wg(re)&&(p=re)}else g&&(p=parseInt(g,10));let y=0,I=(C=(M=s.getAttribute("profiles"))==null?void 0:M.split(","))!=null?C:[];for(let re of u){let nv=(D=re.getAttribute("id"))!=null?D:"id"+(y++).toString(10),Qi=(O=re.getAttribute("mimeType"))!=null?O:"",yn=(_=re.getAttribute("codecs"))!=null?_:"",Tn=(w=re.getAttribute("contentType"))!=null?w:Qi==null?void 0:Qi.split("/")[0],ov=(q=(k=re.getAttribute("profiles"))==null?void 0:k.split(","))!=null?q:[],rc=(v=Gg((z=re.getAttribute("lang"))!=null?z:""))!=null?v:{},uv=(K=(G=(H=($=re.querySelector("Label"))==null?void 0:$.textContent)==null?void 0:H.trim())!=null?G:re.getAttribute("label"))!=null?K:void 0,lv=re.querySelectorAll("Representation"),cv=re.querySelector("SegmentTemplate"),dv=(tt=(ue=re.querySelector("Role"))==null?void 0:ue.getAttribute("value"))!=null?tt:void 0,zi=Tn,J={id:nv,language:rc.language,isDefault:dv==="main",label:uv,codecs:yn,hdr:zi==="video"&&Wu(yn),mime:Qi,representations:[]};for(let j of lv){let pv=(ft=j.getAttribute("lang"))!=null?ft:void 0,hv=(A=j.getAttribute("label"))!=null?A:void 0,fv=(we=(Ie=(le=j.querySelector("BaseURL"))==null?void 0:le.textContent)==null?void 0:Ie.trim())!=null?we:"",Ra=new URL(fv||o,e).toString(),ni=(mt=j.getAttribute("mimeType"))!=null?mt:Qi,$a=(bt=(ai=j.getAttribute("codecs"))!=null?ai:yn)!=null?bt:"",La;if(Tn==="text"){let gt=j.getAttribute("id")||"",Ma=((Ct=rc.privateuse)==null?void 0:Ct.includes("x-auto"))||gt.includes("_auto"),Dt=j.querySelector("SegmentTemplate");if(Dt){let Ki={representationId:(si=j.getAttribute("id"))!=null?si:void 0,bandwidth:(Yi=j.getAttribute("bandwidth"))!=null?Yi:void 0},Ca=parseInt((xl=j.getAttribute("bandwidth"))!=null?xl:"",10)/1e3,Da=(Al=parseInt((Pl=Dt.getAttribute("startNumber"))!=null?Pl:"",10))!=null?Al:1,oi=parseInt((wl=Dt.getAttribute("timescale"))!=null?wl:"",10),In=(kl=Dt.querySelectorAll("SegmentTimeline S"))!=null?kl:[],ui=Dt.getAttribute("media");if(!ui)continue;let Ba=[],Oa=0,Va="",li=0,Ji=Da,ae=0;for(let _e of In){let Bt=parseInt((Rl=_e.getAttribute("d"))!=null?Rl:"",10),ke=parseInt(($l=_e.getAttribute("r"))!=null?$l:"",10)||0,St=parseInt((Ll=_e.getAttribute("t"))!=null?Ll:"",10);ae=Number.isFinite(St)?St:ae;let Ot=Bt/oi*1e3,vt=ae/oi*1e3;for(let Ye=0;Ye<ke+1;Ye++){let yt=dt(ui,{...Ki,segmentNumber:Ji.toString(10),segmentTime:(ae+Ye*Bt).toString(10)}),ci=(vt!=null?vt:0)+Ye*Ot,Zi=ci+Ot;Ji++,Ba.push({time:{from:ci,to:Zi},url:yt})}ae+=(ke+1)*Bt,Oa+=(ke+1)*Ot}li=ae/oi*1e3,Va=dt(ui,{...Ki,segmentNumber:Ji.toString(10),segmentTime:ae.toString(10)});let Xi={time:{from:li,to:1/0},url:Va},it={type:"template",baseUrl:Ra,segmentTemplateUrl:ui,initUrl:"",totalSegmentsDurationMs:Oa,segments:Ba,nextSegmentBeyondManifest:Xi,timescale:oi};La={id:gt,kind:"text",segmentReference:it,profiles:[],duration:p,bitrate:Ca,mime:"",codecs:"",width:0,height:0,isAuto:Ma}}else La={id:gt,isAuto:Ma,kind:"text",url:Ra}}else{let gt=(Cl=(Ml=j.getAttribute("contentType"))!=null?Ml:ni==null?void 0:ni.split("/")[0])!=null?Cl:Tn,Ma=(Bl=(Dl=re.getAttribute("profiles"))==null?void 0:Dl.split(","))!=null?Bl:[],Dt=parseInt((Ol=j.getAttribute("width"))!=null?Ol:"",10),Ki=parseInt((Vl=j.getAttribute("height"))!=null?Vl:"",10),Ca=parseInt((_l=j.getAttribute("bandwidth"))!=null?_l:"",10)/1e3,Da=(Nl=j.getAttribute("frameRate"))!=null?Nl:"",oi=(Fl=j.getAttribute("quality"))!=null?Fl:void 0,In=Da?jg(Da):void 0,ui=(ql=j.getAttribute("id"))!=null?ql:"id"+(y++).toString(10),Ba=gt==="video"?`${Ki}p`:gt==="audio"?`${Ca}Kbps`:$a,Oa=`${ui}@${Ba}`,Va=[...I,...ov,...Ma],li,Ji=j.querySelector("SegmentBase"),ae=(Ul=j.querySelector("SegmentTemplate"))!=null?Ul:cv;if(Ji){let it=(jl=(Hl=j.querySelector("SegmentBase Initialization"))==null?void 0:Hl.getAttribute("range"))!=null?jl:"",[_e,Bt]=it.split("-").map(yt=>parseInt(yt,10)),ke={from:_e,to:Bt},St=(Gl=j.querySelector("SegmentBase"))==null?void 0:Gl.getAttribute("indexRange"),[Ot,vt]=St?St.split("-").map(yt=>parseInt(yt,10)):[],Ye=St?{from:Ot,to:vt}:void 0;li={type:"byteRange",url:Ra,initRange:ke,indexRange:Ye}}else if(ae){let it={representationId:(Wl=j.getAttribute("id"))!=null?Wl:void 0,bandwidth:(Yl=j.getAttribute("bandwidth"))!=null?Yl:void 0},_e=parseInt((Ql=ae.getAttribute("timescale"))!=null?Ql:"",10),Bt=(zl=ae.getAttribute("initialization"))!=null?zl:"",ke=ae.getAttribute("media"),St=(Jl=parseInt((Kl=ae.getAttribute("startNumber"))!=null?Kl:"",10))!=null?Jl:1,Ot=dt(Bt,it);if(!ke)throw new ReferenceError("No media attribute in SegmentTemplate");let vt=(Xl=ae.querySelectorAll("SegmentTimeline S"))!=null?Xl:[],Ye=[],yt=0,ci="",Zi=0;if(vt.length){let _a=St,Ne=0;for(let di of vt){let Qe=parseInt((Zl=di.getAttribute("d"))!=null?Zl:"",10),Vt=parseInt((ec=di.getAttribute("r"))!=null?ec:"",10)||0,Na=parseInt((tc=di.getAttribute("t"))!=null?tc:"",10);Ne=Number.isFinite(Na)?Na:Ne;let En=Qe/_e*1e3,xn=Ne/_e*1e3;for(let Fa=0;Fa<Vt+1;Fa++){let bv=dt(ke,{...it,segmentNumber:_a.toString(10),segmentTime:(Ne+Fa*Qe).toString(10)}),ac=(xn!=null?xn:0)+Fa*En,gv=ac+En;_a++,Ye.push({time:{from:ac,to:gv},url:bv})}Ne+=(Vt+1)*Qe,yt+=(Vt+1)*En}Zi=Ne/_e*1e3,ci=dt(ke,{...it,segmentNumber:_a.toString(10),segmentTime:Ne.toString(10)})}else if(Wg(p)){let Ne=parseInt((ic=ae.getAttribute("duration"))!=null?ic:"",10)/_e*1e3,di=Math.ceil(p/Ne),Qe=0;for(let Vt=1;Vt<di;Vt++){let Na=dt(ke,{...it,segmentNumber:Vt.toString(10),segmentTime:Qe.toString(10)});Ye.push({time:{from:Qe,to:Qe+Ne},url:Na}),Qe+=Ne}Zi=Qe,ci=dt(ke,{...it,segmentNumber:di.toString(10),segmentTime:Qe.toString(10)})}let mv={time:{from:Zi,to:1/0},url:ci};li={type:"template",baseUrl:Ra,segmentTemplateUrl:ke,initUrl:Ot,totalSegmentsDurationMs:yt,segments:Ye,nextSegmentBeyondManifest:mv,timescale:_e}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!gt||!ni)continue;let Xi={video:"video",audio:"audio",text:"text"}[gt];if(!Xi)continue;zi||(zi=Xi),La={id:Oa,kind:Xi,segmentReference:li,profiles:Va,duration:p,bitrate:Ca,mime:ni,codecs:$a,width:Dt,height:Ki,fps:In,quality:oi}}J.language||(J.language=pv),J.label||(J.label=hv),J.mime||(J.mime=ni),J.codecs||(J.codecs=$a),J.hdr||(J.hdr=zi==="video"&&Wu($a)),J.representations.push(La)}zi&&r[zi].push(J)}return{dynamic:c,liveAvailabilityStartTime:d,duration:p,streams:r}};var sa=ze(wr(),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?At(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}),Ws=(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}),Ku=({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}),Ju=({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)}),Ys=a=>"url"in a,Ve=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:c}){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 je;this.switchAbortController=new je;this.destroyAbortController=new je;this.bufferLimit=1/0;this.failedDownloads=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Xt(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 fg(this.sourceBuffer),this.subscription.add(Xu(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Zt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Zt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Xu(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Zt.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,_u(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let c=Ze(this.sourceBuffer.buffered,o),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,n*2,c<l)}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=Xt(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=Xt(this.destroyAbortController.signal,async function*(e){var u,c;let t=(u=e==null?void 0:e.flatMap(l=>l.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let l of this.representations.keys()){let d=t.find(f=>f.id===l);d&&this.representations.set(l,d);let p=this.representations.get(l);if(!p||!Ve(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let i=(c=this.switchingToRepresentationId)!=null?c: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));this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(c!=null&&c.dynamic),this.resetAccumulateBufferAfterStall(),this.startAccumulateBuffer(),this.initData=new Map(i.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(l=>[l.id,l])),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 je,Xt(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 je,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var c,l;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(((c=r==null?void 0:r.time.to)!=null?c:0)-((l=r==null?void 0:r.time.from)!=null?l:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=Ze(this.sourceBuffer.buffered,e),h=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=r.time.to-e+100&&(s=h)}if(isFinite(this.bufferLimit)&&_u(this.sourceBuffer.buffered)>=this.bufferLimit){let d=Ze(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<p);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 p=(0,Fi.default)(o,0);p&&p.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,Fi.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||!Ve(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),c=(r=this.segments.get(o.id))!=null?r:[],l=(n=(s=(0,Fi.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,d=u==null?void 0:u.findIndex(p=>Math.floor(l)>=Math.floor(p.time.from)&&Math.floor(l)<=Math.floor(p.time.to));if(d===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(d+1);this.segments.set(o.id,[...c,...p])}}}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(!Ve(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),c=dt(r.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}}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:p,to:h}},f)=>{let b=p<=i&&h>=i,g=p>i||b||f===0&&i===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),I=this.preloadOnly&&p<=i+y||h<=i+y;return(d==="none"||d==="partially_ejected"&&g&&I&&this.sourceBuffer&&!(Bi(this.sourceBuffer.buffered,p)&&Bi(this.sourceBuffer.buffered,h)))&&g&&I});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+1);let s=e,n=0,o=0,u=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let d=r;d<s.length&&(n<=c||o<=l);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,i="auto"){Ve(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:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Xt(o,async function*(){let l=Zu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,l))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let l=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=Qs(),!l)return;let d=new DataView(l);if(!isFinite(r.segment.time.to)){let p=t.segmentReference.timescale,h=_i(t.mime);r.segment.time.to=h.getSegmentEndTime(d,p)}u&&r.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(d,o),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(l){this.abortActiveSegments([e]),na(l)||this.failedDownloads++}}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 Xt(n,async function*(){let u=Zu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,u),Xu(window,"online").pipe(uR()).subscribe(()=>{c(),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=Qs(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),na(u)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(Ve(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Fi.default)(e,0).byte.from,to:(0,Fi.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Qs(),this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:Zt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ve(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?(c,l)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Qs();let d=this.onSomeTemplateDataLoaded({dataView:c,loaded:l,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Zt.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 c=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),l=_i(n.mime).parseFeedableSegmentChunk(c,this.isLive);l!=null&&l.byteLength&&(u.status="partially_fed",o.feedingBytes+=l.byteLength,await this.sourceBufferTaskQueue.append(l),o.fedBytes+=l.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,c=e.byteLength;for(let l of this.activeSegments){let{segment:d}=l,p=u==="byteRange",h=p?d.byte.to-d.byte.from+1:c;if(l.representationId!==t||!(!p||d.byte.from>=i&&d.byte.to<i+e.byteLength))continue;if(s.aborted){n();continue}let b=p?d.byte.from-i:0,g=p?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,h),T=this.getCurrentPosition();oa(T)&&(this.bufferAccumulation.accumulatedBufferSizeMs=d.time.to-T,this.bufferAccumulation.accumulated.push({segmentView:S,segmentProgress:l}),this.activeSegments.delete(l));let E=({segmentView:R,segmentProgress:M})=>this.sourceBufferTaskQueue.append(R,s).then(C=>C&&!s.aborted?this.onSegmentFullyAppended(M,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:l}),this.resetAccumulateBufferAfterStall())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&y&&!I&&(l.loadedBytes=Math.min(h,r-b),l.loadedBytes>l.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+b+l.feedingBytes,l.loadedBytes-l.feedingBytes),T=l.loadedBytes===h?S:_i(o.mime).parseFeedableSegmentChunk(S);T!=null&&T.byteLength&&(d.status="partially_fed",l.feedingBytes+=T.byteLength,this.sourceBufferTaskQueue.append(T,s).then(E=>{if(s.aborted)n();else if(E)l.fedBytes+=T.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t);else{if(l.feedingBytes<h)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:c}=u;if(u.representationId!==t)continue;if(s.aborted){n();continue}let l=c.byte.from-i,d=c.byte.to-i,p=d-l+1,h=l<r,f=d<=r;if(h){if(c.status==="downloading"&&f){c.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+l,p);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(u.loadedBytes=Math.min(p,r-l),u.loadedBytes>u.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+l+u.feedingBytes,u.loadedBytes-u.feedingBytes),g=u.loadedBytes===p?b:_i(o.mime).parseFeedableSegmentChunk(b);g!=null&&g.byteLength&&(c.status="partially_fed",u.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(u.fedBytes+=g.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):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",Ys(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=Bu(()=>(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?Xt(this.destroyAbortController.signal,async function*(){let o=Zu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,_i(e.mime),r)).then(async o=>{if(!o)return;let{init:u,dataView:c,segments:l}=o,d=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);this.initData.set(e.id,d);let p=l;this.isLive&&Ve(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Zt.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((l,d)=>l.from-d.from);let c=[u[0]];for(let l=1;l<u.length;l++){let{from:d,to:p}=u[l],h=c[c.length-1];h.to>=d?h.to=Math.max(h.to,p):c.push(u[l])}return c},o=u=>{var l;if(s>=t)return r;r.push({...u.time}),r=n(r);let c=Ys(u)?(l=u.size)!=null?l:0:u.byte.to-u.byte.from;s+=c};for(let u of this.segments.values())for(let c of u){let l=c.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=c.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||d)&&c.status==="fed"&&o(c)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let c=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)["none","partially_ejected"].includes(h.status)&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(l)&&d++;if(d===this.segments.size){let p={time:{from:c,to:l},url:"",status:"none"};o(p)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let l of c)l.time.from>=e+u&&l.status==="fed"&&o(l)}return r.length?(await Promise.all(r.map(c=>this.sourceBufferTaskQueue.remove(c.from,c.to)))).reduce((c,l)=>c||l,!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=c=>{var d;s=Math.min(s,c.time.from),n=Math.max(n,c.time.to);let l=Ys(c)?(d=c.size)!=null?d:0:c.byte.to-c.byte.from;r+=l};for(let c of this.segments.values())for(let l of c){if(l.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;l.status==="fed"&&u(l)}if(o=isFinite(s)&&isFinite(n),!o){r=0,s=1/0,n=-1/0;for(let c of this.segments.values())for(let l of c){if(l.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;l.status==="fed"&&u(l)}}if(o=isFinite(s)&&isFinite(n),!o)for(let c=0;c<this.sourceBuffer.buffered.length;c++){let l=this.sourceBuffer.buffered.start(c)*1e3,d=this.sourceBuffer.buffered.end(c)*1e3;for(let p of this.segments.values())for(let h of p)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(d)){s=l,n=d;break}}if(o=isFinite(s)&&isFinite(n),!o&&i){r=0,s=1/0,n=-1/0;let c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let d of l)d.time.from>e+c&&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=Bu(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Zt.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(l=>l.from-t<=n&&l.to+t>=o),c=e.filter(l=>n>=l.from&&n<l.to-t||o>l.from+t&&o<=l.to);u||(c.length===1?r.status="partially_ejected":this.gaps.some(l=>l.from===r.time.from||l.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 el,flattenObject as qi}from"@vkontakte/videoplayer-shared";var zs=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1}){this.lastConnectionType$=new el(void 0);this.lastConnectionReused$=new el(void 0);this.lastRequestFirstBytes$=new el(void 0);this.abortAllController=new je;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",qi({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",qi({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 _,w;let c=e,l=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{l.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let k=new URL(c,location.href);k.searchParams.append("bytes",`${i.from}-${i.to}`),c=k.toString();break}default:iS(t)}this.requestQuic&&(c=ca(c));let p=this.abortAllController.signal,h;if(n){let k=new je;if(h=dR(rS(this.abortAllController.signal,"abort"),rS(n,"abort")).subscribe(()=>{try{k.abort()}catch(q){ha(q)}}),this.abortAllController.signal.aborted||n.aborted)try{k.abort()}catch(q){ha(q)}p=k.signal}let f=pa();d.log("startRequest",qi({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:f}));let b=yield lt(c,{priority:s,headers:l,signal:p}).catch(ha),g=pa();if(!b)return d.error("error",{message:"No response in request"}),d.end(),h==null||h.unsubscribe(),null;if((_=this.throughputEstimator)==null||_.addRawRtt(g-f),!b.ok||!b.body){h==null||h.unsubscribe();let k=`Fetch error ${b.status}: ${b.statusText}`;return d.error("error",{message:k}),d.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!r&&!o){h==null||h.unsubscribe();let k=pa(),q={requestStartedAt:f,requestEndedAt:k,duration:k-f};return d.log("endRequest",qi(q)),d.end(),b.arrayBuffer()}let[y,I]=b.body.tee(),S=y.getReader();o&&((w=this.throughputEstimator)==null||w.trackStream(I,u));let T=0,E=new Uint8Array(0),R=!1,M=k=>{h==null||h.unsubscribe(),R=!0,ha(k)},C=da(p,async function*({done:k,value:q}){if(T===0&&this.lastRequestFirstBytes$.next(pa()-f),p.aborted){h==null||h.unsubscribe();return}if(!k&&q){let z=new Uint8Array(E.length+q.length);z.set(E),z.set(q,E.length),E=z,T+=q.byteLength,r==null||r(new DataView(E.buffer),T),yield S==null?void 0:S.read().then(C,M)}}.bind(this));yield S==null?void 0:S.read().then(C,M),h==null||h.unsubscribe();let D=pa(),O={failed:R,requestStartedAt:f,requestEndedAt:D,duration:D-f};return R?(d.error("endRequest",qi(O)),d.end(),null):(d.log("endRequest",qi(O)),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,c,l;e.indexRange&&(c=e.indexRange.from,l=e.indexRange.to,u=s+1===c,u&&(n=Math.min(c,r),o=Math.max(l,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let p=new DataView(d,r-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=(y=e.indexRange)!=null?y:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,f.from-n,f.to-f.from+1);else{let 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,h,f);return{init:h,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 ei=(a,e,t)=>t*e+(1-t)*a,tl=(a,e)=>a.reduce((t,i)=>t+i,0)/e,aS=(a,e,t,i)=>{let r=0,s=t,n=tl(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 kt=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 Ks=class extends kt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ei(this.slow,e,this.params.emaAlphaSlow),this.fast=ei(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Js=class extends kt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=tl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ei(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 Xs=class extends kt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?ei(this.smoothed,t,this.params.emaAlpha):t}};var ti=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Ks({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Js({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 Xs({initial:e,label:"liveEdgeDelay",...t})}};var il=(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 c=s.segments.find(l=>l.time.from<=e&&l.time.to>=e);!c||((t=this.currentSegment)==null?void 0:t.time.from)===c.time.from&&this.currentSegment.time.to===c.time.to||(this.currentSegment=c,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(c.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&&Ve(t.segmentReference))}};var ER=["timeupdate","progress","play","seeked","stalled","waiting"],xR=["timeupdate","progress","loadeddata","playing","seeked"];var en=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 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 lS;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 lS;this.gapWatchdogActive=!1;this.destroyController=new je;this.initManifest=rl(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=te(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=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: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 c=(n=ug(e))!=null?n:{id:"ManifestParsing",category:pt.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(c)}if(!t)return null;let i=(u,c,l)=>{var d,p,h,f;return!!((p=(d=this.element)==null?void 0:d.canPlayType)!=null&&p.call(d,c)&&((f=(h=ct())==null?void 0:h.isTypeSupported)!=null&&f.call(h,`${c}; codecs="${l}"`))||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 l=t.streams[u].filter(({mime:h,codecs:f})=>i(u,h,f)),d=new Set(l.map(({codecs:h})=>h)),p=og(d);if(p&&(r[u]=l.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,f=r.video.some(g=>g.hdr),b=r.video.some(g=>!g.hdr);SR.isHDR&&h&&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=rl(this.destroyController.signal,async function*(e,t,i){var d;this.tracer.log("initRepresentationsStart",ma({initialVideo:e,initialAudio:t,sourceHls:i})),ii(this.manifest),ii(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Ui(p,"error").pipe(al(h=>{var f;return!!((f=this.element)!=null&&f.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:pt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?jb():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Bs())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,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new la("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],uS(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new la("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}if(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(sl(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let f=fu(this.manifestUrlString,2);this.manifestUrlString=te(this.manifestUrlString,f+1e3,2)}})),this.representationSubscription.add(Hi(...xR.map(p=>Ui(this.element,p))).pipe(nl(p=>this.element?Ze(this.element.buffered,this.element.currentTime*1e3):0),oS(),TR(p=>{var h;p>this.tuning.dash.bufferEmptinessTolerance&&((h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.timeInWaiting=0)})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(oS()).subscribe(h=>il(this.element,1))),this.representationSubscription.add(Zs({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(al(({bufferLength:h,isActiveLowLatency:f})=>f&&!!h)).subscribe(({bufferLength:h})=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add(Zs({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:h,isActiveLowLatency:f})=>{if(!f)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=h-b,S=1;Math.abs(I)>g&&(S=1+Math.sign(I)*y),il(this.element,S)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,g;let f=0;if(h){let y=((g=(b=this.element)==null?void 0:b.currentTime)!=null?g:0)*1e3;f=Math.min(...this.bufferManagers.map(S=>{var T,E;return(E=(T=S.getLiveSegmentsToLoadState(this.manifest))==null?void 0:T.to)!=null?E:y}))-y}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add(Zs({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(IR(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(ii(this.element),this.isUpdatingLive)return;let b=this.element.playbackRate,g=fu(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),S=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,T=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,E=isFinite(h)?h:f,R=this.isActiveLowLatency$.getValue(),M=y<=this.tuning.live.activeLiveDelay&&g===0;this.isActiveLowLatency$.next(R&&M);let C="none";if(R?C="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&M?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(D=>D.proceedLowLatencyLive()),C="active_low_latency"):g!==0&&E<I?C="live_forward_buffering":E<I+T&&(C="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),C==="live_forward_buffering"||C==="live_with_target_offset"){let D=p-(I+S),O=this.normolizeLiveOffset(Math.trunc(g+D/b)),_=Math.abs(O-g),w;!h||_<=this.tuning.dashCmafLive.offsetCalculationError?w=g:O>0&&_>this.tuning.dashCmafLive.offsetCalculationError?w=O:w=0,this.manifestUrlString=te(this.manifestUrlString,w,2)}C!=="none"&&C!=="active_low_latency"&&(p=0,this.updateLive())}))}let u=Hi(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(nl(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Hi(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(nl(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(Hi(this.forceEnded$,Zs({allBuffersFull:u,someBufferEnded:c}).pipe(al(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:pt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Hi(...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 h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)}));let l=[(d=this.manifest.duration)!=null?d:0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{let h=[];return p.duration&&h.push(p.duration),Ve(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&h.push(p.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...l)/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=sl(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 zs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=ti.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator}),this.initTracerSubscription()}async seekLive(e){var i,r,s;ii(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=te(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(){ii(this.element),this.state$.setState("running"),this.subscription.add(Hi(...ER.map(e=>Ui(this.element,e)),Ui(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:pt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Ui(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Ui(this.element,"waiting").subscribe(()=>{var t,i,r;this.element&&this.element.readyState===2&&!this.element.seeking&&Bi(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var f,b,g,y,I,S,T,E,R,M;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,c=(y=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?y:0,l=(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,p=l<o&&n-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,h=this.audioBufferManager&&d<o&&n-c>this.tuning.dash.crashOnStallTWithoutDataTimeout;if(this.tuning.useNewProviderReinitLogic&&(p||h)&&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={...s,liveLastSeekOffset:this.liveLastSeekOffset};else{let C=this.element.currentTime*1e3;(R=this.videoBufferManager)==null||R.maintain(C),(M=this.audioBufferManager)==null||M.maintain(C),s={...s,position:C}}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=sl(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,c;ii(this.element),ii(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),Bi(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(),(c=this.audioBufferManager)==null||c.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 tn=class{constructor(e,t){this.fov=e,this.orientation=t}};var rn=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 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;
|
|
66
66
|
attribute vec2 a_texel;
|
|
67
67
|
|
|
68
68
|
varying vec2 v_texel;
|
|
@@ -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 an=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 tn(this.params.fov,this.params.orientation),this.cameraRotationManager=new rn(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,c=e+i,l=t+r,d=e-i,p=t+r;return[s,n,o,u,c,l,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var ri=class{constructor(e){this.subscription=new OR;this.videoState=new L("stopped");this.elementSize$=new VR(void 0);this.textTracksManager=new Ce;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 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 c=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(r.position-c,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 an(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 en({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:ol.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 c;let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(hS(l=>!!l.length),mS()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})})),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(l=>l.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(Me(this.video,t.playbackRate,i.playbackRateState$,r)),s(BR(this.video),this.elementSize$),s(Be(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:l})=>{if(l==="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 h=[];for(let f of d.audio){h.push(Ku(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(h)}let p=[];for(let h of d.video){p.push(Ju(h));let f=[];for(let b of h.representations){let g=Kg(b);g&&(f.push(g),this.videoTracksMap.set(g,{stream:h,representation:b}))}this.videoStreamsMap.set(h,f)}if(this.params.output.availableVideoStreams$.next(p),this.textTracksManager)for(let h of d.text)for(let f of h.representations){let b=Xg(h,f);this.textTracksMap.set(b,{stream:h,representation:f})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let n=l=>e.error$.next({id:"RepresentationSwitch",category:ol.WTF,message:"Switching representations threw",thrown:l});this.subscription.add(sn(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 l=this.player.state$.getState(),d=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(l)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[h,f]=p,b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),l==="manifest_ready")this.player.initRepresentations(h.id,f==null?void 0:f.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",h.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:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSize$.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(ul()).subscribe(l=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===l);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=d,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===h.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(Ju(h))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(ul()).subscribe(l=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===l);if(!d){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=d,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===h.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(Ku(h))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var d,p;if(l!=null&&l.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),(c=this.textTracksManager)==null||c.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(fS(({to:l})=>l==="ready"),ul());this.subscription.add(sn(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(sn(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=sn(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 R,M,C,D,O,_,w,k,q,z,v,$,H,G,K,ue,tt,ft;let{desiredState:e,output:t}=this.params,i=e.autoVideoTrackSwitching.getState(),r=(R=e.videoTrack.getState())==null?void 0:R.id,n=[...this.videoTracksMap.keys()].find(({id:A})=>A===r),o=t.currentVideoTrack$.getValue(),u=((D=(C=e.videoStream.getState())!=null?C:n&&((M=this.videoTracksMap.get(n))==null?void 0:M.stream))!=null?D:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let c=[...this.videoStreamsMap.keys()].find(({id:A})=>A===u.id),l=c&&this.videoStreamsMap.get(c);if(!l)return;let d=Ze(this.video.buffered,this.video.currentTime*1e3),p=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(d/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),f=(O=e.audioStream.getState())!=null?O:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=(_=[...this.audioStreamsMap.keys()].find(({id:A})=>A===(f==null?void 0:f.id)))!=null?_:this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!i)if(this.params.tuning.useSeparateAudioVideoABR){let A=ws(n,l,(w=this.audioStreamsMap.get(b))!=null?w:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(k=A==null?void 0:A.bitrate)!=null?k:-1/0)}else{let A=Ws(n,l,(q=this.audioStreamsMap.get(b))!=null?q:[]);g=Math.max(g,(z=A==null?void 0:A.bitrate)!=null?z:-1/0)}if(o)if(this.params.tuning.useSeparateAudioVideoABR){let A=ws(o,l,(v=this.audioStreamsMap.get(b))!=null?v:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,($=A==null?void 0:A.bitrate)!=null?$:-1/0)}else{let A=Ws(o,l,(H=this.audioStreamsMap.get(b))!=null?H:[]);g=Math.max(g,(G=A==null?void 0:A.bitrate)!=null?G:-1/0)}}let y=wt(l,{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:h,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&&$b(I,l,(K=this.audioStreamsMap.get(b))!=null?K:[],{throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}):S=b&&Ws(I,l,(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:ol.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 ri{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 ri{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=ze(xs(),1);import{assertNever as va,assertNonNullable as gS,debounce as FR,ErrorCategory as nn,filter as qR,isNonNullable as UR,isNullable as HR,map as on,merge as jR,Observable as GR,observableFrom as WR,Subscription as YR,videoSizeToQuality as QR}from"@vkontakte/videoplayer-shared";var We={};var ji=(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 L("initializing");this.textTracksManager=new Ce;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:nn.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||(We.Hls=r.default,We.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){gS(We.Hls,"hls.js not loaded"),this.hls=new We.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){gS(We.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=c=>{t.error$.next({id:"HlsJsProvider",category:nn.WTF,message:"HlsJsProvider internal logic error",thrown:c})},r=me(this.video),s=(c,l)=>this.subscription.add(c.subscribe(l,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(Me(this.video,e.playbackRate,r.playbackRateState$,i)),s(Be(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(on(c=>c.to)),this.params.output.playbackState$),this.subscription.add(ji(this.hls,We.Events.ERROR).subscribe(c=>{var l;c.fatal&&t.error$.next({id:["HlsJsFatal",c.type,c.details].join("_"),category:nn.WTF,message:`HlsJs fatal ${c.type} ${c.details}, ${(l=c.err)==null?void 0:l.message} ${c.reason}`,thrown:c.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 c;((c=this.videoState.getTransition())==null?void 0:c.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),s(ji(this.hls,We.Events.MANIFEST_PARSED).pipe(on(({levels:c})=>c.reduce((l,d)=>{var I,S;let p=d.name||d.height.toString(10),{width:h,height:f}=d,b=(S=At((I=d.attrs.QUALITY)!=null?I:""))!=null?S:QR({width:h,height:f});if(!b)return l;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,y={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:f},fps:g};return this.trackLevels.set(p,{track:y,level:d}),l.push(y),l},[]))),t.availableVideoTracks$),s(ji(this.hls,We.Events.MANIFEST_PARSED),c=>{if(c.subtitleTracks.length>0){let l=[];for(let d of c.subtitleTracks){let p=d.name,h=d.attrs.URI||"",f=d.lang;l.push({id:p,url:h,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(l)}}),s(ji(this.hls,We.Events.LEVEL_LOADING).pipe(on(({url:c})=>Z(c))),t.hostname$),s(ji(this.hls,We.Events.FRAG_CHANGED),c=>{var p,h,f,b;let{video:l,audio:d}=c.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=l==null?void 0:l.endPTS)!=null?p:0)-((h=l==null?void 0:l.startPTS)!=null?h: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(Et(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,c=>{this.hls.nextLevel=c?-1:this.hls.currentLevel,this.hls.loadLevel=c?-1:this.hls.loadLevel},{onError:i}));let n=c=>{var l;return(l=Array.from(this.trackLevels.values()).find(({level:d})=>d===c))==null?void 0:l.track},o=ji(this.hls,We.Events.LEVEL_SWITCHED).pipe(on(({level:c})=>n(this.hls.levels[c])));o.pipe(qR(UR)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Et(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),c=>{var f;if(HR(c))return;let l=(f=this.trackLevels.get(c.id))==null?void 0:f.level;if(!l)return;let d=this.hls.levels.indexOf(l),p=this.hls.currentLevel,h=this.hls.levels[p];!h||l.bitrate>h.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:nn.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",ll=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 ln,filter as r$,filterChanged as a$,isNonNullable as TS,isNullable as cn,map as IS,merge as s$,observableFrom as n$,Subscription as o$,ValueSubject as pl,VideoQuality as u$}from"@vkontakte/videoplayer-shared";var dl=ze(Ro(),1);import{videoSizeToQuality as zR,getExponentialDelay as KR}from"@vkontakte/videoplayer-shared";var JR=a=>{let e=null;if(a.QUALITY&&(e=At(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],c=u.match(/^#EXT-X-STREAM-INF:(.+)/),l=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!c&&!l)){if(c){let d=(0,dl.default)(c[1].split(",").map(I=>I.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=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();h&&i.push({id:p,quality:h,url:y,bandwidth:f,size:g,fps:b})}if(l){let d=(0,dl.default)(l[1].split(",").map(b=>b.split("=")).map(([b,g])=>[b,g.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=d.LANGUAGE,f=d.NAME;p&&h&&r.push({type:"internal",id:h,label:f,language:h,url:p,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},ZR=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),cl=0,yS=async(a,e=a,t)=>{let r=await(await lt(a)).text();cl+=1;try{let{qualityManifests:s,textTracks:n}=XR(r,e);return{qualityManifests:s,textTracks:n}}catch(s){if(cl<=t.manifestRetryMaxCount)return await ZR(KR(cl-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),yS(a,e,t)}return{qualityManifests:[],textTracks:[]}},un=yS;var Ta=class{constructor(e){this.subscription=new o$;this.videoState=new L("stopped");this.textTracksManager=new Ce;this.manifests$=new pl([]);this.liveOffset=new ot;this.manifestStartTime$=new pl(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 c=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let l=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(l),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&c.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(c.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 l=this.liveOffset.getTotalOffset();l>=this.maxSeekBackTime$.getValue()&&(l=0,this.liveOffset.resetTo(l)),this.liveOffset.resume(),this.params.output.position$.next(-l/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},un(te(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:ln.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:ln.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 pl((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,c,l,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(d=(l=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?l:(c=t.getState())==null?void 0:c.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(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:ln.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(Me(this.video,t.playbackRate,r.playbackRateState$,i)),s(Be(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(),c=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&TS(c.to)){let d=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Z(p.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.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,c,l;let o=(l=(c=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:c.call(u))==null?void 0:l.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:c,size:l,bandwidth:d,fps:p})=>({id:u,quality:c,size:l,fps:p,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(cn(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:c,min:l}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[d,p]of[[c,"mq"],[l,"lq"]]){let h=String(parseFloat(d||""));p&&d&&r.searchParams.set(p,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=te(r.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),ll(n).then(c=>{var l;if(!cn(c))this.maxSeekBackTime$.next(c);else{let d=(l=this.params.source.maxSeekBackTime)!=null?l:this.maxSeekBackTime$.getValue();if(cn(d)||!isFinite(d))try{lt(n).then(p=>p.text()).then(p=>{var f;let h=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:f[1];if(h){let b=new URL(h,n).toString();ll(b).then(g=>{cn(g)||this.maxSeekBackTime$.next(g)})}})}catch(p){}}})}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:ln.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 hl,fromEvent as fl,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 L("stopped");this.textTracksManager=new Ce;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 c=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let l=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(l);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&c.state==="requested"&&this.seek(c.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),un(te(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:hl.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,c,l,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(d=(l=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?l:(c=t.getState())==null?void 0:c.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(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:hl.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(Me(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(),c=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&d$(c.to)){let p=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let h=this.manifests$.getValue().find(f=>f.id===p);if(h){this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Z(h.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)}}}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.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:c,size:l,bandwidth:d,fps:p})=>({id:u,quality:c,size:l,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!b$.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(xS(fl(o,"addtrack"),fl(o,"removetrack"),fl(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[c,l]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(c||""));l&&c&&r.searchParams.set(l,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:hl.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 L("stopped");this.trackUrls={};this.textTracksManager=new Ce;this.syncPlayback=()=>{var u,c,l;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)!==((l=(c=this.trackUrls[n.to.id])==null?void 0:c.track)==null?void 0:l.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(Me(this.video,t.playbackRate,r.playbackRateState$,i)),s(Be(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,c;((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 l=this.params.desiredState.playbackRate.getState(),d=(c=this.params.output.element$.getValue())==null?void 0:c.playbackRate;if(l!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(l),p.playbackRate=l)}}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,c=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,l=(o=this.trackUrls[c!=null?c:"0"])==null?void 0:o.track;if(u&&l&&y$(l.quality,u.quality)&&(t=u),!t){let d=Object.values(this.trackUrls).filter(h=>!kS(h.track.quality)&&v$(h.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(i=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(c=>c.track);t=wt(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 bl,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,ml=()=>null,dn=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=ml;this.externalStopCallback=ml;this.externalErrorCallback=ml;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 L("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 dn(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:bl.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(Be(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:bl.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:bl.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 Rt,ErrorCategory as hn,filter as q$,isNonNullable as _S,isNullable as U$,map as H$,merge as j$,once as G$,Subject as Te,Subscription as NS,ValueSubject as B,flattenObject as FS}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:c,to:l})=>`${c}-${l}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(CS(({type:c})=>c!==void 0)),n=new V$,o=0,u="unknown";return t.add(i.subscribe(c=>{o&&window.clearTimeout(o),u=c,o=window.setTimeout(()=>n.next(c),a.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(c=>{o&&(window.clearTimeout(o),o=0,c&&(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,pn=null;function gl(){return Aa||(Aa=new(window.AudioContext||window.webkitAudioContext)),pn||(pn=new GainNode(Aa,{gain:1}),pn.connect(Aa.destination)),{audioCtx:Aa,gainNode:pn}}import{clientChecker as F$}from"@vkontakte/videoplayer-shared";var Gi=class Gi{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}=gl(),s=(Math.random()+1)*999999;this.lastAudioContextResumeId=s,i.resume().then(()=>{var n;if(s!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${Gi.errorId} destroyed`);r.gain.value=t;try{new MediaElementAudioSourceNode(i,{mediaElement:e}).connect(r),this.audioContextInit=!0}catch(o){this.volumeMultiplierError$.next({id:Gi.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:Gi.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}=gl();e.gain.value=1}this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};Gi.errorId="VolumeMultiplierManager";var Wi=Gi;var W$={chunkDuration:5e3,maxParallelRequests:5},ka=class{constructor(e){this.current$=new B({type:void 0});this.providerError$=new Te;this.noAvailableProvidersError$=new Te;this.volumeMultiplierError$=new Te;this.providerOutput={position$:new B(0),duration$:new B(1/0),volume$:new B({muted:!1,volume:1}),availableVideoStreams$:new B([]),currentVideoStream$:new B(void 0),availableVideoTracks$:new B([]),currentVideoTrack$:new B(void 0),availableAudioStreams$:new B([]),currentAudioStream$:new B(void 0),availableAudioTracks$:new B([]),currentVideoSegmentLength$:new B(0),currentAudioSegmentLength$:new B(0),isAudioAvailable$:new B(!0),autoVideoTrackLimitingAvailable$:new B(!1),autoVideoTrackLimits$:new B(void 0),currentBuffer$:new B(void 0),isBuffering$:new B(!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 B(void 0),isLowLatency$:new B(!1),canChangePlaybackSpeed$:new B(!0),liveTime$:new B(void 0),liveBufferTime$:new B(void 0),availableTextTracks$:new B([]),currentTextTrack$:new B(void 0),hostname$:new B(void 0),httpConnectionType$:new B(void 0),httpConnectionReused$:new B(void 0),inPiP$:new B(!1),inFullscreen$:new B(!1),element$:new B(void 0),elementVisible$:new B(!0),availableSources$:new B(void 0),is3DVideo$:new B(!1),playbackState$:new B("")};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=ag([...ng(this.params.tuning),...sg(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(c=>_S(e.sources[c])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(c=>!r.includes(c)),...t.filter(c=>r.includes(c))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",FS(s)),this.screenFormatsIterator=new Pa(s);let n=[...Du(!0),...Du(!1)];this.chromecastFormatsIterator=new Pa(n.filter(c=>_S(e.sources[c]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Wi.isSupported()&&(this.volumeMultiplierManager=new Wi(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:hn.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 Rt(o),new ga({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Rt(o),new Sa({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Rt(o),Di||!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 Rt(o),new Ta({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Rt(o),new Ea({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Rt(o),new qb({...n,source:o,config:{...W$,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Rt(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 Rt(o),new xr({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 NS,t=!1,i=0;return e.add(j$(this.providerOutput.error$,DS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(H$(r=>({id:`ProviderHangup:${r}`,category:hn.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(q$(({to:s})=>s==="playing"),G$()).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===hn.NETWORK,u=r.category===hn.FATAL,c=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=i<this.params.tuning.providerErrorLimit&&!u,d=c&&!u&&(o&&t||!l);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:c,tryFailover:d,canReinitProvider:l},this.params.tuning.useNewProviderReinitLogic?l?(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()):l?(i++,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",FS(n))})),e}};import{fromEvent as fn,once as Y$,combine as Q$,Subscription as US,ValueSubject as Sl,map as z$,filter as K$,isNonNullable as mn,now as Ae,safeStorage as vl}from"@vkontakte/videoplayer-shared";var J$=5e3,HS="one_video_throughput",jS="one_video_rtt",ht=window.navigator.connection,GS=()=>{let a=ht==null?void 0:ht.downlink;if(mn(a)&&a!==10)return a*1e3},WS=()=>{let a=ht==null?void 0:ht.rtt;if(mn(a)&&a!==3e3)return a},YS=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},yl=class a{constructor(e){this.subscription=new US;this.concurrentDownloads=new Set;var r,s;this.tuningConfig=e;let t=a.load(HS)||(e.useBrowserEstimation?GS():void 0)||J$,i=(s=(r=a.load(jS))!=null?r:e.useBrowserEstimation?WS():void 0)!=null?s:0;if(this.throughput$=new Sl(t),this.rtt$=new Sl(i),this.rttAdjustedThroughput$=new Sl(YS(t,i,e.rttPenaltyRequestSize)),this.throughput=ti.getSmoothedValue(t,-1,e),this.rtt=ti.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=GS();u&&this.throughput.next(u);let c=WS();mn(c)&&this.rtt.next(c)};ht&&"onchange"in ht&&this.subscription.add(fn(ht,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{vl.set(HS,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{vl.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(Q$({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(z$(({throughput:n,rtt:o})=>YS(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,i=Ae(),r=new US;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(fn(e,"progress").pipe(Y$()).subscribe(s=>{t=s.loaded,i=Ae()}));break;case 1:case 0:r.add(fn(e,"loadstart").subscribe(()=>{t=0,i=Ae()}));break}r.add(fn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Ae(),u=n-t,c=o-i;this.addRawSpeed(u,c,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=Ae(),n=0,o=Ae(),u=l=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${l}`).catch(()=>{})},c=async({done:l,value:d})=>{if(l)!t&&this.addRawSpeed(r,Ae()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=Ae();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=d.byteLength,s=Ae()}else n+=d.byteLength;o=Ae()}else r+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Ae()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Ae()-o,this.concurrentDownloads.size),n=0,o=Ae());await(i==null?void 0:i.read().then(c,u))}};this.concurrentDownloads.add(e),i==null||i.read().then(c,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=vl.get(e);if(mn(t))return(i=parseInt(t,10))!=null?i:void 0}},QS=yl;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:2,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},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:!1,useNewPartialSegmentFeeding:!1,useNewSwitchTo:!1,useSeparateAudioVideoABR:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,useNewProviderReinitLogic:!1,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},JS=a=>{var e;return{...X$(a,KS),configName:[...(e=a.configName)!=null?e:[],...KS.configName]}};import{assertNonNullable as bn,combine as $t,ErrorCategory as gn,filter as oe,filterChanged as N,fromEvent as Il,isNonNullable as sL,isNullable as nL,Logger as oL,map as V,mapTo as tv,merge as Lt,now as Sn,once as et,Subject as U,Subscription as iv,tap as rv,ValueSubject as P,isHigher as uL,isInvariantQuality as av,flattenObject as Mt,throttle as El,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 Tl=({seekState:a,position$:e})=>Z$(a.stateChangeEnded$.pipe(eL(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),XS(tL)),e.pipe(XS(()=>a.getState().state==="none")));import{assertNonNullable as iL}from"@vkontakte/videoplayer-shared";var ZS=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return iL(e,`Wrong container or containerId {${a.container}}`),e};import{filter as rL,once as aL}from"@vkontakte/videoplayer-shared";var ev=(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(rL(r=>r.length>0),aL()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(a)};var vn=class{constructor(e={configName:[]},t=lL.createRootTracer(!1)){this.subscription=new iv;this.logger=new oL;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;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 U,ready$:new U,started$:new U,playing$:new U,paused$:new U,stopped$:new U,willStart$:new U,willResume$:new U,willPause$:new U,willStop$:new U,willDestruct$:new U,watchCoverageRecord$:new U,watchCoverageLive$:new U,managedError$:new U,fatalError$:new U,ended$:new U,looped$:new U,seeked$:new U,willSeek$:new U,autoplaySoundProhibited$:new U,firstBytes$:new U,loadedMetadata$:new U,firstFrame$:new U,canplay$:new U,log$:new U};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:yb};if(this.initLogs(),this.tuning=JS(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ha({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new QS(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 c=o.map(p=>JSON.stringify(p,(h,f)=>{let b=typeof f;return["number","string","boolean"].includes(b)?f:f===null?null:`<${b}>`})),l=`Player.${String(r)}`,d=`Exception calling ${l} (${c.join(", ")})`;throw this.events.fatalError$.next({id:l,category:gn.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",Mt(i)),this.domContainer=ZS(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"),Il(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){bn(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",Mt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var i;bn(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",Mt(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$,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(nL(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return sL(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(Lt(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=Sn(),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",Mt(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:gn.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",Mt(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),N()).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(N()).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((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(N((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(N()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(N()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(N()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=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($t({hasLiveOffsetByPaused:Lt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(V(n=>n.to),N(),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($t({atLiveEdge:$t({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Tl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(V(({isLive:n,position:o,isLowLatency:u})=>{let c=this.getActiveLiveDelay(u);return n&&Math.abs(o)<c/1e3}),N(),rv(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(V(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add($t({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(V(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),N(),rv(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(V(n=>n.muted),N()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(V(n=>n.volume),N()).subscribe(this.info.volume$)).add(Tl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Lt(e.providerOutput.endedEvent$.pipe(tv(!0)),e.providerOutput.seekedEvent$.pipe(tv(!1))).pipe(N()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(V(n=>({id:n?`No${n}`:"NoProviders",category:gn.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:Sn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(et(),V(()=>Sn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(et(),V(()=>Sn()-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=Lt(e.providerOutput.isBuffering$,t,i).pipe(V(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),N());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(Lt(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,c;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(c=n==null?void 0:n.size)==null?void 0:c.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(Lt(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(),c=e.providerOutput.elementVisible$.getValue(),l=this.chromecastInitializer.castState$.getValue(),d;l==="CONNECTED"?d="second_screen":u?c?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 iv;this.subscription.add(t),this.subscription.add(e.current$.pipe(N((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=wt(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(Lt(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;bn(this.providerContainer),bn(e),vb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Sb(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",rg())}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(N()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add($t({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(oe(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),N((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(oe(i=>i>0),N()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(oe(i=>i>0),N()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add($t({currentBuffer:this.info.currentBuffer$.pipe(oe(i=>i.end>0),N((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(N())}).pipe(El(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(N()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(N()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(N()).subscribe(e("canChangePlaybackSpeed"))).add($t({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(oe(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),El(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(N(),oe(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(N(),oe(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(N()).subscribe(e("muted"))).add(this.info.volume$.pipe(N()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(N(),oe(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add($t({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(oe(({throughputEstimation:i,rtt:r})=>!!i&&!!r),El(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(N(),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:gn.DOM,message:String(r)})})};this.subscription.add(Lt(Il(document,"visibilitychange"),Il(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",Mt({quality:t,availableTracks:Mt(e),track:Mt(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 dW,Observable as pW,Subject as hW,ValueSubject as fW,VideoQuality as mW}from"@vkontakte/videoplayer-shared";var bW=`@vkontakte/videoplayer-core@${nc}`;export{qa as ChromecastState,Pn as HttpConnectionType,pW as Observable,ce as PlaybackState,vn as Player,bW as SDK_VERSION,hW as Subject,dW as Subscription,An as Surface,nc as VERSION,fW as ValueSubject,Tt as VideoFormat,mW as VideoQuality};
|
|
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};
|