@vkontakte/videoplayer-core 2.0.108-dev.377c6d18.0 → 2.0.108-dev.3ff897f5.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 +42 -21
- package/es2015.esm.js +42 -21
- package/es2018.cjs.js +42 -21
- package/es2018.esm.js +40 -19
- package/esnext.cjs.js +42 -21
- package/esnext.esm.js +42 -21
- package/evergreen.esm.js +42 -21
- package/package.json +2 -2
- package/types/player/Player.d.ts +6 -4
- package/types/player/types.d.ts +5 -6
- package/types/providers/DashProvider/baseDashProvider.d.ts +5 -3
- package/types/providers/DashProvider/lib/buffer.d.ts +3 -0
- package/types/providers/DashProvider/lib/fetcher.d.ts +4 -2
- package/types/providers/DashProvider/lib/player.d.ts +5 -4
- package/types/providers/DashProvider/lib/types.d.ts +0 -6
- package/types/providers/DashProvider/lib/utils.d.ts +5 -3
- package/types/providers/ProviderContainer/index.d.ts +1 -0
- package/types/providers/types.d.ts +2 -1
- package/types/utils/autoSelectTrack.d.ts +29 -0
- package/types/utils/tuningConfig.d.ts +6 -0
- package/types/providers/DashProvider/lib/LiveTextManager.d.ts +0 -22
- package/types/utils/autoSelectVideoTrack.d.ts +0 -26
package/esnext.esm.js
CHANGED
|
@@ -1,40 +1,61 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.108-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.108-dev.3ff897f5.0
|
|
3
|
+
* Wed, 04 Sep 2024 18:33:52 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-108/doc/
|
|
5
5
|
*/
|
|
6
|
-
var RS=Object.create;var Hu=Object.defineProperty;var LS=Object.getOwnPropertyDescriptor;var $S=Object.getOwnPropertyNames;var MS=Object.getPrototypeOf,CS=Object.prototype.hasOwnProperty;var m=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var DS=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of $S(e))!CS.call(i,a)&&a!==t&&Hu(i,a,{get:()=>e[a],enumerable:!(r=LS(e,a))||r.enumerable});return i};var He=(i,e,t)=>(t=i!=null?RS(MS(i)):{},DS(e||!i||!i.__esModule?Hu(t,"default",{value:i,enumerable:!0}):t,i));var he=m((CR,Ju)=>{"use strict";Ju.exports=function(i){try{return!!i()}catch{return!0}}});var Cr=m((DR,Xu)=>{"use strict";var US=he();Xu.exports=!US(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var ie=m((OR,tl)=>{"use strict";var Zu=Cr(),el=Function.prototype,Ws=el.call,HS=Zu&&el.bind.bind(Ws,Ws);tl.exports=Zu?HS:function(i){return function(){return Ws.apply(i,arguments)}}});var Xt=m((VR,il)=>{"use strict";var rl=ie(),jS=rl({}.toString),GS=rl("".slice);il.exports=function(i){return GS(jS(i),8,-1)}});var sl=m((BR,al)=>{"use strict";var YS=ie(),WS=he(),QS=Xt(),Qs=Object,zS=YS("".split);al.exports=WS(function(){return!Qs("z").propertyIsEnumerable(0)})?function(i){return QS(i)==="String"?zS(i,""):Qs(i)}:Qs});var Zt=m((_R,nl)=>{"use strict";nl.exports=function(i){return i==null}});var Dr=m((NR,ol)=>{"use strict";var KS=Zt(),JS=TypeError;ol.exports=function(i){if(KS(i))throw new JS("Can't call method on "+i);return i}});var er=m((FR,ul)=>{"use strict";var XS=sl(),ZS=Dr();ul.exports=function(i){return XS(ZS(i))}});var zs=m((qR,ll)=>{"use strict";ll.exports=function(){}});var Rt=m((UR,cl)=>{"use strict";cl.exports={}});var q=m((Ks,dl)=>{"use strict";var Or=function(i){return i&&i.Math===Math&&i};dl.exports=Or(typeof globalThis=="object"&&globalThis)||Or(typeof window=="object"&&window)||Or(typeof self=="object"&&self)||Or(typeof global=="object"&&global)||Or(typeof Ks=="object"&&Ks)||function(){return this}()||Function("return this")()});var F=m((HR,pl)=>{"use strict";var Js=typeof document=="object"&&document.all;pl.exports=typeof Js>"u"&&Js!==void 0?function(i){return typeof i=="function"||i===Js}:function(i){return typeof i=="function"}});var fl=m((jR,ml)=>{"use strict";var eg=q(),tg=F(),hl=eg.WeakMap;ml.exports=tg(hl)&&/native code/.test(String(hl))});var ye=m((GR,bl)=>{"use strict";var rg=F();bl.exports=function(i){return typeof i=="object"?i!==null:rg(i)}});var Te=m((YR,Sl)=>{"use strict";var ig=he();Sl.exports=!ig(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Sa=m((WR,vl)=>{"use strict";var ag=q(),gl=ye(),Xs=ag.document,sg=gl(Xs)&&gl(Xs.createElement);vl.exports=function(i){return sg?Xs.createElement(i):{}}});var Zs=m((QR,yl)=>{"use strict";var ng=Te(),og=he(),ug=Sa();yl.exports=!ng&&!og(function(){return Object.defineProperty(ug("div"),"a",{get:function(){return 7}}).a!==7})});var en=m((zR,Tl)=>{"use strict";var lg=Te(),cg=he();Tl.exports=lg&&cg(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var je=m((KR,Il)=>{"use strict";var dg=ye(),pg=String,hg=TypeError;Il.exports=function(i){if(dg(i))return i;throw new hg(pg(i)+" is not an object")}});var me=m((JR,El)=>{"use strict";var mg=Cr(),ga=Function.prototype.call;El.exports=mg?ga.bind(ga):function(){return ga.apply(ga,arguments)}});var va=m((XR,xl)=>{"use strict";xl.exports={}});var Ke=m((ZR,kl)=>{"use strict";var tn=va(),rn=q(),fg=F(),Pl=function(i){return fg(i)?i:void 0};kl.exports=function(i,e){return arguments.length<2?Pl(tn[i])||Pl(rn[i]):tn[i]&&tn[i][e]||rn[i]&&rn[i][e]}});var Vr=m((eL,wl)=>{"use strict";var bg=ie();wl.exports=bg({}.isPrototypeOf)});var tr=m((tL,Ll)=>{"use strict";var Sg=q(),Al=Sg.navigator,Rl=Al&&Al.userAgent;Ll.exports=Rl?String(Rl):""});var sn=m((rL,Vl)=>{"use strict";var Ol=q(),an=tr(),$l=Ol.process,Ml=Ol.Deno,Cl=$l&&$l.versions||Ml&&Ml.version,Dl=Cl&&Cl.v8,Ce,ya;Dl&&(Ce=Dl.split("."),ya=Ce[0]>0&&Ce[0]<4?1:+(Ce[0]+Ce[1]));!ya&&an&&(Ce=an.match(/Edge\/(\d+)/),(!Ce||Ce[1]>=74)&&(Ce=an.match(/Chrome\/(\d+)/),Ce&&(ya=+Ce[1])));Vl.exports=ya});var nn=m((iL,_l)=>{"use strict";var Bl=sn(),gg=he(),vg=q(),yg=vg.String;_l.exports=!!Object.getOwnPropertySymbols&&!gg(function(){var i=Symbol("symbol detection");return!yg(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&Bl&&Bl<41})});var on=m((aL,Nl)=>{"use strict";var Tg=nn();Nl.exports=Tg&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var un=m((sL,Fl)=>{"use strict";var Ig=Ke(),Eg=F(),xg=Vr(),Pg=on(),kg=Object;Fl.exports=Pg?function(i){return typeof i=="symbol"}:function(i){var e=Ig("Symbol");return Eg(e)&&xg(e.prototype,kg(i))}});var Br=m((nL,ql)=>{"use strict";var wg=String;ql.exports=function(i){try{return wg(i)}catch{return"Object"}}});var Je=m((oL,Ul)=>{"use strict";var Ag=F(),Rg=Br(),Lg=TypeError;Ul.exports=function(i){if(Ag(i))return i;throw new Lg(Rg(i)+" is not a function")}});var _r=m((uL,Hl)=>{"use strict";var $g=Je(),Mg=Zt();Hl.exports=function(i,e){var t=i[e];return Mg(t)?void 0:$g(t)}});var Gl=m((lL,jl)=>{"use strict";var ln=me(),cn=F(),dn=ye(),Cg=TypeError;jl.exports=function(i,e){var t,r;if(e==="string"&&cn(t=i.toString)&&!dn(r=ln(t,i))||cn(t=i.valueOf)&&!dn(r=ln(t,i))||e!=="string"&&cn(t=i.toString)&&!dn(r=ln(t,i)))return r;throw new Cg("Can't convert object to primitive value")}});var De=m((cL,Yl)=>{"use strict";Yl.exports=!0});var zl=m((dL,Ql)=>{"use strict";var Wl=q(),Dg=Object.defineProperty;Ql.exports=function(i,e){try{Dg(Wl,i,{value:e,configurable:!0,writable:!0})}catch{Wl[i]=e}return e}});var Nr=m((pL,Xl)=>{"use strict";var Og=De(),Vg=q(),Bg=zl(),Kl="__core-js_shared__",Jl=Xl.exports=Vg[Kl]||Bg(Kl,{});(Jl.versions||(Jl.versions=[])).push({version:"3.38.0",mode:Og?"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 pn=m((hL,ec)=>{"use strict";var Zl=Nr();ec.exports=function(i,e){return Zl[i]||(Zl[i]=e||{})}});var Fr=m((mL,tc)=>{"use strict";var _g=Dr(),Ng=Object;tc.exports=function(i){return Ng(_g(i))}});var Oe=m((fL,rc)=>{"use strict";var Fg=ie(),qg=Fr(),Ug=Fg({}.hasOwnProperty);rc.exports=Object.hasOwn||function(e,t){return Ug(qg(e),t)}});var hn=m((bL,ic)=>{"use strict";var Hg=ie(),jg=0,Gg=Math.random(),Yg=Hg(1 .toString);ic.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+Yg(++jg+Gg,36)}});var ee=m((SL,sc)=>{"use strict";var Wg=q(),Qg=pn(),ac=Oe(),zg=hn(),Kg=nn(),Jg=on(),rr=Wg.Symbol,mn=Qg("wks"),Xg=Jg?rr.for||rr:rr&&rr.withoutSetter||zg;sc.exports=function(i){return ac(mn,i)||(mn[i]=Kg&&ac(rr,i)?rr[i]:Xg("Symbol."+i)),mn[i]}});var lc=m((gL,uc)=>{"use strict";var Zg=me(),nc=ye(),oc=un(),ev=_r(),tv=Gl(),rv=ee(),iv=TypeError,av=rv("toPrimitive");uc.exports=function(i,e){if(!nc(i)||oc(i))return i;var t=ev(i,av),r;if(t){if(e===void 0&&(e="default"),r=Zg(t,i,e),!nc(r)||oc(r))return r;throw new iv("Can't convert object to primitive value")}return e===void 0&&(e="number"),tv(i,e)}});var fn=m((vL,cc)=>{"use strict";var sv=lc(),nv=un();cc.exports=function(i){var e=sv(i,"string");return nv(e)?e:e+""}});var Lt=m(pc=>{"use strict";var ov=Te(),uv=Zs(),lv=en(),Ta=je(),dc=fn(),cv=TypeError,bn=Object.defineProperty,dv=Object.getOwnPropertyDescriptor,Sn="enumerable",gn="configurable",vn="writable";pc.f=ov?lv?function(e,t,r){if(Ta(e),t=dc(t),Ta(r),typeof e=="function"&&t==="prototype"&&"value"in r&&vn in r&&!r[vn]){var a=dv(e,t);a&&a[vn]&&(e[t]=r.value,r={configurable:gn in r?r[gn]:a[gn],enumerable:Sn in r?r[Sn]:a[Sn],writable:!1})}return bn(e,t,r)}:bn:function(e,t,r){if(Ta(e),t=dc(t),Ta(r),uv)try{return bn(e,t,r)}catch{}if("get"in r||"set"in r)throw new cv("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var qr=m((TL,hc)=>{"use strict";hc.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var ir=m((IL,mc)=>{"use strict";var pv=Te(),hv=Lt(),mv=qr();mc.exports=pv?function(i,e,t){return hv.f(i,e,mv(1,t))}:function(i,e,t){return i[e]=t,i}});var Ia=m((EL,bc)=>{"use strict";var fv=pn(),bv=hn(),fc=fv("keys");bc.exports=function(i){return fc[i]||(fc[i]=bv(i))}});var Ea=m((xL,Sc)=>{"use strict";Sc.exports={}});var En=m((PL,yc)=>{"use strict";var Sv=fl(),vc=q(),gv=ye(),vv=ir(),yn=Oe(),Tn=Nr(),yv=Ia(),Tv=Ea(),gc="Object already initialized",In=vc.TypeError,Iv=vc.WeakMap,xa,Ur,Pa,Ev=function(i){return Pa(i)?Ur(i):xa(i,{})},xv=function(i){return function(e){var t;if(!gv(e)||(t=Ur(e)).type!==i)throw new In("Incompatible receiver, "+i+" required");return t}};Sv||Tn.state?(Ve=Tn.state||(Tn.state=new Iv),Ve.get=Ve.get,Ve.has=Ve.has,Ve.set=Ve.set,xa=function(i,e){if(Ve.has(i))throw new In(gc);return e.facade=i,Ve.set(i,e),e},Ur=function(i){return Ve.get(i)||{}},Pa=function(i){return Ve.has(i)}):($t=yv("state"),Tv[$t]=!0,xa=function(i,e){if(yn(i,$t))throw new In(gc);return e.facade=i,vv(i,$t,e),e},Ur=function(i){return yn(i,$t)?i[$t]:{}},Pa=function(i){return yn(i,$t)});var Ve,$t;yc.exports={set:xa,get:Ur,has:Pa,enforce:Ev,getterFor:xv}});var xn=m((kL,xc)=>{"use strict";var Pv=Cr(),Ec=Function.prototype,Tc=Ec.apply,Ic=Ec.call;xc.exports=typeof Reflect=="object"&&Reflect.apply||(Pv?Ic.bind(Tc):function(){return Ic.apply(Tc,arguments)})});var Pn=m((wL,Pc)=>{"use strict";var kv=Xt(),wv=ie();Pc.exports=function(i){if(kv(i)==="Function")return wv(i)}});var Rc=m(Ac=>{"use strict";var kc={}.propertyIsEnumerable,wc=Object.getOwnPropertyDescriptor,Av=wc&&!kc.call({1:2},1);Ac.f=Av?function(e){var t=wc(this,e);return!!t&&t.enumerable}:kc});var Mc=m($c=>{"use strict";var Rv=Te(),Lv=me(),$v=Rc(),Mv=qr(),Cv=er(),Dv=fn(),Ov=Oe(),Vv=Zs(),Lc=Object.getOwnPropertyDescriptor;$c.f=Rv?Lc:function(e,t){if(e=Cv(e),t=Dv(t),Vv)try{return Lc(e,t)}catch{}if(Ov(e,t))return Mv(!Lv($v.f,e,t),e[t])}});var kn=m((LL,Cc)=>{"use strict";var Bv=he(),_v=F(),Nv=/#|\.prototype\./,Hr=function(i,e){var t=qv[Fv(i)];return t===Hv?!0:t===Uv?!1:_v(e)?Bv(e):!!e},Fv=Hr.normalize=function(i){return String(i).replace(Nv,".").toLowerCase()},qv=Hr.data={},Uv=Hr.NATIVE="N",Hv=Hr.POLYFILL="P";Cc.exports=Hr});var jr=m(($L,Oc)=>{"use strict";var Dc=Pn(),jv=Je(),Gv=Cr(),Yv=Dc(Dc.bind);Oc.exports=function(i,e){return jv(i),e===void 0?i:Gv?Yv(i,e):function(){return i.apply(e,arguments)}}});var Ie=m((ML,Bc)=>{"use strict";var Gr=q(),Wv=xn(),Qv=Pn(),zv=F(),Kv=Mc().f,Jv=kn(),ar=va(),Xv=jr(),sr=ir(),Vc=Oe();Nr();var Zv=function(i){var e=function(t,r,a){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,r)}return new i(t,r,a)}return Wv(i,this,arguments)};return e.prototype=i.prototype,e};Bc.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?Gr:a?Gr[t]:Gr[t]&&Gr[t].prototype,o=r?ar:ar[t]||sr(ar,t,{})[t],l=o.prototype,u,c,d,p,h,f,b,S,v;for(p in e)u=Jv(r?p:t+(a?".":"#")+p,i.forced),c=!u&&n&&Vc(n,p),f=o[p],c&&(i.dontCallGetSet?(v=Kv(n,p),b=v&&v.value):b=n[p]),h=c&&b?b:e[p],!(!u&&!s&&typeof f==typeof h)&&(i.bind&&c?S=Xv(h,Gr):i.wrap&&c?S=Zv(h):s&&zv(h)?S=Qv(h):S=h,(i.sham||h&&h.sham||f&&f.sham)&&sr(S,"sham",!0),sr(o,p,S),s&&(d=t+"Prototype",Vc(ar,d)||sr(ar,d,{}),sr(ar[d],p,h),i.real&&l&&(u||!l[p])&&sr(l,p,h)))}});var Fc=m((CL,Nc)=>{"use strict";var wn=Te(),ey=Oe(),_c=Function.prototype,ty=wn&&Object.getOwnPropertyDescriptor,An=ey(_c,"name"),ry=An&&function(){}.name==="something",iy=An&&(!wn||wn&&ty(_c,"name").configurable);Nc.exports={EXISTS:An,PROPER:ry,CONFIGURABLE:iy}});var Uc=m((DL,qc)=>{"use strict";var ay=Math.ceil,sy=Math.floor;qc.exports=Math.trunc||function(e){var t=+e;return(t>0?sy:ay)(t)}});var ka=m((OL,Hc)=>{"use strict";var ny=Uc();Hc.exports=function(i){var e=+i;return e!==e||e===0?0:ny(e)}});var Gc=m((VL,jc)=>{"use strict";var oy=ka(),uy=Math.max,ly=Math.min;jc.exports=function(i,e){var t=oy(i);return t<0?uy(t+e,0):ly(t,e)}});var Wc=m((BL,Yc)=>{"use strict";var cy=ka(),dy=Math.min;Yc.exports=function(i){var e=cy(i);return e>0?dy(e,9007199254740991):0}});var wa=m((_L,Qc)=>{"use strict";var py=Wc();Qc.exports=function(i){return py(i.length)}});var Jc=m((NL,Kc)=>{"use strict";var hy=er(),my=Gc(),fy=wa(),zc=function(i){return function(e,t,r){var a=hy(e),s=fy(a);if(s===0)return!i&&-1;var n=my(r,s),o;if(i&&t!==t){for(;s>n;)if(o=a[n++],o!==o)return!0}else for(;s>n;n++)if((i||n in a)&&a[n]===t)return i||n||0;return!i&&-1}};Kc.exports={includes:zc(!0),indexOf:zc(!1)}});var ed=m((FL,Zc)=>{"use strict";var by=ie(),Rn=Oe(),Sy=er(),gy=Jc().indexOf,vy=Ea(),Xc=by([].push);Zc.exports=function(i,e){var t=Sy(i),r=0,a=[],s;for(s in t)!Rn(vy,s)&&Rn(t,s)&&Xc(a,s);for(;e.length>r;)Rn(t,s=e[r++])&&(~gy(a,s)||Xc(a,s));return a}});var Ln=m((qL,td)=>{"use strict";td.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var id=m((UL,rd)=>{"use strict";var yy=ed(),Ty=Ln();rd.exports=Object.keys||function(e){return yy(e,Ty)}});var sd=m(ad=>{"use strict";var Iy=Te(),Ey=en(),xy=Lt(),Py=je(),ky=er(),wy=id();ad.f=Iy&&!Ey?Object.defineProperties:function(e,t){Py(e);for(var r=ky(t),a=wy(t),s=a.length,n=0,o;s>n;)xy.f(e,o=a[n++],r[o]);return e}});var $n=m((jL,nd)=>{"use strict";var Ay=Ke();nd.exports=Ay("document","documentElement")});var On=m((GL,hd)=>{"use strict";var Ry=je(),Ly=sd(),od=Ln(),$y=Ea(),My=$n(),Cy=Sa(),Dy=Ia(),ud=">",ld="<",Cn="prototype",Dn="script",dd=Dy("IE_PROTO"),Mn=function(){},pd=function(i){return ld+Dn+ud+i+ld+"/"+Dn+ud},cd=function(i){i.write(pd("")),i.close();var e=i.parentWindow.Object;return i=null,e},Oy=function(){var i=Cy("iframe"),e="java"+Dn+":",t;return i.style.display="none",My.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(pd("document.F=Object")),t.close(),t.F},Aa,Ra=function(){try{Aa=new ActiveXObject("htmlfile")}catch{}Ra=typeof document<"u"?document.domain&&Aa?cd(Aa):Oy():cd(Aa);for(var i=od.length;i--;)delete Ra[Cn][od[i]];return Ra()};$y[dd]=!0;hd.exports=Object.create||function(e,t){var r;return e!==null?(Mn[Cn]=Ry(e),r=new Mn,Mn[Cn]=null,r[dd]=e):r=Ra(),t===void 0?r:Ly.f(r,t)}});var fd=m((YL,md)=>{"use strict";var Vy=he();md.exports=!Vy(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var Bn=m((WL,Sd)=>{"use strict";var By=Oe(),_y=F(),Ny=Fr(),Fy=Ia(),qy=fd(),bd=Fy("IE_PROTO"),Vn=Object,Uy=Vn.prototype;Sd.exports=qy?Vn.getPrototypeOf:function(i){var e=Ny(i);if(By(e,bd))return e[bd];var t=e.constructor;return _y(t)&&e instanceof t?t.prototype:e instanceof Vn?Uy:null}});var nr=m((QL,gd)=>{"use strict";var Hy=ir();gd.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:Hy(i,e,t),i}});var qn=m((zL,Td)=>{"use strict";var jy=he(),Gy=F(),Yy=ye(),Wy=On(),vd=Bn(),Qy=nr(),zy=ee(),Ky=De(),Fn=zy("iterator"),yd=!1,Xe,_n,Nn;[].keys&&(Nn=[].keys(),"next"in Nn?(_n=vd(vd(Nn)),_n!==Object.prototype&&(Xe=_n)):yd=!0);var Jy=!Yy(Xe)||jy(function(){var i={};return Xe[Fn].call(i)!==i});Jy?Xe={}:Ky&&(Xe=Wy(Xe));Gy(Xe[Fn])||Qy(Xe,Fn,function(){return this});Td.exports={IteratorPrototype:Xe,BUGGY_SAFARI_ITERATORS:yd}});var La=m((KL,Ed)=>{"use strict";var Xy=ee(),Zy=Xy("toStringTag"),Id={};Id[Zy]="z";Ed.exports=String(Id)==="[object z]"});var Yr=m((JL,xd)=>{"use strict";var eT=La(),tT=F(),$a=Xt(),rT=ee(),iT=rT("toStringTag"),aT=Object,sT=$a(function(){return arguments}())==="Arguments",nT=function(i,e){try{return i[e]}catch{}};xd.exports=eT?$a:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=nT(e=aT(i),iT))=="string"?t:sT?$a(e):(r=$a(e))==="Object"&&tT(e.callee)?"Arguments":r}});var kd=m((XL,Pd)=>{"use strict";var oT=La(),uT=Yr();Pd.exports=oT?{}.toString:function(){return"[object "+uT(this)+"]"}});var Wr=m((ZL,Ad)=>{"use strict";var lT=La(),cT=Lt().f,dT=ir(),pT=Oe(),hT=kd(),mT=ee(),wd=mT("toStringTag");Ad.exports=function(i,e,t,r){var a=t?i:i&&i.prototype;a&&(pT(a,wd)||cT(a,wd,{configurable:!0,value:e}),r&&!lT&&dT(a,"toString",hT))}});var Ld=m((e$,Rd)=>{"use strict";var fT=qn().IteratorPrototype,bT=On(),ST=qr(),gT=Wr(),vT=Rt(),yT=function(){return this};Rd.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=bT(fT,{next:ST(+!r,t)}),gT(i,a,!1,!0),vT[a]=yT,i}});var Md=m((t$,$d)=>{"use strict";var TT=ie(),IT=Je();$d.exports=function(i,e,t){try{return TT(IT(Object.getOwnPropertyDescriptor(i,e)[t]))}catch{}}});var Dd=m((r$,Cd)=>{"use strict";var ET=ye();Cd.exports=function(i){return ET(i)||i===null}});var Vd=m((i$,Od)=>{"use strict";var xT=Dd(),PT=String,kT=TypeError;Od.exports=function(i){if(xT(i))return i;throw new kT("Can't set "+PT(i)+" as a prototype")}});var Un=m((a$,Bd)=>{"use strict";var wT=Md(),AT=ye(),RT=Dr(),LT=Vd();Bd.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=wT(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch{}return function(a,s){return RT(a),LT(s),AT(a)&&(i?t(a,s):a.__proto__=s),a}}():void 0)});var Qd=m((s$,Wd)=>{"use strict";var $T=Ie(),MT=me(),Ma=De(),Gd=Fc(),CT=F(),DT=Ld(),_d=Bn(),Nd=Un(),OT=Wr(),VT=ir(),Hn=nr(),BT=ee(),Fd=Rt(),Yd=qn(),_T=Gd.PROPER,NT=Gd.CONFIGURABLE,qd=Yd.IteratorPrototype,Ca=Yd.BUGGY_SAFARI_ITERATORS,Qr=BT("iterator"),Ud="keys",zr="values",Hd="entries",jd=function(){return this};Wd.exports=function(i,e,t,r,a,s,n){DT(t,e,r);var o=function(v){if(v===a&&p)return p;if(!Ca&&v&&v in c)return c[v];switch(v){case Ud:return function(){return new t(this,v)};case zr:return function(){return new t(this,v)};case Hd:return function(){return new t(this,v)}}return function(){return new t(this)}},l=e+" Iterator",u=!1,c=i.prototype,d=c[Qr]||c["@@iterator"]||a&&c[a],p=!Ca&&d||o(a),h=e==="Array"&&c.entries||d,f,b,S;if(h&&(f=_d(h.call(new i)),f!==Object.prototype&&f.next&&(!Ma&&_d(f)!==qd&&(Nd?Nd(f,qd):CT(f[Qr])||Hn(f,Qr,jd)),OT(f,l,!0,!0),Ma&&(Fd[l]=jd))),_T&&a===zr&&d&&d.name!==zr&&(!Ma&&NT?VT(c,"name",zr):(u=!0,p=function(){return MT(d,this)})),a)if(b={values:o(zr),keys:s?p:o(Ud),entries:o(Hd)},n)for(S in b)(Ca||u||!(S in c))&&Hn(c,S,b[S]);else $T({target:e,proto:!0,forced:Ca||u},b);return(!Ma||n)&&c[Qr]!==p&&Hn(c,Qr,p,{name:a}),Fd[e]=p,b}});var Kd=m((n$,zd)=>{"use strict";zd.exports=function(i,e){return{value:i,done:e}}});var Gn=m((o$,tp)=>{"use strict";var FT=er(),jn=zs(),Jd=Rt(),Zd=En(),qT=Lt().f,UT=Qd(),Da=Kd(),HT=De(),jT=Te(),ep="Array Iterator",GT=Zd.set,YT=Zd.getterFor(ep);tp.exports=UT(Array,"Array",function(i,e){GT(this,{type:ep,target:FT(i),index:0,kind:e})},function(){var i=YT(this),e=i.target,t=i.index++;if(!e||t>=e.length)return i.target=void 0,Da(void 0,!0);switch(i.kind){case"keys":return Da(t,!1);case"values":return Da(e[t],!1)}return Da([t,e[t]],!1)},"values");var Xd=Jd.Arguments=Jd.Array;jn("keys");jn("values");jn("entries");if(!HT&&jT&&Xd.name!=="values")try{qT(Xd,"name",{value:"values"})}catch{}});var ip=m((u$,rp)=>{"use strict";var WT=ee(),QT=Rt(),zT=WT("iterator"),KT=Array.prototype;rp.exports=function(i){return i!==void 0&&(QT.Array===i||KT[zT]===i)}});var Yn=m((l$,sp)=>{"use strict";var JT=Yr(),ap=_r(),XT=Zt(),ZT=Rt(),eI=ee(),tI=eI("iterator");sp.exports=function(i){if(!XT(i))return ap(i,tI)||ap(i,"@@iterator")||ZT[JT(i)]}});var op=m((c$,np)=>{"use strict";var rI=me(),iI=Je(),aI=je(),sI=Br(),nI=Yn(),oI=TypeError;np.exports=function(i,e){var t=arguments.length<2?nI(i):e;if(iI(t))return aI(rI(t,i));throw new oI(sI(i)+" is not iterable")}});var cp=m((d$,lp)=>{"use strict";var uI=me(),up=je(),lI=_r();lp.exports=function(i,e,t){var r,a;up(i);try{if(r=lI(i,"return"),!r){if(e==="throw")throw t;return t}r=uI(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return up(r),t}});var Va=m((p$,mp)=>{"use strict";var cI=jr(),dI=me(),pI=je(),hI=Br(),mI=ip(),fI=wa(),dp=Vr(),bI=op(),SI=Yn(),pp=cp(),gI=TypeError,Oa=function(i,e){this.stopped=i,this.result=e},hp=Oa.prototype;mp.exports=function(i,e,t){var r=t&&t.that,a=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),l=cI(e,r),u,c,d,p,h,f,b,S=function(A){return u&&pp(u,"normal",A),new Oa(!0,A)},v=function(A){return a?(pI(A),o?l(A[0],A[1],S):l(A[0],A[1])):o?l(A,S):l(A)};if(s)u=i.iterator;else if(n)u=i;else{if(c=SI(i),!c)throw new gI(hI(i)+" is not iterable");if(mI(c)){for(d=0,p=fI(i);p>d;d++)if(h=v(i[d]),h&&dp(hp,h))return h;return new Oa(!1)}u=bI(i,c)}for(f=s?i.next:u.next;!(b=dI(f,u)).done;){try{h=v(b.value)}catch(A){pp(u,"throw",A)}if(typeof h=="object"&&h&&dp(hp,h))return h}return new Oa(!1)}});var bp=m((h$,fp)=>{"use strict";var vI=Te(),yI=Lt(),TI=qr();fp.exports=function(i,e,t){vI?yI.f(i,e,TI(0,t)):i[e]=t}});var Sp=m(()=>{"use strict";var II=Ie(),EI=Va(),xI=bp();II({target:"Object",stat:!0},{fromEntries:function(e){var t={};return EI(e,function(r,a){xI(t,r,a)},{AS_ENTRIES:!0}),t}})});var vp=m((b$,gp)=>{"use strict";Gn();Sp();var PI=va();gp.exports=PI.Object.fromEntries});var Tp=m((S$,yp)=>{"use strict";yp.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 Ep=m(()=>{"use strict";Gn();var kI=Tp(),wI=q(),AI=Wr(),Ip=Rt();for(Ba in kI)AI(wI[Ba],Ba),Ip[Ba]=Ip.Array;var Ba});var Pp=m((y$,xp)=>{"use strict";var RI=vp();Ep();xp.exports=RI});var Wn=m((T$,kp)=>{"use strict";var LI=Pp();kp.exports=LI});var wp=m(()=>{"use strict"});var Qn=m((x$,Ap)=>{"use strict";var Kr=q(),$I=tr(),MI=Xt(),_a=function(i){return $I.slice(0,i.length)===i};Ap.exports=function(){return _a("Bun/")?"BUN":_a("Cloudflare-Workers")?"CLOUDFLARE":_a("Deno/")?"DENO":_a("Node.js/")?"NODE":Kr.Bun&&typeof Bun.version=="string"?"BUN":Kr.Deno&&typeof Deno.version=="object"?"DENO":MI(Kr.process)==="process"?"NODE":Kr.window&&Kr.document?"BROWSER":"REST"}()});var Na=m((P$,Rp)=>{"use strict";var CI=Qn();Rp.exports=CI==="NODE"});var $p=m((k$,Lp)=>{"use strict";var DI=Lt();Lp.exports=function(i,e,t){return DI.f(i,e,t)}});var Dp=m((w$,Cp)=>{"use strict";var OI=Ke(),VI=$p(),BI=ee(),_I=Te(),Mp=BI("species");Cp.exports=function(i){var e=OI(i);_I&&e&&!e[Mp]&&VI(e,Mp,{configurable:!0,get:function(){return this}})}});var Vp=m((A$,Op)=>{"use strict";var NI=Vr(),FI=TypeError;Op.exports=function(i,e){if(NI(e,i))return i;throw new FI("Incorrect invocation")}});var Kn=m((R$,Bp)=>{"use strict";var qI=ie(),UI=F(),zn=Nr(),HI=qI(Function.toString);UI(zn.inspectSource)||(zn.inspectSource=function(i){return HI(i)});Bp.exports=zn.inspectSource});var Hp=m((L$,Up)=>{"use strict";var jI=ie(),GI=he(),_p=F(),YI=Yr(),WI=Ke(),QI=Kn(),Np=function(){},Fp=WI("Reflect","construct"),Jn=/^\s*(?:class|function)\b/,zI=jI(Jn.exec),KI=!Jn.test(Np),Jr=function(e){if(!_p(e))return!1;try{return Fp(Np,[],e),!0}catch{return!1}},qp=function(e){if(!_p(e))return!1;switch(YI(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return KI||!!zI(Jn,QI(e))}catch{return!0}};qp.sham=!0;Up.exports=!Fp||GI(function(){var i;return Jr(Jr.call)||!Jr(Object)||!Jr(function(){i=!0})||i})?qp:Jr});var Gp=m(($$,jp)=>{"use strict";var JI=Hp(),XI=Br(),ZI=TypeError;jp.exports=function(i){if(JI(i))return i;throw new ZI(XI(i)+" is not a constructor")}});var Xn=m((M$,Wp)=>{"use strict";var Yp=je(),eE=Gp(),tE=Zt(),rE=ee(),iE=rE("species");Wp.exports=function(i,e){var t=Yp(i).constructor,r;return t===void 0||tE(r=Yp(t)[iE])?e:eE(r)}});var zp=m((C$,Qp)=>{"use strict";var aE=ie();Qp.exports=aE([].slice)});var Jp=m((D$,Kp)=>{"use strict";var sE=TypeError;Kp.exports=function(i,e){if(i<e)throw new sE("Not enough arguments");return i}});var Zn=m((O$,Xp)=>{"use strict";var nE=tr();Xp.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(nE)});var uo=m((V$,oh)=>{"use strict";var fe=q(),oE=xn(),uE=jr(),Zp=F(),lE=Oe(),nh=he(),eh=$n(),cE=zp(),th=Sa(),dE=Jp(),pE=Zn(),hE=Na(),so=fe.setImmediate,no=fe.clearImmediate,mE=fe.process,eo=fe.Dispatch,fE=fe.Function,rh=fe.MessageChannel,bE=fe.String,to=0,Xr={},ih="onreadystatechange",Zr,Mt,ro,io;nh(function(){Zr=fe.location});var oo=function(i){if(lE(Xr,i)){var e=Xr[i];delete Xr[i],e()}},ao=function(i){return function(){oo(i)}},ah=function(i){oo(i.data)},sh=function(i){fe.postMessage(bE(i),Zr.protocol+"//"+Zr.host)};(!so||!no)&&(so=function(e){dE(arguments.length,1);var t=Zp(e)?e:fE(e),r=cE(arguments,1);return Xr[++to]=function(){oE(t,void 0,r)},Mt(to),to},no=function(e){delete Xr[e]},hE?Mt=function(i){mE.nextTick(ao(i))}:eo&&eo.now?Mt=function(i){eo.now(ao(i))}:rh&&!pE?(ro=new rh,io=ro.port2,ro.port1.onmessage=ah,Mt=uE(io.postMessage,io)):fe.addEventListener&&Zp(fe.postMessage)&&!fe.importScripts&&Zr&&Zr.protocol!=="file:"&&!nh(sh)?(Mt=sh,fe.addEventListener("message",ah,!1)):ih in th("script")?Mt=function(i){eh.appendChild(th("script"))[ih]=function(){eh.removeChild(this),oo(i)}}:Mt=function(i){setTimeout(ao(i),0)});oh.exports={set:so,clear:no}});var ch=m((B$,lh)=>{"use strict";var uh=q(),SE=Te(),gE=Object.getOwnPropertyDescriptor;lh.exports=function(i){if(!SE)return uh[i];var e=gE(uh,i);return e&&e.value}});var lo=m((_$,ph)=>{"use strict";var dh=function(){this.head=null,this.tail=null};dh.prototype={add:function(i){var e={item:i,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var i=this.head;if(i){var e=this.head=i.next;return e===null&&(this.tail=null),i.item}}};ph.exports=dh});var mh=m((N$,hh)=>{"use strict";var vE=tr();hh.exports=/ipad|iphone|ipod/i.test(vE)&&typeof Pebble<"u"});var bh=m((F$,fh)=>{"use strict";var yE=tr();fh.exports=/web0s(?!.*chrome)/i.test(yE)});var Eh=m((q$,Ih)=>{"use strict";var ur=q(),TE=ch(),Sh=jr(),co=uo().set,IE=lo(),EE=Zn(),xE=mh(),PE=bh(),po=Na(),gh=ur.MutationObserver||ur.WebKitMutationObserver,vh=ur.document,yh=ur.process,Fa=ur.Promise,fo=TE("queueMicrotask"),or,ho,mo,qa,Th;fo||(ei=new IE,ti=function(){var i,e;for(po&&(i=yh.domain)&&i.exit();e=ei.get();)try{e()}catch(t){throw ei.head&&or(),t}i&&i.enter()},!EE&&!po&&!PE&&gh&&vh?(ho=!0,mo=vh.createTextNode(""),new gh(ti).observe(mo,{characterData:!0}),or=function(){mo.data=ho=!ho}):!xE&&Fa&&Fa.resolve?(qa=Fa.resolve(void 0),qa.constructor=Fa,Th=Sh(qa.then,qa),or=function(){Th(ti)}):po?or=function(){yh.nextTick(ti)}:(co=Sh(co,ur),or=function(){co(ti)}),fo=function(i){ei.head||or(),ei.add(i)});var ei,ti;Ih.exports=fo});var Ph=m((U$,xh)=>{"use strict";xh.exports=function(i,e){try{arguments.length===1?console.error(i):console.error(i,e)}catch{}}});var Ua=m((H$,kh)=>{"use strict";kh.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var Ct=m((j$,wh)=>{"use strict";var kE=q();wh.exports=kE.Promise});var lr=m((G$,$h)=>{"use strict";var wE=q(),ri=Ct(),AE=F(),RE=kn(),LE=Kn(),$E=ee(),Ah=Qn(),ME=De(),bo=sn(),Rh=ri&&ri.prototype,CE=$E("species"),So=!1,Lh=AE(wE.PromiseRejectionEvent),DE=RE("Promise",function(){var i=LE(ri),e=i!==String(ri);if(!e&&bo===66||ME&&!(Rh.catch&&Rh.finally))return!0;if(!bo||bo<51||!/native code/.test(i)){var t=new ri(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[CE]=r,So=t.then(function(){})instanceof r,!So)return!0}return!e&&(Ah==="BROWSER"||Ah==="DENO")&&!Lh});$h.exports={CONSTRUCTOR:DE,REJECTION_EVENT:Lh,SUBCLASSING:So}});var cr=m((Y$,Ch)=>{"use strict";var Mh=Je(),OE=TypeError,VE=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw new OE("Bad Promise constructor");e=r,t=a}),this.resolve=Mh(e),this.reject=Mh(t)};Ch.exports.f=function(i){return new VE(i)}});var Xh=m(()=>{"use strict";var BE=Ie(),_E=De(),Ya=Na(),ht=q(),mr=me(),Dh=nr(),Oh=Un(),NE=Wr(),FE=Dp(),qE=Je(),Ga=F(),UE=ye(),HE=Vp(),jE=Xn(),Fh=uo().set,Io=Eh(),GE=Ph(),YE=Ua(),WE=lo(),qh=En(),Wa=Ct(),Eo=lr(),Uh=cr(),Qa="Promise",Hh=Eo.CONSTRUCTOR,QE=Eo.REJECTION_EVENT,zE=Eo.SUBCLASSING,go=qh.getterFor(Qa),KE=qh.set,dr=Wa&&Wa.prototype,Dt=Wa,Ha=dr,jh=ht.TypeError,vo=ht.document,xo=ht.process,yo=Uh.f,JE=yo,XE=!!(vo&&vo.createEvent&&ht.dispatchEvent),Gh="unhandledrejection",ZE="rejectionhandled",Vh=0,Yh=1,ex=2,Po=1,Wh=2,ja,Bh,tx,_h,Qh=function(i){var e;return UE(i)&&Ga(e=i.then)?e:!1},zh=function(i,e){var t=e.value,r=e.state===Yh,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,l,u,c;try{a?(r||(e.rejection===Wh&&ix(e),e.rejection=Po),a===!0?l=t:(o&&o.enter(),l=a(t),o&&(o.exit(),c=!0)),l===i.promise?n(new jh("Promise-chain cycle")):(u=Qh(l))?mr(u,l,s,n):s(l)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Kh=function(i,e){i.notified||(i.notified=!0,Io(function(){for(var t=i.reactions,r;r=t.get();)zh(r,i);i.notified=!1,e&&!i.rejection&&rx(i)}))},Jh=function(i,e,t){var r,a;XE?(r=vo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),ht.dispatchEvent(r)):r={promise:e,reason:t},!QE&&(a=ht["on"+i])?a(r):i===Gh&&GE("Unhandled promise rejection",t)},rx=function(i){mr(Fh,ht,function(){var e=i.facade,t=i.value,r=Nh(i),a;if(r&&(a=YE(function(){Ya?xo.emit("unhandledRejection",t,e):Jh(Gh,e,t)}),i.rejection=Ya||Nh(i)?Wh:Po,a.error))throw a.value})},Nh=function(i){return i.rejection!==Po&&!i.parent},ix=function(i){mr(Fh,ht,function(){var e=i.facade;Ya?xo.emit("rejectionHandled",e):Jh(ZE,e,i.value)})},pr=function(i,e,t){return function(r){i(e,r,t)}},hr=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=ex,Kh(i,!0))},To=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw new jh("Promise can't be resolved itself");var r=Qh(e);r?Io(function(){var a={done:!1};try{mr(r,e,pr(To,a,i),pr(hr,a,i))}catch(s){hr(a,s,i)}}):(i.value=e,i.state=Yh,Kh(i,!1))}catch(a){hr({done:!1},a,i)}}};if(Hh&&(Dt=function(e){HE(this,Ha),qE(e),mr(ja,this);var t=go(this);try{e(pr(To,t),pr(hr,t))}catch(r){hr(t,r)}},Ha=Dt.prototype,ja=function(e){KE(this,{type:Qa,done:!1,notified:!1,parent:!1,reactions:new WE,rejection:!1,state:Vh,value:void 0})},ja.prototype=Dh(Ha,"then",function(e,t){var r=go(this),a=yo(jE(this,Dt));return r.parent=!0,a.ok=Ga(e)?e:!0,a.fail=Ga(t)&&t,a.domain=Ya?xo.domain:void 0,r.state===Vh?r.reactions.add(a):Io(function(){zh(a,r)}),a.promise}),Bh=function(){var i=new ja,e=go(i);this.promise=i,this.resolve=pr(To,e),this.reject=pr(hr,e)},Uh.f=yo=function(i){return i===Dt||i===tx?new Bh(i):JE(i)},!_E&&Ga(Wa)&&dr!==Object.prototype)){_h=dr.then,zE||Dh(dr,"then",function(e,t){var r=this;return new Dt(function(a,s){mr(_h,r,a,s)}).then(e,t)},{unsafe:!0});try{delete dr.constructor}catch{}Oh&&Oh(dr,Ha)}BE({global:!0,constructor:!0,wrap:!0,forced:Hh},{Promise:Dt});NE(Dt,Qa,!1,!0);FE(Qa)});var im=m((z$,rm)=>{"use strict";var ax=ee(),em=ax("iterator"),tm=!1;try{Zh=0,ko={next:function(){return{done:!!Zh++}},return:function(){tm=!0}},ko[em]=function(){return this},Array.from(ko,function(){throw 2})}catch{}var Zh,ko;rm.exports=function(i,e){try{if(!e&&!tm)return!1}catch{return!1}var t=!1;try{var r={};r[em]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch{}return t}});var wo=m((K$,am)=>{"use strict";var sx=Ct(),nx=im(),ox=lr().CONSTRUCTOR;am.exports=ox||!nx(function(i){sx.all(i).then(void 0,function(){})})});var sm=m(()=>{"use strict";var ux=Ie(),lx=me(),cx=Je(),dx=cr(),px=Ua(),hx=Va(),mx=wo();ux({target:"Promise",stat:!0,forced:mx},{all:function(e){var t=this,r=dx.f(t),a=r.resolve,s=r.reject,n=px(function(){var o=cx(t.resolve),l=[],u=0,c=1;hx(e,function(d){var p=u++,h=!1;c++,lx(o,t,d).then(function(f){h||(h=!0,l[p]=f,--c||a(l))},s)}),--c||a(l)});return n.error&&s(n.value),r.promise}})});var om=m(()=>{"use strict";var fx=Ie(),bx=De(),Sx=lr().CONSTRUCTOR,Ro=Ct(),gx=Ke(),vx=F(),yx=nr(),nm=Ro&&Ro.prototype;fx({target:"Promise",proto:!0,forced:Sx,real:!0},{catch:function(i){return this.then(void 0,i)}});!bx&&vx(Ro)&&(Ao=gx("Promise").prototype.catch,nm.catch!==Ao&&yx(nm,"catch",Ao,{unsafe:!0}));var Ao});var um=m(()=>{"use strict";var Tx=Ie(),Ix=me(),Ex=Je(),xx=cr(),Px=Ua(),kx=Va(),wx=wo();Tx({target:"Promise",stat:!0,forced:wx},{race:function(e){var t=this,r=xx.f(t),a=r.reject,s=Px(function(){var n=Ex(t.resolve);kx(e,function(o){Ix(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var lm=m(()=>{"use strict";var Ax=Ie(),Rx=cr(),Lx=lr().CONSTRUCTOR;Ax({target:"Promise",stat:!0,forced:Lx},{reject:function(e){var t=Rx.f(this),r=t.reject;return r(e),t.promise}})});var Lo=m((sM,cm)=>{"use strict";var $x=je(),Mx=ye(),Cx=cr();cm.exports=function(i,e){if($x(i),Mx(e)&&e.constructor===i)return e;var t=Cx.f(i),r=t.resolve;return r(e),t.promise}});var hm=m(()=>{"use strict";var Dx=Ie(),Ox=Ke(),dm=De(),Vx=Ct(),pm=lr().CONSTRUCTOR,Bx=Lo(),_x=Ox("Promise"),Nx=dm&&!pm;Dx({target:"Promise",stat:!0,forced:dm||pm},{resolve:function(e){return Bx(Nx&&this===_x?Vx:this,e)}})});var mm=m(()=>{"use strict";Xh();sm();om();um();lm();hm()});var gm=m(()=>{"use strict";var Fx=Ie(),qx=De(),za=Ct(),Ux=he(),bm=Ke(),Sm=F(),Hx=Xn(),fm=Lo(),jx=nr(),Mo=za&&za.prototype,Gx=!!za&&Ux(function(){Mo.finally.call({then:function(){}},function(){})});Fx({target:"Promise",proto:!0,real:!0,forced:Gx},{finally:function(i){var e=Hx(this,bm("Promise")),t=Sm(i);return this.then(t?function(r){return fm(e,i()).then(function(){return r})}:i,t?function(r){return fm(e,i()).then(function(){throw r})}:i)}});!qx&&Sm(za)&&($o=bm("Promise").prototype.finally,Mo.finally!==$o&&jx(Mo,"finally",$o,{unsafe:!0}));var $o});var Ka=m((pM,vm)=>{"use strict";var Yx=Ke();vm.exports=Yx});var Tm=m((hM,ym)=>{"use strict";wp();mm();gm();var Wx=Ka();ym.exports=Wx("Promise","finally")});var Em=m((mM,Im)=>{"use strict";var Qx=Tm();Im.exports=Qx});var Ja=m((fM,xm)=>{"use strict";var zx=Em();xm.exports=zx});var zm=m(()=>{"use strict";var xP=Ie(),PP=Fr(),kP=wa(),wP=ka(),AP=zs();xP({target:"Array",proto:!0},{at:function(e){var t=PP(this),r=kP(t),a=wP(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});AP("at")});var Jm=m((xC,Km)=>{"use strict";zm();var RP=Ka();Km.exports=RP("Array","at")});var Zm=m((PC,Xm)=>{"use strict";var LP=Jm();Xm.exports=LP});var ni=m((kC,ef)=>{"use strict";var $P=Zm();ef.exports=$P});var Hf=m(()=>{"use strict"});var jf=m(()=>{"use strict"});var Yf=m((kV,Gf)=>{"use strict";var qk=ye(),Uk=Xt(),Hk=ee(),jk=Hk("match");Gf.exports=function(i){var e;return qk(i)&&((e=i[jk])!==void 0?!!e:Uk(i)==="RegExp")}});var Qf=m((wV,Wf)=>{"use strict";var Gk=Yr(),Yk=String;Wf.exports=function(i){if(Gk(i)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return Yk(i)}});var Kf=m((AV,zf)=>{"use strict";var Wk=je();zf.exports=function(){var i=Wk(this),e="";return i.hasIndices&&(e+="d"),i.global&&(e+="g"),i.ignoreCase&&(e+="i"),i.multiline&&(e+="m"),i.dotAll&&(e+="s"),i.unicode&&(e+="u"),i.unicodeSets&&(e+="v"),i.sticky&&(e+="y"),e}});var Zf=m((RV,Xf)=>{"use strict";var Qk=me(),zk=Oe(),Kk=Vr(),Jk=Kf(),Jf=RegExp.prototype;Xf.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in Jf)&&!zk(i,"flags")&&Kk(Jf,i)?Qk(Jk,i):e}});var tb=m((LV,eb)=>{"use strict";var uu=ie(),Xk=Fr(),Zk=Math.floor,nu=uu("".charAt),ew=uu("".replace),ou=uu("".slice),tw=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,rw=/\$([$&'`]|\d{1,2})/g;eb.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,l=rw;return a!==void 0&&(a=Xk(a),l=tw),ew(s,l,function(u,c){var d;switch(nu(c,0)){case"$":return"$";case"&":return i;case"`":return ou(e,0,t);case"'":return ou(e,n);case"<":d=a[ou(c,1,-1)];break;default:var p=+c;if(p===0)return u;if(p>o){var h=Zk(p/10);return h===0?u:h<=o?r[h-1]===void 0?nu(c,1):r[h-1]+nu(c,1):u}d=r[p-1]}return d===void 0?"":d})}});var ab=m(()=>{"use strict";var iw=Ie(),aw=me(),cu=ie(),rb=Dr(),sw=F(),nw=Zt(),ow=Yf(),xr=Qf(),uw=_r(),lw=Zf(),cw=tb(),dw=ee(),pw=De(),hw=dw("replace"),mw=TypeError,lu=cu("".indexOf),fw=cu("".replace),ib=cu("".slice),bw=Math.max;iw({target:"String",proto:!0},{replaceAll:function(e,t){var r=rb(this),a,s,n,o,l,u,c,d,p,h,f=0,b="";if(!nw(e)){if(a=ow(e),a&&(s=xr(rb(lw(e))),!~lu(s,"g")))throw new mw("`.replaceAll` does not allow non-global regexes");if(n=uw(e,hw),n)return aw(n,e,r,t);if(pw&&a)return fw(xr(r),e,t)}for(o=xr(r),l=xr(e),u=sw(t),u||(t=xr(t)),c=l.length,d=bw(1,c),p=lu(o,l);p!==-1;)h=u?xr(t(l,p,o)):cw(l,o,p,[],void 0,t),b+=ib(o,f,p)+h,f=p+c,p=p+d>o.length?-1:lu(o,l,p+d);return f<o.length&&(b+=ib(o,f)),b}})});var nb=m((CV,sb)=>{"use strict";Hf();jf();ab();var Sw=Ka();sb.exports=Sw("String","replaceAll")});var ub=m((DV,ob)=>{"use strict";var gw=nb();ob.exports=gw});var cb=m((OV,lb)=>{"use strict";var vw=ub();lb.exports=vw});var ju="2.0.108-dev.377c6d18.0";var re=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(re||{}),pt=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(pt||{});var ma=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(ma||{}),Hs=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Hs||{});var js=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(js||{});import{assertNever as Ku,assertNonNullable as OS,isNonNullable as fa,ValueSubject as Gs,Subject as VS,Subscription as BS,merge as _S,observableFrom as NS,fromEvent as Yu,map as Wu,tap as Qu,filterChanged as FS,isNullable as Ys,ErrorCategory as zu}from"@vkontakte/videoplayer-shared";var Gu=i=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",i),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var ba=class{constructor(e){this.connection$=new Gs(void 0);this.castState$=new Gs("NOT_AVAILABLE");this.errorEvent$=new VS;this.realCastState$=new Gs("NOT_AVAILABLE");this.subscription=new BS;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=fa(window.chrome?.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},a||Gu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:zu.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){fa(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Ys(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Ys(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(Yu(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{switch(a.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=r.getCurrentSession()?.getMediaSession()?.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Ku(a.sessionState)}})).add(_S(Yu(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Qu(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),Wu(a=>a.castState)),NS([r.getCastState()])).pipe(FS(),Wu(qS),Qu(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=fa(this.connection$.getValue());if(s&&!n){let o=r.getCurrentSession();OS(o);let l=o.getCastDevice(),u=o.getMediaSession()?.media.contentId;(Ys(u)||u===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:l}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a==="CONNECTED"?fa(this.connection$.getValue())?"CONNECTED":"AVAILABLE":a)}))}initializeCastApi(){let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:zu.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},qS=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return Ku(i)}};var oS=He(Wn(),1);var Dm=He(Ja(),1);import{assertNever as Pm}from"@vkontakte/videoplayer-shared";var K=(i,e=0,t=0)=>{switch(t){case 0:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return i;let r=new URL(i);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(i);return!r.searchParams.get("offset_p")&&e===0?i:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:Pm(t)}return i},Co=(i,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(i);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(i);return Number(t.searchParams.get("offset_p")??0)}default:Pm(e)}};var I=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};import{isNonNullable as Kx,Subject as Xa,merge as km}from"@vkontakte/videoplayer-shared";var L=class{constructor(e){this.transitionStarted$=new Xa;this.transitionEnded$=new Xa;this.transitionUpdated$=new Xa;this.forceChanged$=new Xa;this.stateChangeStarted$=km(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=km(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,r=this.state;this.transition=void 0,this.prevState=r,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:r,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,r=this.state;r===e||Kx(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as Jx}from"@vkontakte/videoplayer-shared";var wm=i=>{switch(i){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return Jx(i)}};import{assertNever as fr,assertNonNullable as Ot,debounce as Am,ErrorCategory as Rm,fromEvent as Vt,isNonNullable as Lm,map as $m,merge as Mm,observableFrom as Xx,Subject as Zx,Subscription as Do,timeout as eP,getHighestQuality as tP}from"@vkontakte/videoplayer-shared";var rP=5,iP=5,aP=500,Cm=7e3,ii=class{constructor(e){this.subscription=new Do;this.loadMediaTimeoutSubscription=new Do;this.videoState=new L("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(a?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:fr(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:fr(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:fr(e)}break}default:fr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(wm(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 Do;this.subscription.add(e),this.subscription.add(Mm(this.videoState.stateChangeStarted$.pipe($m(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe($m(a=>`stateChangeEnded$ ${JSON.stringify(a)}`))).subscribe(a=>this.log({message:`[videoState] ${a}`})));let t=(a,s)=>this.subscription.add(a.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let a=new Zx;e.add(a.pipe(Am(aP)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Vt(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)>rP)&&a.next(o),s=o})),e.add(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{this.logRemoteEvent(a);let{remotePlayer:s}=this.params.connection,n=a.value,o=this.params.output.isBuffering$.getValue(),l=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==l&&this.params.output.isBuffering$.next(l),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<iP&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),I(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:fr(n)}}),t(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=Mm(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Xx(["init"])).pipe(Am(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),I(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),I(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&I(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),r={volume:e.volume??t.volume,muted:e.muted??t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,r,a,s;switch(e){case"MPEG":{let u=t[e];Ot(u);let c=tP(Object.keys(u));Ot(c);let d=u[c];Ot(d),r=d,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let u=t[e];Ot(u),r=u.url,a="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let u=t[e];Ot(u),r=u.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let u=t[e];Ot(u),r=u.url,a="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=t[e];Ot(u),r=K(u.url),a="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let u="Unsupported format for Chromecast",c=new Error(u);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Rm.VIDEO_PIPELINE,message:u,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return fr(e)}let n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??r,a);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:l}=this.params.meta;return Lm(o)&&(n.metadata.title=o),Lm(l)&&(n.metadata.subtitle=l),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((a,s)=>{this.loadMediaTimeoutSubscription.add(eP(Cm).subscribe(()=>s(`timeout(${Cm})`)))});(0,Dm.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},a=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${a}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Rm.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as Vm}from"@vkontakte/videoplayer-shared";import{clearVideoElement as sP}from"@vkontakte/videoplayer-shared";var Om=i=>{try{i.pause(),i.playbackRate=0,sP(i),i.remove()}catch(e){console.error(e)}};import{fromEvent as nP,Subscription as oP}from"@vkontakte/videoplayer-shared";var Oo=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)}},Vo=window.WeakMap?new WeakMap:new Oo,Bo=window.WeakMap?new WeakMap:new Map,uP=(i,e=20)=>{let t=0;return nP(i,"ratechange").subscribe(r=>{t++,t>=e&&(i.currentTime=i.currentTime,t=0)})},ae=(i,{audioVideoSyncRate:e})=>{let t=i.querySelector("video"),r=!!t;t?Vm(t):(t=document.createElement("video"),i.appendChild(t)),Vo.set(t,r);let a=new oP;return a.add(uP(t,e)),Bo.set(t,a),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},se=i=>{Bo.get(i)?.unsubscribe(),Bo.delete(i);let t=Vo.get(i);Vo.delete(i),t?Vm(i):Om(i)};import{assertNonNullable as ai,isNonNullable as Ye,isNullable as dP,fromEvent as br,merge as Bm,observableFrom as _m,filterChanged as Nm,map as si,Subject as Fm,Subscription as pP,ValueSubject as hP,ErrorCategory as mP}from"@vkontakte/videoplayer-shared";import{isNonNullable as _o,isNullable as lP,Subscription as cP}from"@vkontakte/videoplayer-shared";var Za=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),l=lP(a),u=new cP;return a&&u.add(a.subscribe(c=>{let d=i.getState();r(c,d)&&i.setState(c)},s)),r(o,n)||(t(n),l&&i.setState(n)),u.add(i.stateChangeStarted$.subscribe(c=>{t(c.to),l&&i.setState(c.to)},s)),u},Ge=(i,e,t)=>Za(e,()=>i.loop,r=>{_o(r)&&(i.loop=r)},{onError:t}),ne=(i,e,t,r)=>Za(e,()=>({muted:i.muted,volume:i.volume}),a=>{_o(a)&&(i.muted=a.muted,i.volume=a.volume)},{equal:(a,s)=>a===s||a?.muted===s?.muted&&a?.volume===s?.volume,changed$:t,onError:r}),Ee=(i,e,t,r)=>Za(e,()=>i.playbackRate,a=>{_o(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),mt=Za;var fP=i=>["__",i.language,i.label].join("|"),bP=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},No=class i{constructor(){this.available$=new Fm;this.current$=new hP(void 0);this.error$=new Fm;this.subscription=new pP;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let a=s=>{this.error$.next({id:"TextTracksManager",category:mP.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(mt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{Ye(s)&&this.setInternal(s)},{equal:(s,n)=>Ye(s)&&Ye(n)&&s.length===n.length&&s.every(({id:o},l)=>o===n[l].id),changed$:this.available$.pipe(si(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(mt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{Ye(s)&&this.setExternal(s)},{equal:(s,n)=>Ye(s)&&Ye(n)&&s.length===n.length&&s.every(({id:o},l)=>o===n[l].id),changed$:this.available$.pipe(si(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(mt(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:a})),this.subscription.add(mt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){ai(this.video);let{textTracks:e}=this.video;this.subscription.add(br(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(Bm(br(e,"addtrack"),br(e,"removetrack"),_m(["init"])).pipe(si(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Nm((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add(Bm(br(e,"change"),_m(["init"])).pipe(si(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),si(r=>r&&this.htmlTextTrackToITextTrack(r).id),Nm()).subscribe(this.current$));let t=r=>this.applyCueSettings(r.target?.activeCues??null);this.subscription.add(br(e,"addtrack").subscribe(r=>{r.track?.addEventListener("cuechange",t);let a=s=>{let n=s.target?.cues??null;n&&n.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",a))};r.track?.addEventListener("cuechange",a)})),this.subscription.add(br(e,"removetrack").subscribe(r=>{r.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let a=r;Ye(t.align)&&(a.align=t.align),Ye(t.position)&&(a.position=t.position),Ye(t.size)&&(a.size=t.size),Ye(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){ai(this.video);let t=[...this.video.textTracks];return e?t:t.filter(i.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:r}=e,a=e.id?e.id:fP(e),s=this.externalTracks.has(a),n=a.includes("auto");return s?{id:a,type:"external",isAuto:n,language:t,label:r,url:this.externalTracks.get(a)?.url}:{id:a,type:"internal",isAuto:n,language:t,label:r,url:this.internalTracks.get(a)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:a,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===a&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(a=>a.id===r)).forEach(([,r])=>this.detach(r))}select(e){ai(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(dP(e)||!bP(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){ai(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){ai(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},xe=No;var et=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 qm=i=>{let e=i;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Fo=i=>{let e=qm(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},Um=i=>{let e=qm(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};import{fromEvent as Pe,map as ft,merge as jm,filterChanged as gP,isNonNullable as Gm,Subject as vP,filter as Ym,mapTo as Wm,combine as yP,once as TP,ErrorCategory as IP,ValueSubject as Qm,clientChecker as EP}from"@vkontakte/videoplayer-shared";var SP=3,Hm=(i,e,t=SP)=>{let r=0,a=0;for(let s=0;s<i.length;s++){let n=i.start(s),o=i.end(s);if(n<=e&&e<=o){if(r=n,a=o,!t)return{from:r,to:a};for(let l=s-1;l>=0;l--)i.end(l)+t>=r&&(r=i.start(l));for(let l=s+1;l<i.length;l++)i.start(l)-t<=a&&(a=i.end(l))}}return{from:r,to:a}};var oe=i=>{let e=y=>Pe(i,y).pipe(Wm(void 0)),r=jm(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(y=>Pe(i,y))).pipe(ft(y=>y.type==="ended"?i.readyState<2:i.readyState<3),gP()),a=jm(Pe(i,"progress"),Pe(i,"timeupdate")).pipe(ft(()=>Hm(i.buffered,i.currentTime))),s=EP.isSafari?yP({play:e("play").pipe(TP()),playing:e("playing")}).pipe(Wm(void 0)):e("playing"),n=Pe(i,"volumechange").pipe(ft(()=>({muted:i.muted,volume:i.volume}))),o=Pe(i,"ratechange").pipe(ft(()=>i.playbackRate)),l=Pe(i,"error").pipe(Ym(()=>!!(i.error||i.played.length)),ft(()=>{let y=i.error;return{id:y?`MediaError#${y.code}`:"HtmlVideoError",category:IP.VIDEO_PIPELINE,message:y?y.message:"Error event from HTML video element",thrown:i.error??void 0}})),u=Pe(i,"timeupdate").pipe(ft(()=>i.currentTime)),c=new vP,d=.3,p;u.subscribe(y=>{i.loop&&Gm(p)&&Gm(y)&&p>=i.duration-d&&y<=d&&c.next(p),p=y});let h=e("pause").pipe(Ym(()=>!i.error&&p!==i.duration)),f=Pe(i,"enterpictureinpicture"),b=Pe(i,"leavepictureinpicture"),S=new Qm(Um(i));f.subscribe(()=>S.next(!0)),b.subscribe(()=>S.next(!1));let v=new Qm(Fo(i));return Pe(i,"fullscreenchange").pipe(ft(()=>Fo(i))).subscribe(v),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:l,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:u,durationChange$:Pe(i,"durationchange").pipe(ft(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:v}};import{VideoQuality as bt}from"@vkontakte/videoplayer-shared";var St=i=>{switch(i){case"mobile":return bt.Q_144P;case"lowest":return bt.Q_240P;case"low":return bt.Q_360P;case"sd":case"medium":return bt.Q_480P;case"hd":case"high":return bt.Q_720P;case"fullhd":case"full":return bt.Q_1080P;case"quadhd":case"quad":return bt.Q_1440P;case"ultrahd":case"ultra":return bt.Q_2160P}};var Go=He(ni(),1);import{isNonNullable as gt,isNullable as Uo,now as of,isHigher as Ho,isHigherOrEqual as sf,isInvariantQuality as nf,isLower as jo,isLowerOrEqual as MP,videoSizeToQuality as CP,assertNotEmptyArray as DP}from"@vkontakte/videoplayer-shared";var qo=!1,tt={},tf=i=>{qo=i},rf=()=>{tt={}},af=i=>{i(tt)},oi=(i,e)=>{qo&&(tt.meta=tt.meta??{},tt.meta[i]=e)},te=class{constructor(e){this.name=e}next(e){if(!qo)return;tt.series=tt.series??{};let t=tt.series[this.name]??[];t.push([Date.now(),e]),tt.series[this.name]=t}};var OP=new te("best_bitrate"),VP=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t,es=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=of()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},BP='Assertion "ABR Tracks is empty array" failed',_P=(i,{container:e,throughput:t,tuning:r,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:l,history:u,droppedVideoMaxQualityLimit:c,abrLogger:d})=>{DP(i,BP);let p=r.usePixelRatio?window.devicePixelRatio??1:1,h=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*p*r.containerSizeFactor,height:e.height*p*r.containerSizeFactor},f=h&&CP(h),b=r.considerPlaybackRate&>(o)?o:1,S=i.filter(P=>!nf(P.quality)).sort((P,V)=>Ho(P.quality,V.quality)?-1:1),v=(0,Go.default)(S,-1)?.quality,A=(0,Go.default)(S,0)?.quality,y=Uo(a)||gt(a.min)&>(a.max)&&jo(a.max,a.min)||gt(a.min)&&A&&Ho(a.min,A)||gt(a.max)&&v&&jo(a.max,v),g=b*VP(n??.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),T={},x=S.filter(P=>(f?jo(P.quality,f):!0)?(gt(t)&&isFinite(t)&>(P.bitrate)?t-s>=P.bitrate*g:!0)?r.lazyQualitySwitch&>(r.minBufferToSwitchUp)&&l&&!nf(l.quality)&&(n??0)<r.minBufferToSwitchUp&&Ho(P.quality,l.quality)?(T[P.quality]="Buffer",!1):!!c&&sf(P.quality,c)?(T[P.quality]="DroppedFramesLimit",!1):y||(Uo(a.max)||MP(P.quality,a.max))&&(Uo(a.min)||sf(P.quality,a.min))?!0:(T[P.quality]="FitsQualityLimits",!1):(T[P.quality]="FitsThroughput",!1):(T[P.quality]="FitsContainer",!1))[0];x&&x.bitrate&&OP.next(x.bitrate);let R=x??S[Math.ceil((S.length-1)/2)]??i[0];R.quality!==u?.last?.quality&&d({message:`
|
|
7
|
-
[
|
|
8
|
-
|
|
6
|
+
var Ug=Object.create;var Hu=Object.defineProperty;var Hg=Object.getOwnPropertyDescriptor;var jg=Object.getOwnPropertyNames;var Gg=Object.getPrototypeOf,Wg=Object.prototype.hasOwnProperty;var f=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var Yg=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of jg(e))!Wg.call(i,a)&&a!==t&&Hu(i,a,{get:()=>e[a],enumerable:!(r=Hg(e,a))||r.enumerable});return i};var _e=(i,e,t)=>(t=i!=null?Ug(Gg(i)):{},Yg(e||!i||!i.__esModule?Hu(t,"default",{value:i,enumerable:!0}):t,i));var fe=f((FR,Ju)=>{"use strict";Ju.exports=function(i){try{return!!i()}catch{return!0}}});var Rr=f((qR,Xu)=>{"use strict";var tS=fe();Xu.exports=!tS(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var ae=f((UR,tc)=>{"use strict";var Zu=Rr(),ec=Function.prototype,Ys=ec.call,rS=Zu&&ec.bind.bind(Ys,Ys);tc.exports=Zu?rS:function(i){return function(){return Ys.apply(i,arguments)}}});var Yt=f((HR,ic)=>{"use strict";var rc=ae(),iS=rc({}.toString),aS=rc("".slice);ic.exports=function(i){return aS(iS(i),8,-1)}});var sc=f((jR,ac)=>{"use strict";var sS=ae(),nS=fe(),oS=Yt(),Qs=Object,uS=sS("".split);ac.exports=nS(function(){return!Qs("z").propertyIsEnumerable(0)})?function(i){return oS(i)==="String"?uS(i,""):Qs(i)}:Qs});var Qt=f((GR,nc)=>{"use strict";nc.exports=function(i){return i==null}});var $r=f((WR,oc)=>{"use strict";var cS=Qt(),lS=TypeError;oc.exports=function(i){if(cS(i))throw new lS("Can't call method on "+i);return i}});var zt=f((YR,uc)=>{"use strict";var dS=sc(),pS=$r();uc.exports=function(i){return dS(pS(i))}});var zs=f((QR,cc)=>{"use strict";cc.exports=function(){}});var It=f((zR,lc)=>{"use strict";lc.exports={}});var H=f((Ks,dc)=>{"use strict";var Lr=function(i){return i&&i.Math===Math&&i};dc.exports=Lr(typeof globalThis=="object"&&globalThis)||Lr(typeof window=="object"&&window)||Lr(typeof self=="object"&&self)||Lr(typeof global=="object"&&global)||Lr(typeof Ks=="object"&&Ks)||function(){return this}()||Function("return this")()});var U=f((KR,pc)=>{"use strict";var Js=typeof document=="object"&&document.all;pc.exports=typeof Js>"u"&&Js!==void 0?function(i){return typeof i=="function"||i===Js}:function(i){return typeof i=="function"}});var mc=f((JR,fc)=>{"use strict";var hS=H(),fS=U(),hc=hS.WeakMap;fc.exports=fS(hc)&&/native code/.test(String(hc))});var ve=f((XR,bc)=>{"use strict";var mS=U();bc.exports=function(i){return typeof i=="object"?i!==null:mS(i)}});var ye=f((ZR,gc)=>{"use strict";var bS=fe();gc.exports=!bS(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var ha=f((e$,vc)=>{"use strict";var gS=H(),Sc=ve(),Xs=gS.document,SS=Sc(Xs)&&Sc(Xs.createElement);vc.exports=function(i){return SS?Xs.createElement(i):{}}});var Zs=f((t$,yc)=>{"use strict";var vS=ye(),yS=fe(),TS=ha();yc.exports=!vS&&!yS(function(){return Object.defineProperty(TS("div"),"a",{get:function(){return 7}}).a!==7})});var en=f((r$,Tc)=>{"use strict";var IS=ye(),ES=fe();Tc.exports=IS&&ES(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Ne=f((i$,Ic)=>{"use strict";var xS=ve(),PS=String,AS=TypeError;Ic.exports=function(i){if(xS(i))return i;throw new AS(PS(i)+" is not an object")}});var me=f((a$,Ec)=>{"use strict";var kS=Rr(),fa=Function.prototype.call;Ec.exports=kS?fa.bind(fa):function(){return fa.apply(fa,arguments)}});var ma=f((s$,xc)=>{"use strict";xc.exports={}});var He=f((n$,Ac)=>{"use strict";var tn=ma(),rn=H(),wS=U(),Pc=function(i){return wS(i)?i:void 0};Ac.exports=function(i,e){return arguments.length<2?Pc(tn[i])||Pc(rn[i]):tn[i]&&tn[i][e]||rn[i]&&rn[i][e]}});var Mr=f((o$,kc)=>{"use strict";var RS=ae();kc.exports=RS({}.isPrototypeOf)});var Kt=f((u$,$c)=>{"use strict";var $S=H(),wc=$S.navigator,Rc=wc&&wc.userAgent;$c.exports=Rc?String(Rc):""});var sn=f((c$,Vc)=>{"use strict";var Bc=H(),an=Kt(),Lc=Bc.process,Mc=Bc.Deno,Cc=Lc&&Lc.versions||Mc&&Mc.version,Dc=Cc&&Cc.v8,$e,ba;Dc&&($e=Dc.split("."),ba=$e[0]>0&&$e[0]<4?1:+($e[0]+$e[1]));!ba&&an&&($e=an.match(/Edge\/(\d+)/),(!$e||$e[1]>=74)&&($e=an.match(/Chrome\/(\d+)/),$e&&(ba=+$e[1])));Vc.exports=ba});var nn=f((l$,_c)=>{"use strict";var Oc=sn(),LS=fe(),MS=H(),CS=MS.String;_c.exports=!!Object.getOwnPropertySymbols&&!LS(function(){var i=Symbol("symbol detection");return!CS(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&Oc&&Oc<41})});var on=f((d$,Nc)=>{"use strict";var DS=nn();Nc.exports=DS&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var un=f((p$,Fc)=>{"use strict";var BS=He(),VS=U(),OS=Mr(),_S=on(),NS=Object;Fc.exports=_S?function(i){return typeof i=="symbol"}:function(i){var e=BS("Symbol");return VS(e)&&OS(e.prototype,NS(i))}});var Cr=f((h$,qc)=>{"use strict";var FS=String;qc.exports=function(i){try{return FS(i)}catch{return"Object"}}});var je=f((f$,Uc)=>{"use strict";var qS=U(),US=Cr(),HS=TypeError;Uc.exports=function(i){if(qS(i))return i;throw new HS(US(i)+" is not a function")}});var Dr=f((m$,Hc)=>{"use strict";var jS=je(),GS=Qt();Hc.exports=function(i,e){var t=i[e];return GS(t)?void 0:jS(t)}});var Gc=f((b$,jc)=>{"use strict";var cn=me(),ln=U(),dn=ve(),WS=TypeError;jc.exports=function(i,e){var t,r;if(e==="string"&&ln(t=i.toString)&&!dn(r=cn(t,i))||ln(t=i.valueOf)&&!dn(r=cn(t,i))||e!=="string"&&ln(t=i.toString)&&!dn(r=cn(t,i)))return r;throw new WS("Can't convert object to primitive value")}});var Le=f((g$,Wc)=>{"use strict";Wc.exports=!0});var zc=f((S$,Qc)=>{"use strict";var Yc=H(),YS=Object.defineProperty;Qc.exports=function(i,e){try{YS(Yc,i,{value:e,configurable:!0,writable:!0})}catch{Yc[i]=e}return e}});var Br=f((v$,Xc)=>{"use strict";var QS=Le(),zS=H(),KS=zc(),Kc="__core-js_shared__",Jc=Xc.exports=zS[Kc]||KS(Kc,{});(Jc.versions||(Jc.versions=[])).push({version:"3.38.0",mode:QS?"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 pn=f((y$,el)=>{"use strict";var Zc=Br();el.exports=function(i,e){return Zc[i]||(Zc[i]=e||{})}});var Vr=f((T$,tl)=>{"use strict";var JS=$r(),XS=Object;tl.exports=function(i){return XS(JS(i))}});var Me=f((I$,rl)=>{"use strict";var ZS=ae(),ev=Vr(),tv=ZS({}.hasOwnProperty);rl.exports=Object.hasOwn||function(e,t){return tv(ev(e),t)}});var hn=f((E$,il)=>{"use strict";var rv=ae(),iv=0,av=Math.random(),sv=rv(1 .toString);il.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+sv(++iv+av,36)}});var J=f((x$,sl)=>{"use strict";var nv=H(),ov=pn(),al=Me(),uv=hn(),cv=nn(),lv=on(),Jt=nv.Symbol,fn=ov("wks"),dv=lv?Jt.for||Jt:Jt&&Jt.withoutSetter||uv;sl.exports=function(i){return al(fn,i)||(fn[i]=cv&&al(Jt,i)?Jt[i]:dv("Symbol."+i)),fn[i]}});var cl=f((P$,ul)=>{"use strict";var pv=me(),nl=ve(),ol=un(),hv=Dr(),fv=Gc(),mv=J(),bv=TypeError,gv=mv("toPrimitive");ul.exports=function(i,e){if(!nl(i)||ol(i))return i;var t=hv(i,gv),r;if(t){if(e===void 0&&(e="default"),r=pv(t,i,e),!nl(r)||ol(r))return r;throw new bv("Can't convert object to primitive value")}return e===void 0&&(e="number"),fv(i,e)}});var mn=f((A$,ll)=>{"use strict";var Sv=cl(),vv=un();ll.exports=function(i){var e=Sv(i,"string");return vv(e)?e:e+""}});var Et=f(pl=>{"use strict";var yv=ye(),Tv=Zs(),Iv=en(),ga=Ne(),dl=mn(),Ev=TypeError,bn=Object.defineProperty,xv=Object.getOwnPropertyDescriptor,gn="enumerable",Sn="configurable",vn="writable";pl.f=yv?Iv?function(e,t,r){if(ga(e),t=dl(t),ga(r),typeof e=="function"&&t==="prototype"&&"value"in r&&vn in r&&!r[vn]){var a=xv(e,t);a&&a[vn]&&(e[t]=r.value,r={configurable:Sn in r?r[Sn]:a[Sn],enumerable:gn in r?r[gn]:a[gn],writable:!1})}return bn(e,t,r)}:bn:function(e,t,r){if(ga(e),t=dl(t),ga(r),Tv)try{return bn(e,t,r)}catch{}if("get"in r||"set"in r)throw new Ev("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Or=f((w$,hl)=>{"use strict";hl.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var Xt=f((R$,fl)=>{"use strict";var Pv=ye(),Av=Et(),kv=Or();fl.exports=Pv?function(i,e,t){return Av.f(i,e,kv(1,t))}:function(i,e,t){return i[e]=t,i}});var Sa=f(($$,bl)=>{"use strict";var wv=pn(),Rv=hn(),ml=wv("keys");bl.exports=function(i){return ml[i]||(ml[i]=Rv(i))}});var va=f((L$,gl)=>{"use strict";gl.exports={}});var En=f((M$,yl)=>{"use strict";var $v=mc(),vl=H(),Lv=ve(),Mv=Xt(),yn=Me(),Tn=Br(),Cv=Sa(),Dv=va(),Sl="Object already initialized",In=vl.TypeError,Bv=vl.WeakMap,ya,_r,Ta,Vv=function(i){return Ta(i)?_r(i):ya(i,{})},Ov=function(i){return function(e){var t;if(!Lv(e)||(t=_r(e)).type!==i)throw new In("Incompatible receiver, "+i+" required");return t}};$v||Tn.state?(Ce=Tn.state||(Tn.state=new Bv),Ce.get=Ce.get,Ce.has=Ce.has,Ce.set=Ce.set,ya=function(i,e){if(Ce.has(i))throw new In(Sl);return e.facade=i,Ce.set(i,e),e},_r=function(i){return Ce.get(i)||{}},Ta=function(i){return Ce.has(i)}):(xt=Cv("state"),Dv[xt]=!0,ya=function(i,e){if(yn(i,xt))throw new In(Sl);return e.facade=i,Mv(i,xt,e),e},_r=function(i){return yn(i,xt)?i[xt]:{}},Ta=function(i){return yn(i,xt)});var Ce,xt;yl.exports={set:ya,get:_r,has:Ta,enforce:Vv,getterFor:Ov}});var xn=f((C$,xl)=>{"use strict";var _v=Rr(),El=Function.prototype,Tl=El.apply,Il=El.call;xl.exports=typeof Reflect=="object"&&Reflect.apply||(_v?Il.bind(Tl):function(){return Il.apply(Tl,arguments)})});var Pn=f((D$,Pl)=>{"use strict";var Nv=Yt(),Fv=ae();Pl.exports=function(i){if(Nv(i)==="Function")return Fv(i)}});var Rl=f(wl=>{"use strict";var Al={}.propertyIsEnumerable,kl=Object.getOwnPropertyDescriptor,qv=kl&&!Al.call({1:2},1);wl.f=qv?function(e){var t=kl(this,e);return!!t&&t.enumerable}:Al});var Ml=f(Ll=>{"use strict";var Uv=ye(),Hv=me(),jv=Rl(),Gv=Or(),Wv=zt(),Yv=mn(),Qv=Me(),zv=Zs(),$l=Object.getOwnPropertyDescriptor;Ll.f=Uv?$l:function(e,t){if(e=Wv(e),t=Yv(t),zv)try{return $l(e,t)}catch{}if(Qv(e,t))return Gv(!Hv(jv.f,e,t),e[t])}});var An=f((O$,Cl)=>{"use strict";var Kv=fe(),Jv=U(),Xv=/#|\.prototype\./,Nr=function(i,e){var t=ey[Zv(i)];return t===ry?!0:t===ty?!1:Jv(e)?Kv(e):!!e},Zv=Nr.normalize=function(i){return String(i).replace(Xv,".").toLowerCase()},ey=Nr.data={},ty=Nr.NATIVE="N",ry=Nr.POLYFILL="P";Cl.exports=Nr});var Fr=f((_$,Bl)=>{"use strict";var Dl=Pn(),iy=je(),ay=Rr(),sy=Dl(Dl.bind);Bl.exports=function(i,e){return iy(i),e===void 0?i:ay?sy(i,e):function(){return i.apply(e,arguments)}}});var Te=f((N$,Ol)=>{"use strict";var qr=H(),ny=xn(),oy=Pn(),uy=U(),cy=Ml().f,ly=An(),Zt=ma(),dy=Fr(),er=Xt(),Vl=Me();Br();var py=function(i){var e=function(t,r,a){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,r)}return new i(t,r,a)}return ny(i,this,arguments)};return e.prototype=i.prototype,e};Ol.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?qr:a?qr[t]:qr[t]&&qr[t].prototype,o=r?Zt:Zt[t]||er(Zt,t,{})[t],c=o.prototype,u,d,l,p,h,m,b,g,v;for(p in e)u=ly(r?p:t+(a?".":"#")+p,i.forced),d=!u&&n&&Vl(n,p),m=o[p],d&&(i.dontCallGetSet?(v=cy(n,p),b=v&&v.value):b=n[p]),h=d&&b?b:e[p],!(!u&&!s&&typeof m==typeof h)&&(i.bind&&d?g=dy(h,qr):i.wrap&&d?g=py(h):s&&uy(h)?g=oy(h):g=h,(i.sham||h&&h.sham||m&&m.sham)&&er(g,"sham",!0),er(o,p,g),s&&(l=t+"Prototype",Vl(Zt,l)||er(Zt,l,{}),er(Zt[l],p,h),i.real&&c&&(u||!c[p])&&er(c,p,h)))}});var Fl=f((F$,Nl)=>{"use strict";var kn=ye(),hy=Me(),_l=Function.prototype,fy=kn&&Object.getOwnPropertyDescriptor,wn=hy(_l,"name"),my=wn&&function(){}.name==="something",by=wn&&(!kn||kn&&fy(_l,"name").configurable);Nl.exports={EXISTS:wn,PROPER:my,CONFIGURABLE:by}});var Ul=f((q$,ql)=>{"use strict";var gy=Math.ceil,Sy=Math.floor;ql.exports=Math.trunc||function(e){var t=+e;return(t>0?Sy:gy)(t)}});var Ia=f((U$,Hl)=>{"use strict";var vy=Ul();Hl.exports=function(i){var e=+i;return e!==e||e===0?0:vy(e)}});var Gl=f((H$,jl)=>{"use strict";var yy=Ia(),Ty=Math.max,Iy=Math.min;jl.exports=function(i,e){var t=yy(i);return t<0?Ty(t+e,0):Iy(t,e)}});var Yl=f((j$,Wl)=>{"use strict";var Ey=Ia(),xy=Math.min;Wl.exports=function(i){var e=Ey(i);return e>0?xy(e,9007199254740991):0}});var Ea=f((G$,Ql)=>{"use strict";var Py=Yl();Ql.exports=function(i){return Py(i.length)}});var Jl=f((W$,Kl)=>{"use strict";var Ay=zt(),ky=Gl(),wy=Ea(),zl=function(i){return function(e,t,r){var a=Ay(e),s=wy(a);if(s===0)return!i&&-1;var n=ky(r,s),o;if(i&&t!==t){for(;s>n;)if(o=a[n++],o!==o)return!0}else for(;s>n;n++)if((i||n in a)&&a[n]===t)return i||n||0;return!i&&-1}};Kl.exports={includes:zl(!0),indexOf:zl(!1)}});var ed=f((Y$,Zl)=>{"use strict";var Ry=ae(),Rn=Me(),$y=zt(),Ly=Jl().indexOf,My=va(),Xl=Ry([].push);Zl.exports=function(i,e){var t=$y(i),r=0,a=[],s;for(s in t)!Rn(My,s)&&Rn(t,s)&&Xl(a,s);for(;e.length>r;)Rn(t,s=e[r++])&&(~Ly(a,s)||Xl(a,s));return a}});var $n=f((Q$,td)=>{"use strict";td.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var id=f((z$,rd)=>{"use strict";var Cy=ed(),Dy=$n();rd.exports=Object.keys||function(e){return Cy(e,Dy)}});var sd=f(ad=>{"use strict";var By=ye(),Vy=en(),Oy=Et(),_y=Ne(),Ny=zt(),Fy=id();ad.f=By&&!Vy?Object.defineProperties:function(e,t){_y(e);for(var r=Ny(t),a=Fy(t),s=a.length,n=0,o;s>n;)Oy.f(e,o=a[n++],r[o]);return e}});var Ln=f((J$,nd)=>{"use strict";var qy=He();nd.exports=qy("document","documentElement")});var Bn=f((X$,hd)=>{"use strict";var Uy=Ne(),Hy=sd(),od=$n(),jy=va(),Gy=Ln(),Wy=ha(),Yy=Sa(),ud=">",cd="<",Cn="prototype",Dn="script",dd=Yy("IE_PROTO"),Mn=function(){},pd=function(i){return cd+Dn+ud+i+cd+"/"+Dn+ud},ld=function(i){i.write(pd("")),i.close();var e=i.parentWindow.Object;return i=null,e},Qy=function(){var i=Wy("iframe"),e="java"+Dn+":",t;return i.style.display="none",Gy.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(pd("document.F=Object")),t.close(),t.F},xa,Pa=function(){try{xa=new ActiveXObject("htmlfile")}catch{}Pa=typeof document<"u"?document.domain&&xa?ld(xa):Qy():ld(xa);for(var i=od.length;i--;)delete Pa[Cn][od[i]];return Pa()};jy[dd]=!0;hd.exports=Object.create||function(e,t){var r;return e!==null?(Mn[Cn]=Uy(e),r=new Mn,Mn[Cn]=null,r[dd]=e):r=Pa(),t===void 0?r:Hy.f(r,t)}});var md=f((Z$,fd)=>{"use strict";var zy=fe();fd.exports=!zy(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var On=f((eL,gd)=>{"use strict";var Ky=Me(),Jy=U(),Xy=Vr(),Zy=Sa(),eT=md(),bd=Zy("IE_PROTO"),Vn=Object,tT=Vn.prototype;gd.exports=eT?Vn.getPrototypeOf:function(i){var e=Xy(i);if(Ky(e,bd))return e[bd];var t=e.constructor;return Jy(t)&&e instanceof t?t.prototype:e instanceof Vn?tT:null}});var tr=f((tL,Sd)=>{"use strict";var rT=Xt();Sd.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:rT(i,e,t),i}});var qn=f((rL,Td)=>{"use strict";var iT=fe(),aT=U(),sT=ve(),nT=Bn(),vd=On(),oT=tr(),uT=J(),cT=Le(),Fn=uT("iterator"),yd=!1,Ge,_n,Nn;[].keys&&(Nn=[].keys(),"next"in Nn?(_n=vd(vd(Nn)),_n!==Object.prototype&&(Ge=_n)):yd=!0);var lT=!sT(Ge)||iT(function(){var i={};return Ge[Fn].call(i)!==i});lT?Ge={}:cT&&(Ge=nT(Ge));aT(Ge[Fn])||oT(Ge,Fn,function(){return this});Td.exports={IteratorPrototype:Ge,BUGGY_SAFARI_ITERATORS:yd}});var Aa=f((iL,Ed)=>{"use strict";var dT=J(),pT=dT("toStringTag"),Id={};Id[pT]="z";Ed.exports=String(Id)==="[object z]"});var Ur=f((aL,xd)=>{"use strict";var hT=Aa(),fT=U(),ka=Yt(),mT=J(),bT=mT("toStringTag"),gT=Object,ST=ka(function(){return arguments}())==="Arguments",vT=function(i,e){try{return i[e]}catch{}};xd.exports=hT?ka:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=vT(e=gT(i),bT))=="string"?t:ST?ka(e):(r=ka(e))==="Object"&&fT(e.callee)?"Arguments":r}});var Ad=f((sL,Pd)=>{"use strict";var yT=Aa(),TT=Ur();Pd.exports=yT?{}.toString:function(){return"[object "+TT(this)+"]"}});var Hr=f((nL,wd)=>{"use strict";var IT=Aa(),ET=Et().f,xT=Xt(),PT=Me(),AT=Ad(),kT=J(),kd=kT("toStringTag");wd.exports=function(i,e,t,r){var a=t?i:i&&i.prototype;a&&(PT(a,kd)||ET(a,kd,{configurable:!0,value:e}),r&&!IT&&xT(a,"toString",AT))}});var $d=f((oL,Rd)=>{"use strict";var wT=qn().IteratorPrototype,RT=Bn(),$T=Or(),LT=Hr(),MT=It(),CT=function(){return this};Rd.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=RT(wT,{next:$T(+!r,t)}),LT(i,a,!1,!0),MT[a]=CT,i}});var Md=f((uL,Ld)=>{"use strict";var DT=ae(),BT=je();Ld.exports=function(i,e,t){try{return DT(BT(Object.getOwnPropertyDescriptor(i,e)[t]))}catch{}}});var Dd=f((cL,Cd)=>{"use strict";var VT=ve();Cd.exports=function(i){return VT(i)||i===null}});var Vd=f((lL,Bd)=>{"use strict";var OT=Dd(),_T=String,NT=TypeError;Bd.exports=function(i){if(OT(i))return i;throw new NT("Can't set "+_T(i)+" as a prototype")}});var Un=f((dL,Od)=>{"use strict";var FT=Md(),qT=ve(),UT=$r(),HT=Vd();Od.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=FT(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch{}return function(a,s){return UT(a),HT(s),qT(a)&&(i?t(a,s):a.__proto__=s),a}}():void 0)});var Qd=f((pL,Yd)=>{"use strict";var jT=Te(),GT=me(),wa=Le(),Gd=Fl(),WT=U(),YT=$d(),_d=On(),Nd=Un(),QT=Hr(),zT=Xt(),Hn=tr(),KT=J(),Fd=It(),Wd=qn(),JT=Gd.PROPER,XT=Gd.CONFIGURABLE,qd=Wd.IteratorPrototype,Ra=Wd.BUGGY_SAFARI_ITERATORS,jr=KT("iterator"),Ud="keys",Gr="values",Hd="entries",jd=function(){return this};Yd.exports=function(i,e,t,r,a,s,n){YT(t,e,r);var o=function(v){if(v===a&&p)return p;if(!Ra&&v&&v in d)return d[v];switch(v){case Ud:return function(){return new t(this,v)};case Gr:return function(){return new t(this,v)};case Hd:return function(){return new t(this,v)}}return function(){return new t(this)}},c=e+" Iterator",u=!1,d=i.prototype,l=d[jr]||d["@@iterator"]||a&&d[a],p=!Ra&&l||o(a),h=e==="Array"&&d.entries||l,m,b,g;if(h&&(m=_d(h.call(new i)),m!==Object.prototype&&m.next&&(!wa&&_d(m)!==qd&&(Nd?Nd(m,qd):WT(m[jr])||Hn(m,jr,jd)),QT(m,c,!0,!0),wa&&(Fd[c]=jd))),JT&&a===Gr&&l&&l.name!==Gr&&(!wa&&XT?zT(d,"name",Gr):(u=!0,p=function(){return GT(l,this)})),a)if(b={values:o(Gr),keys:s?p:o(Ud),entries:o(Hd)},n)for(g in b)(Ra||u||!(g in d))&&Hn(d,g,b[g]);else jT({target:e,proto:!0,forced:Ra||u},b);return(!wa||n)&&d[jr]!==p&&Hn(d,jr,p,{name:a}),Fd[e]=p,b}});var Kd=f((hL,zd)=>{"use strict";zd.exports=function(i,e){return{value:i,done:e}}});var Gn=f((fL,tp)=>{"use strict";var ZT=zt(),jn=zs(),Jd=It(),Zd=En(),eI=Et().f,tI=Qd(),$a=Kd(),rI=Le(),iI=ye(),ep="Array Iterator",aI=Zd.set,sI=Zd.getterFor(ep);tp.exports=tI(Array,"Array",function(i,e){aI(this,{type:ep,target:ZT(i),index:0,kind:e})},function(){var i=sI(this),e=i.target,t=i.index++;if(!e||t>=e.length)return i.target=void 0,$a(void 0,!0);switch(i.kind){case"keys":return $a(t,!1);case"values":return $a(e[t],!1)}return $a([t,e[t]],!1)},"values");var Xd=Jd.Arguments=Jd.Array;jn("keys");jn("values");jn("entries");if(!rI&&iI&&Xd.name!=="values")try{eI(Xd,"name",{value:"values"})}catch{}});var ip=f((mL,rp)=>{"use strict";var nI=J(),oI=It(),uI=nI("iterator"),cI=Array.prototype;rp.exports=function(i){return i!==void 0&&(oI.Array===i||cI[uI]===i)}});var Wn=f((bL,sp)=>{"use strict";var lI=Ur(),ap=Dr(),dI=Qt(),pI=It(),hI=J(),fI=hI("iterator");sp.exports=function(i){if(!dI(i))return ap(i,fI)||ap(i,"@@iterator")||pI[lI(i)]}});var op=f((gL,np)=>{"use strict";var mI=me(),bI=je(),gI=Ne(),SI=Cr(),vI=Wn(),yI=TypeError;np.exports=function(i,e){var t=arguments.length<2?vI(i):e;if(bI(t))return gI(mI(t,i));throw new yI(SI(i)+" is not iterable")}});var lp=f((SL,cp)=>{"use strict";var TI=me(),up=Ne(),II=Dr();cp.exports=function(i,e,t){var r,a;up(i);try{if(r=II(i,"return"),!r){if(e==="throw")throw t;return t}r=TI(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return up(r),t}});var Ma=f((vL,fp)=>{"use strict";var EI=Fr(),xI=me(),PI=Ne(),AI=Cr(),kI=ip(),wI=Ea(),dp=Mr(),RI=op(),$I=Wn(),pp=lp(),LI=TypeError,La=function(i,e){this.stopped=i,this.result=e},hp=La.prototype;fp.exports=function(i,e,t){var r=t&&t.that,a=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),c=EI(e,r),u,d,l,p,h,m,b,g=function(A){return u&&pp(u,"normal",A),new La(!0,A)},v=function(A){return a?(PI(A),o?c(A[0],A[1],g):c(A[0],A[1])):o?c(A,g):c(A)};if(s)u=i.iterator;else if(n)u=i;else{if(d=$I(i),!d)throw new LI(AI(i)+" is not iterable");if(kI(d)){for(l=0,p=wI(i);p>l;l++)if(h=v(i[l]),h&&dp(hp,h))return h;return new La(!1)}u=RI(i,d)}for(m=s?i.next:u.next;!(b=xI(m,u)).done;){try{h=v(b.value)}catch(A){pp(u,"throw",A)}if(typeof h=="object"&&h&&dp(hp,h))return h}return new La(!1)}});var bp=f((yL,mp)=>{"use strict";var MI=ye(),CI=Et(),DI=Or();mp.exports=function(i,e,t){MI?CI.f(i,e,DI(0,t)):i[e]=t}});var gp=f(()=>{"use strict";var BI=Te(),VI=Ma(),OI=bp();BI({target:"Object",stat:!0},{fromEntries:function(e){var t={};return VI(e,function(r,a){OI(t,r,a)},{AS_ENTRIES:!0}),t}})});var vp=f((EL,Sp)=>{"use strict";Gn();gp();var _I=ma();Sp.exports=_I.Object.fromEntries});var Tp=f((xL,yp)=>{"use strict";yp.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 Ep=f(()=>{"use strict";Gn();var NI=Tp(),FI=H(),qI=Hr(),Ip=It();for(Ca in NI)qI(FI[Ca],Ca),Ip[Ca]=Ip.Array;var Ca});var Pp=f((kL,xp)=>{"use strict";var UI=vp();Ep();xp.exports=UI});var Yn=f((wL,Ap)=>{"use strict";var HI=Pp();Ap.exports=HI});var kp=f(()=>{"use strict"});var Qn=f((LL,wp)=>{"use strict";var Wr=H(),jI=Kt(),GI=Yt(),Da=function(i){return jI.slice(0,i.length)===i};wp.exports=function(){return Da("Bun/")?"BUN":Da("Cloudflare-Workers")?"CLOUDFLARE":Da("Deno/")?"DENO":Da("Node.js/")?"NODE":Wr.Bun&&typeof Bun.version=="string"?"BUN":Wr.Deno&&typeof Deno.version=="object"?"DENO":GI(Wr.process)==="process"?"NODE":Wr.window&&Wr.document?"BROWSER":"REST"}()});var Ba=f((ML,Rp)=>{"use strict";var WI=Qn();Rp.exports=WI==="NODE"});var Lp=f((CL,$p)=>{"use strict";var YI=Et();$p.exports=function(i,e,t){return YI.f(i,e,t)}});var Dp=f((DL,Cp)=>{"use strict";var QI=He(),zI=Lp(),KI=J(),JI=ye(),Mp=KI("species");Cp.exports=function(i){var e=QI(i);JI&&e&&!e[Mp]&&zI(e,Mp,{configurable:!0,get:function(){return this}})}});var Vp=f((BL,Bp)=>{"use strict";var XI=Mr(),ZI=TypeError;Bp.exports=function(i,e){if(XI(e,i))return i;throw new ZI("Incorrect invocation")}});var Kn=f((VL,Op)=>{"use strict";var eE=ae(),tE=U(),zn=Br(),rE=eE(Function.toString);tE(zn.inspectSource)||(zn.inspectSource=function(i){return rE(i)});Op.exports=zn.inspectSource});var Hp=f((OL,Up)=>{"use strict";var iE=ae(),aE=fe(),_p=U(),sE=Ur(),nE=He(),oE=Kn(),Np=function(){},Fp=nE("Reflect","construct"),Jn=/^\s*(?:class|function)\b/,uE=iE(Jn.exec),cE=!Jn.test(Np),Yr=function(e){if(!_p(e))return!1;try{return Fp(Np,[],e),!0}catch{return!1}},qp=function(e){if(!_p(e))return!1;switch(sE(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return cE||!!uE(Jn,oE(e))}catch{return!0}};qp.sham=!0;Up.exports=!Fp||aE(function(){var i;return Yr(Yr.call)||!Yr(Object)||!Yr(function(){i=!0})||i})?qp:Yr});var Gp=f((_L,jp)=>{"use strict";var lE=Hp(),dE=Cr(),pE=TypeError;jp.exports=function(i){if(lE(i))return i;throw new pE(dE(i)+" is not a constructor")}});var Xn=f((NL,Yp)=>{"use strict";var Wp=Ne(),hE=Gp(),fE=Qt(),mE=J(),bE=mE("species");Yp.exports=function(i,e){var t=Wp(i).constructor,r;return t===void 0||fE(r=Wp(t)[bE])?e:hE(r)}});var zp=f((FL,Qp)=>{"use strict";var gE=ae();Qp.exports=gE([].slice)});var Jp=f((qL,Kp)=>{"use strict";var SE=TypeError;Kp.exports=function(i,e){if(i<e)throw new SE("Not enough arguments");return i}});var Zn=f((UL,Xp)=>{"use strict";var vE=Kt();Xp.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(vE)});var uo=f((HL,oh)=>{"use strict";var be=H(),yE=xn(),TE=Fr(),Zp=U(),IE=Me(),nh=fe(),eh=Ln(),EE=zp(),th=ha(),xE=Jp(),PE=Zn(),AE=Ba(),so=be.setImmediate,no=be.clearImmediate,kE=be.process,eo=be.Dispatch,wE=be.Function,rh=be.MessageChannel,RE=be.String,to=0,Qr={},ih="onreadystatechange",zr,Pt,ro,io;nh(function(){zr=be.location});var oo=function(i){if(IE(Qr,i)){var e=Qr[i];delete Qr[i],e()}},ao=function(i){return function(){oo(i)}},ah=function(i){oo(i.data)},sh=function(i){be.postMessage(RE(i),zr.protocol+"//"+zr.host)};(!so||!no)&&(so=function(e){xE(arguments.length,1);var t=Zp(e)?e:wE(e),r=EE(arguments,1);return Qr[++to]=function(){yE(t,void 0,r)},Pt(to),to},no=function(e){delete Qr[e]},AE?Pt=function(i){kE.nextTick(ao(i))}:eo&&eo.now?Pt=function(i){eo.now(ao(i))}:rh&&!PE?(ro=new rh,io=ro.port2,ro.port1.onmessage=ah,Pt=TE(io.postMessage,io)):be.addEventListener&&Zp(be.postMessage)&&!be.importScripts&&zr&&zr.protocol!=="file:"&&!nh(sh)?(Pt=sh,be.addEventListener("message",ah,!1)):ih in th("script")?Pt=function(i){eh.appendChild(th("script"))[ih]=function(){eh.removeChild(this),oo(i)}}:Pt=function(i){setTimeout(ao(i),0)});oh.exports={set:so,clear:no}});var lh=f((jL,ch)=>{"use strict";var uh=H(),$E=ye(),LE=Object.getOwnPropertyDescriptor;ch.exports=function(i){if(!$E)return uh[i];var e=LE(uh,i);return e&&e.value}});var co=f((GL,ph)=>{"use strict";var dh=function(){this.head=null,this.tail=null};dh.prototype={add:function(i){var e={item:i,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var i=this.head;if(i){var e=this.head=i.next;return e===null&&(this.tail=null),i.item}}};ph.exports=dh});var fh=f((WL,hh)=>{"use strict";var ME=Kt();hh.exports=/ipad|iphone|ipod/i.test(ME)&&typeof Pebble<"u"});var bh=f((YL,mh)=>{"use strict";var CE=Kt();mh.exports=/web0s(?!.*chrome)/i.test(CE)});var Eh=f((QL,Ih)=>{"use strict";var ir=H(),DE=lh(),gh=Fr(),lo=uo().set,BE=co(),VE=Zn(),OE=fh(),_E=bh(),po=Ba(),Sh=ir.MutationObserver||ir.WebKitMutationObserver,vh=ir.document,yh=ir.process,Va=ir.Promise,mo=DE("queueMicrotask"),rr,ho,fo,Oa,Th;mo||(Kr=new BE,Jr=function(){var i,e;for(po&&(i=yh.domain)&&i.exit();e=Kr.get();)try{e()}catch(t){throw Kr.head&&rr(),t}i&&i.enter()},!VE&&!po&&!_E&&Sh&&vh?(ho=!0,fo=vh.createTextNode(""),new Sh(Jr).observe(fo,{characterData:!0}),rr=function(){fo.data=ho=!ho}):!OE&&Va&&Va.resolve?(Oa=Va.resolve(void 0),Oa.constructor=Va,Th=gh(Oa.then,Oa),rr=function(){Th(Jr)}):po?rr=function(){yh.nextTick(Jr)}:(lo=gh(lo,ir),rr=function(){lo(Jr)}),mo=function(i){Kr.head||rr(),Kr.add(i)});var Kr,Jr;Ih.exports=mo});var Ph=f((zL,xh)=>{"use strict";xh.exports=function(i,e){try{arguments.length===1?console.error(i):console.error(i,e)}catch{}}});var _a=f((KL,Ah)=>{"use strict";Ah.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var At=f((JL,kh)=>{"use strict";var NE=H();kh.exports=NE.Promise});var ar=f((XL,Lh)=>{"use strict";var FE=H(),Xr=At(),qE=U(),UE=An(),HE=Kn(),jE=J(),wh=Qn(),GE=Le(),bo=sn(),Rh=Xr&&Xr.prototype,WE=jE("species"),go=!1,$h=qE(FE.PromiseRejectionEvent),YE=UE("Promise",function(){var i=HE(Xr),e=i!==String(Xr);if(!e&&bo===66||GE&&!(Rh.catch&&Rh.finally))return!0;if(!bo||bo<51||!/native code/.test(i)){var t=new Xr(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[WE]=r,go=t.then(function(){})instanceof r,!go)return!0}return!e&&(wh==="BROWSER"||wh==="DENO")&&!$h});Lh.exports={CONSTRUCTOR:YE,REJECTION_EVENT:$h,SUBCLASSING:go}});var sr=f((ZL,Ch)=>{"use strict";var Mh=je(),QE=TypeError,zE=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw new QE("Bad Promise constructor");e=r,t=a}),this.resolve=Mh(e),this.reject=Mh(t)};Ch.exports.f=function(i){return new zE(i)}});var Xh=f(()=>{"use strict";var KE=Te(),JE=Le(),Ua=Ba(),st=H(),cr=me(),Dh=tr(),Bh=Un(),XE=Hr(),ZE=Dp(),ex=je(),qa=U(),tx=ve(),rx=Vp(),ix=Xn(),Fh=uo().set,Io=Eh(),ax=Ph(),sx=_a(),nx=co(),qh=En(),Ha=At(),Eo=ar(),Uh=sr(),ja="Promise",Hh=Eo.CONSTRUCTOR,ox=Eo.REJECTION_EVENT,ux=Eo.SUBCLASSING,So=qh.getterFor(ja),cx=qh.set,nr=Ha&&Ha.prototype,kt=Ha,Na=nr,jh=st.TypeError,vo=st.document,xo=st.process,yo=Uh.f,lx=yo,dx=!!(vo&&vo.createEvent&&st.dispatchEvent),Gh="unhandledrejection",px="rejectionhandled",Vh=0,Wh=1,hx=2,Po=1,Yh=2,Fa,Oh,fx,_h,Qh=function(i){var e;return tx(i)&&qa(e=i.then)?e:!1},zh=function(i,e){var t=e.value,r=e.state===Wh,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,c,u,d;try{a?(r||(e.rejection===Yh&&bx(e),e.rejection=Po),a===!0?c=t:(o&&o.enter(),c=a(t),o&&(o.exit(),d=!0)),c===i.promise?n(new jh("Promise-chain cycle")):(u=Qh(c))?cr(u,c,s,n):s(c)):n(t)}catch(l){o&&!d&&o.exit(),n(l)}},Kh=function(i,e){i.notified||(i.notified=!0,Io(function(){for(var t=i.reactions,r;r=t.get();)zh(r,i);i.notified=!1,e&&!i.rejection&&mx(i)}))},Jh=function(i,e,t){var r,a;dx?(r=vo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),st.dispatchEvent(r)):r={promise:e,reason:t},!ox&&(a=st["on"+i])?a(r):i===Gh&&ax("Unhandled promise rejection",t)},mx=function(i){cr(Fh,st,function(){var e=i.facade,t=i.value,r=Nh(i),a;if(r&&(a=sx(function(){Ua?xo.emit("unhandledRejection",t,e):Jh(Gh,e,t)}),i.rejection=Ua||Nh(i)?Yh:Po,a.error))throw a.value})},Nh=function(i){return i.rejection!==Po&&!i.parent},bx=function(i){cr(Fh,st,function(){var e=i.facade;Ua?xo.emit("rejectionHandled",e):Jh(px,e,i.value)})},or=function(i,e,t){return function(r){i(e,r,t)}},ur=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=hx,Kh(i,!0))},To=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw new jh("Promise can't be resolved itself");var r=Qh(e);r?Io(function(){var a={done:!1};try{cr(r,e,or(To,a,i),or(ur,a,i))}catch(s){ur(a,s,i)}}):(i.value=e,i.state=Wh,Kh(i,!1))}catch(a){ur({done:!1},a,i)}}};if(Hh&&(kt=function(e){rx(this,Na),ex(e),cr(Fa,this);var t=So(this);try{e(or(To,t),or(ur,t))}catch(r){ur(t,r)}},Na=kt.prototype,Fa=function(e){cx(this,{type:ja,done:!1,notified:!1,parent:!1,reactions:new nx,rejection:!1,state:Vh,value:void 0})},Fa.prototype=Dh(Na,"then",function(e,t){var r=So(this),a=yo(ix(this,kt));return r.parent=!0,a.ok=qa(e)?e:!0,a.fail=qa(t)&&t,a.domain=Ua?xo.domain:void 0,r.state===Vh?r.reactions.add(a):Io(function(){zh(a,r)}),a.promise}),Oh=function(){var i=new Fa,e=So(i);this.promise=i,this.resolve=or(To,e),this.reject=or(ur,e)},Uh.f=yo=function(i){return i===kt||i===fx?new Oh(i):lx(i)},!JE&&qa(Ha)&&nr!==Object.prototype)){_h=nr.then,ux||Dh(nr,"then",function(e,t){var r=this;return new kt(function(a,s){cr(_h,r,a,s)}).then(e,t)},{unsafe:!0});try{delete nr.constructor}catch{}Bh&&Bh(nr,Na)}KE({global:!0,constructor:!0,wrap:!0,forced:Hh},{Promise:kt});XE(kt,ja,!1,!0);ZE(ja)});var af=f((rM,rf)=>{"use strict";var gx=J(),ef=gx("iterator"),tf=!1;try{Zh=0,Ao={next:function(){return{done:!!Zh++}},return:function(){tf=!0}},Ao[ef]=function(){return this},Array.from(Ao,function(){throw 2})}catch{}var Zh,Ao;rf.exports=function(i,e){try{if(!e&&!tf)return!1}catch{return!1}var t=!1;try{var r={};r[ef]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch{}return t}});var ko=f((iM,sf)=>{"use strict";var Sx=At(),vx=af(),yx=ar().CONSTRUCTOR;sf.exports=yx||!vx(function(i){Sx.all(i).then(void 0,function(){})})});var nf=f(()=>{"use strict";var Tx=Te(),Ix=me(),Ex=je(),xx=sr(),Px=_a(),Ax=Ma(),kx=ko();Tx({target:"Promise",stat:!0,forced:kx},{all:function(e){var t=this,r=xx.f(t),a=r.resolve,s=r.reject,n=Px(function(){var o=Ex(t.resolve),c=[],u=0,d=1;Ax(e,function(l){var p=u++,h=!1;d++,Ix(o,t,l).then(function(m){h||(h=!0,c[p]=m,--d||a(c))},s)}),--d||a(c)});return n.error&&s(n.value),r.promise}})});var uf=f(()=>{"use strict";var wx=Te(),Rx=Le(),$x=ar().CONSTRUCTOR,Ro=At(),Lx=He(),Mx=U(),Cx=tr(),of=Ro&&Ro.prototype;wx({target:"Promise",proto:!0,forced:$x,real:!0},{catch:function(i){return this.then(void 0,i)}});!Rx&&Mx(Ro)&&(wo=Lx("Promise").prototype.catch,of.catch!==wo&&Cx(of,"catch",wo,{unsafe:!0}));var wo});var cf=f(()=>{"use strict";var Dx=Te(),Bx=me(),Vx=je(),Ox=sr(),_x=_a(),Nx=Ma(),Fx=ko();Dx({target:"Promise",stat:!0,forced:Fx},{race:function(e){var t=this,r=Ox.f(t),a=r.reject,s=_x(function(){var n=Vx(t.resolve);Nx(e,function(o){Bx(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var lf=f(()=>{"use strict";var qx=Te(),Ux=sr(),Hx=ar().CONSTRUCTOR;qx({target:"Promise",stat:!0,forced:Hx},{reject:function(e){var t=Ux.f(this),r=t.reject;return r(e),t.promise}})});var $o=f((pM,df)=>{"use strict";var jx=Ne(),Gx=ve(),Wx=sr();df.exports=function(i,e){if(jx(i),Gx(e)&&e.constructor===i)return e;var t=Wx.f(i),r=t.resolve;return r(e),t.promise}});var ff=f(()=>{"use strict";var Yx=Te(),Qx=He(),pf=Le(),zx=At(),hf=ar().CONSTRUCTOR,Kx=$o(),Jx=Qx("Promise"),Xx=pf&&!hf;Yx({target:"Promise",stat:!0,forced:pf||hf},{resolve:function(e){return Kx(Xx&&this===Jx?zx:this,e)}})});var mf=f(()=>{"use strict";Xh();nf();uf();cf();lf();ff()});var vf=f(()=>{"use strict";var Zx=Te(),eP=Le(),Ga=At(),tP=fe(),gf=He(),Sf=U(),rP=Xn(),bf=$o(),iP=tr(),Mo=Ga&&Ga.prototype,aP=!!Ga&&tP(function(){Mo.finally.call({then:function(){}},function(){})});Zx({target:"Promise",proto:!0,real:!0,forced:aP},{finally:function(i){var e=rP(this,gf("Promise")),t=Sf(i);return this.then(t?function(r){return bf(e,i()).then(function(){return r})}:i,t?function(r){return bf(e,i()).then(function(){throw r})}:i)}});!eP&&Sf(Ga)&&(Lo=gf("Promise").prototype.finally,Mo.finally!==Lo&&iP(Mo,"finally",Lo,{unsafe:!0}));var Lo});var Wa=f((vM,yf)=>{"use strict";var sP=He();yf.exports=sP});var If=f((yM,Tf)=>{"use strict";kp();mf();vf();var nP=Wa();Tf.exports=nP("Promise","finally")});var xf=f((TM,Ef)=>{"use strict";var oP=If();Ef.exports=oP});var Ya=f((IM,Pf)=>{"use strict";var uP=xf();Pf.exports=uP});var Kf=f(()=>{"use strict";var OP=Te(),_P=Vr(),NP=Ea(),FP=Ia(),qP=zs();OP({target:"Array",proto:!0},{at:function(e){var t=_P(this),r=NP(t),a=FP(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});qP("at")});var Xf=f((LC,Jf)=>{"use strict";Kf();var UP=Wa();Jf.exports=UP("Array","at")});var em=f((MC,Zf)=>{"use strict";var HP=Xf();Zf.exports=HP});var ri=f((CC,tm)=>{"use strict";var jP=em();tm.exports=jP});var Km=f(()=>{"use strict"});var Jm=f(()=>{"use strict"});var Zm=f((CV,Xm)=>{"use strict";var KA=ve(),JA=Yt(),XA=J(),ZA=XA("match");Xm.exports=function(i){var e;return KA(i)&&((e=i[ZA])!==void 0?!!e:JA(i)==="RegExp")}});var tb=f((DV,eb)=>{"use strict";var ek=Ur(),tk=String;eb.exports=function(i){if(ek(i)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return tk(i)}});var ib=f((BV,rb)=>{"use strict";var rk=Ne();rb.exports=function(){var i=rk(this),e="";return i.hasIndices&&(e+="d"),i.global&&(e+="g"),i.ignoreCase&&(e+="i"),i.multiline&&(e+="m"),i.dotAll&&(e+="s"),i.unicode&&(e+="u"),i.unicodeSets&&(e+="v"),i.sticky&&(e+="y"),e}});var nb=f((VV,sb)=>{"use strict";var ik=me(),ak=Me(),sk=Mr(),nk=ib(),ab=RegExp.prototype;sb.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in ab)&&!ak(i,"flags")&&sk(ab,i)?ik(nk,i):e}});var ub=f((OV,ob)=>{"use strict";var uu=ae(),ok=Vr(),uk=Math.floor,nu=uu("".charAt),ck=uu("".replace),ou=uu("".slice),lk=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,dk=/\$([$&'`]|\d{1,2})/g;ob.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,c=dk;return a!==void 0&&(a=ok(a),c=lk),ck(s,c,function(u,d){var l;switch(nu(d,0)){case"$":return"$";case"&":return i;case"`":return ou(e,0,t);case"'":return ou(e,n);case"<":l=a[ou(d,1,-1)];break;default:var p=+d;if(p===0)return u;if(p>o){var h=uk(p/10);return h===0?u:h<=o?r[h-1]===void 0?nu(d,1):r[h-1]+nu(d,1):u}l=r[p-1]}return l===void 0?"":l})}});var db=f(()=>{"use strict";var pk=Te(),hk=me(),lu=ae(),cb=$r(),fk=U(),mk=Qt(),bk=Zm(),vr=tb(),gk=Dr(),Sk=nb(),vk=ub(),yk=J(),Tk=Le(),Ik=yk("replace"),Ek=TypeError,cu=lu("".indexOf),xk=lu("".replace),lb=lu("".slice),Pk=Math.max;pk({target:"String",proto:!0},{replaceAll:function(e,t){var r=cb(this),a,s,n,o,c,u,d,l,p,h,m=0,b="";if(!mk(e)){if(a=bk(e),a&&(s=vr(cb(Sk(e))),!~cu(s,"g")))throw new Ek("`.replaceAll` does not allow non-global regexes");if(n=gk(e,Ik),n)return hk(n,e,r,t);if(Tk&&a)return xk(vr(r),e,t)}for(o=vr(r),c=vr(e),u=fk(t),u||(t=vr(t)),d=c.length,l=Pk(1,d),p=cu(o,c);p!==-1;)h=u?vr(t(c,p,o)):vk(c,o,p,[],void 0,t),b+=lb(o,m,p)+h,m=p+d,p=p+l>o.length?-1:cu(o,c,p+l);return m<o.length&&(b+=lb(o,m)),b}})});var hb=f((FV,pb)=>{"use strict";Km();Jm();db();var Ak=Wa();pb.exports=Ak("String","replaceAll")});var mb=f((qV,fb)=>{"use strict";var kk=hb();fb.exports=kk});var gb=f((UV,bb)=>{"use strict";var wk=mb();bb.exports=wk});var ju="2.0.108-dev.3ff897f5.0";var ie=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(ie||{}),at=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(at||{});var la=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(la||{}),Hs=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Hs||{});var js=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(js||{});import{assertNever as Ku,assertNonNullable as Qg,isNonNullable as da,ValueSubject as Gs,Subject as zg,Subscription as Kg,merge as Jg,observableFrom as Xg,fromEvent as Wu,map as Yu,tap as Qu,filterChanged as Zg,isNullable as Ws,ErrorCategory as zu}from"@vkontakte/videoplayer-shared";var Gu=i=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",i),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var pa=class{constructor(e){this.connection$=new Gs(void 0);this.castState$=new Gs("NOT_AVAILABLE");this.errorEvent$=new zg;this.realCastState$=new Gs("NOT_AVAILABLE");this.subscription=new Kg;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=da(window.chrome?.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},a||Gu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:zu.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){da(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Ws(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Ws(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(Wu(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{switch(a.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=r.getCurrentSession()?.getMediaSession()?.media?.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Ku(a.sessionState)}})).add(Jg(Wu(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Qu(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),Yu(a=>a.castState)),Xg([r.getCastState()])).pipe(Zg(),Yu(eS),Qu(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=da(this.connection$.getValue());if(s&&!n){let o=r.getCurrentSession();Qg(o);let c=o.getCastDevice(),u=o.getMediaSession()?.media?.contentId;(Ws(u)||u===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a==="CONNECTED"?da(this.connection$.getValue())?"CONNECTED":"AVAILABLE":a)}))}initializeCastApi(){let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:zu.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},eS=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return Ku(i)}};var mg=_e(Yn(),1);var Bf=_e(Ya(),1);import{assertNever as Af}from"@vkontakte/videoplayer-shared";var K=(i,e=0,t=0)=>{switch(t){case 0:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return i;let r=new URL(i);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(i);return!r.searchParams.get("offset_p")&&e===0?i:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:Af(t)}return i},Co=(i,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(i);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(i);return Number(t.searchParams.get("offset_p")??0)}default:Af(e)}};var I=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};import{isNonNullable as cP,Subject as Qa,merge as kf}from"@vkontakte/videoplayer-shared";var L=class{constructor(e){this.transitionStarted$=new Qa;this.transitionEnded$=new Qa;this.transitionUpdated$=new Qa;this.forceChanged$=new Qa;this.stateChangeStarted$=kf(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=kf(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,r=this.state;this.transition=void 0,this.prevState=r,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:r,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,r=this.state;r===e||cP(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as lP}from"@vkontakte/videoplayer-shared";var wf=i=>{switch(i){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return lP(i)}};import{assertNever as lr,assertNonNullable as wt,debounce as Rf,ErrorCategory as $f,fromEvent as Rt,isNonNullable as Lf,map as Mf,merge as Cf,observableFrom as dP,Subject as pP,Subscription as Do,timeout as hP,getHighestQuality as fP}from"@vkontakte/videoplayer-shared";var mP=5,bP=5,gP=500,Df=7e3,Zr=class{constructor(e){this.subscription=new Do;this.loadMediaTimeoutSubscription=new Do;this.videoState=new L("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(a?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:lr(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:lr(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:lr(e)}break}default:lr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(wf(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 Do;this.subscription.add(e),this.subscription.add(Cf(this.videoState.stateChangeStarted$.pipe(Mf(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(Mf(a=>`stateChangeEnded$ ${JSON.stringify(a)}`))).subscribe(a=>this.log({message:`[videoState] ${a}`})));let t=(a,s)=>this.subscription.add(a.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let a=new pP;e.add(a.pipe(Rf(gP)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Rt(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)>mP)&&a.next(o),s=o})),e.add(Rt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Rt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Rt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(Rt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{this.logRemoteEvent(a);let{remotePlayer:s}=this.params.connection,n=a.value,o=this.params.output.isBuffering$.getValue(),c=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==c&&this.params.output.isBuffering$.next(c),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<bP&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),I(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:lr(n)}}),t(Rt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(Rt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=Cf(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,dP(["init"])).pipe(Rf(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),I(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),I(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&I(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),r={volume:e.volume??t.volume,muted:e.muted??t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,r,a,s;switch(e){case"MPEG":{let u=t[e];wt(u);let d=fP(Object.keys(u));wt(d);let l=u[d];wt(l),r=l,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let u=t[e];wt(u),r=u.url,a="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let u=t[e];wt(u),r=u.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let u=t[e];wt(u),r=u.url,a="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=t[e];wt(u),r=K(u.url),a="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let u="Unsupported format for Chromecast",d=new Error(u);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:$f.VIDEO_PIPELINE,message:u,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return lr(e)}let n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??r,a);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:c}=this.params.meta;return Lf(o)&&(n.metadata.title=o),Lf(c)&&(n.metadata.subtitle=c),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((a,s)=>{this.loadMediaTimeoutSubscription.add(hP(Df).subscribe(()=>s(`timeout(${Df})`)))});(0,Bf.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},a=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${a}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:$f.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as Of}from"@vkontakte/videoplayer-shared";import{clearVideoElement as SP}from"@vkontakte/videoplayer-shared";var Vf=i=>{try{i.pause(),i.playbackRate=0,SP(i),i.remove()}catch(e){console.error(e)}};import{fromEvent as vP,Subscription as yP}from"@vkontakte/videoplayer-shared";var Bo=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)}},Vo=window.WeakMap?new WeakMap:new Bo,Oo=window.WeakMap?new WeakMap:new Map,TP=(i,e=20)=>{let t=0;return vP(i,"ratechange").subscribe(r=>{t++,t>=e&&(i.currentTime=i.currentTime,t=0)})},se=(i,{audioVideoSyncRate:e})=>{let t=i.querySelector("video"),r=!!t;t?Of(t):(t=document.createElement("video"),i.appendChild(t)),Vo.set(t,r);let a=new yP;return a.add(TP(t,e)),Oo.set(t,a),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},ne=i=>{Oo.get(i)?.unsubscribe(),Oo.delete(i);let t=Vo.get(i);Vo.delete(i),t?Of(i):Vf(i)};import{assertNonNullable as ei,isNonNullable as qe,isNullable as xP,fromEvent as dr,merge as _f,observableFrom as Nf,filterChanged as Ff,map as ti,Subject as qf,Subscription as PP,ValueSubject as AP,ErrorCategory as kP}from"@vkontakte/videoplayer-shared";import{isNonNullable as _o,isNullable as IP,Subscription as EP}from"@vkontakte/videoplayer-shared";var za=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),c=IP(a),u=new EP;return a&&u.add(a.subscribe(d=>{let l=i.getState();r(d,l)&&i.setState(d)},s)),r(o,n)||(t(n),c&&i.setState(n)),u.add(i.stateChangeStarted$.subscribe(d=>{t(d.to),c&&i.setState(d.to)},s)),u},Fe=(i,e,t)=>za(e,()=>i.loop,r=>{_o(r)&&(i.loop=r)},{onError:t}),oe=(i,e,t,r)=>za(e,()=>({muted:i.muted,volume:i.volume}),a=>{_o(a)&&(i.muted=a.muted,i.volume=a.volume)},{equal:(a,s)=>a===s||a?.muted===s?.muted&&a?.volume===s?.volume,changed$:t,onError:r}),Ie=(i,e,t,r)=>za(e,()=>i.playbackRate,a=>{_o(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),nt=za;var wP=i=>["__",i.language,i.label].join("|"),RP=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},No=class i{constructor(){this.available$=new qf;this.current$=new AP(void 0);this.error$=new qf;this.subscription=new PP;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let a=s=>{this.error$.next({id:"TextTracksManager",category:kP.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(nt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{qe(s)&&this.setInternal(s)},{equal:(s,n)=>qe(s)&&qe(n)&&s.length===n.length&&s.every(({id:o},c)=>o===n[c].id),changed$:this.available$.pipe(ti(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(nt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{qe(s)&&this.setExternal(s)},{equal:(s,n)=>qe(s)&&qe(n)&&s.length===n.length&&s.every(({id:o},c)=>o===n[c].id),changed$:this.available$.pipe(ti(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(nt(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:a})),this.subscription.add(nt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){ei(this.video);let{textTracks:e}=this.video;this.subscription.add(dr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(_f(dr(e,"addtrack"),dr(e,"removetrack"),Nf(["init"])).pipe(ti(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Ff((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add(_f(dr(e,"change"),Nf(["init"])).pipe(ti(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),ti(r=>r&&this.htmlTextTrackToITextTrack(r).id),Ff()).subscribe(this.current$));let t=r=>this.applyCueSettings(r.target?.activeCues??null);this.subscription.add(dr(e,"addtrack").subscribe(r=>{r.track?.addEventListener("cuechange",t);let a=s=>{let n=s.target?.cues??null;n&&n.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",a))};r.track?.addEventListener("cuechange",a)})),this.subscription.add(dr(e,"removetrack").subscribe(r=>{r.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let a=r;qe(t.align)&&(a.align=t.align),qe(t.position)&&(a.position=t.position),qe(t.size)&&(a.size=t.size),qe(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){ei(this.video);let t=[...this.video.textTracks];return e?t:t.filter(i.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:r}=e,a=e.id?e.id:wP(e),s=this.externalTracks.has(a),n=a.includes("auto");return s?{id:a,type:"external",isAuto:n,language:t,label:r,url:this.externalTracks.get(a)?.url}:{id:a,type:"internal",isAuto:n,language:t,label:r,url:this.internalTracks.get(a)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:a,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===a&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(a=>a.id===r)).forEach(([,r])=>this.detach(r))}select(e){ei(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(xP(e)||!RP(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){ei(this.video);let t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){ei(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Ee=No;var Ye=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 Uf=i=>{let e=i;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Fo=i=>{let e=Uf(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},Hf=i=>{let e=Uf(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};import{fromEvent as xe,map as ot,merge as Gf,filterChanged as LP,isNonNullable as Wf,Subject as MP,filter as Yf,mapTo as Qf,combine as CP,once as DP,ErrorCategory as BP,ValueSubject as zf,clientChecker as VP}from"@vkontakte/videoplayer-shared";var $P=3,jf=(i,e,t=$P)=>{let r=0,a=0;for(let s=0;s<i.length;s++){let n=i.start(s),o=i.end(s);if(n<=e&&e<=o){if(r=n,a=o,!t)return{from:r,to:a};for(let c=s-1;c>=0;c--)i.end(c)+t>=r&&(r=i.start(c));for(let c=s+1;c<i.length;c++)i.start(c)-t<=a&&(a=i.end(c))}}return{from:r,to:a}};var ue=i=>{let e=y=>xe(i,y).pipe(Qf(void 0)),r=Gf(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(y=>xe(i,y))).pipe(ot(y=>y.type==="ended"?i.readyState<2:i.readyState<3),LP()),a=Gf(xe(i,"progress"),xe(i,"timeupdate")).pipe(ot(()=>jf(i.buffered,i.currentTime))),s=VP.isSafari?CP({play:e("play").pipe(DP()),playing:e("playing")}).pipe(Qf(void 0)):e("playing"),n=xe(i,"volumechange").pipe(ot(()=>({muted:i.muted,volume:i.volume}))),o=xe(i,"ratechange").pipe(ot(()=>i.playbackRate)),c=xe(i,"error").pipe(Yf(()=>!!(i.error||i.played.length)),ot(()=>{let y=i.error;return{id:y?`MediaError#${y.code}`:"HtmlVideoError",category:BP.VIDEO_PIPELINE,message:y?y.message:"Error event from HTML video element",thrown:i.error??void 0}})),u=xe(i,"timeupdate").pipe(ot(()=>i.currentTime)),d=new MP,l=.3,p;u.subscribe(y=>{i.loop&&Wf(p)&&Wf(y)&&p>=i.duration-l&&y<=l&&d.next(p),p=y});let h=e("pause").pipe(Yf(()=>!i.error&&p!==i.duration)),m=xe(i,"enterpictureinpicture"),b=xe(i,"leavepictureinpicture"),g=new zf(Hf(i));m.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new zf(Fo(i));return xe(i,"fullscreenchange").pipe(ot(()=>Fo(i))).subscribe(v),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:d,error$:c,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:u,durationChange$:xe(i,"durationchange").pipe(ot(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v}};import{VideoQuality as ut}from"@vkontakte/videoplayer-shared";var ct=i=>{switch(i){case"mobile":return ut.Q_144P;case"lowest":return ut.Q_240P;case"low":return ut.Q_360P;case"sd":case"medium":return ut.Q_480P;case"hd":case"high":return ut.Q_720P;case"fullhd":case"full":return ut.Q_1080P;case"quadhd":case"quad":return ut.Q_1440P;case"ultrahd":case"ultra":return ut.Q_2160P}};var $t=_e(ri(),1);import{isNonNullable as ce,isNullable as Uo,now as cm,isHigher as Ho,isHigherOrEqual as sm,isInvariantQuality as nm,isLower as jo,isLowerOrEqual as om,videoSizeToQuality as GP,assertNotEmptyArray as lm,assertNonNullable as WP}from"@vkontakte/videoplayer-shared";var qo=!1,Qe={},rm=i=>{qo=i},im=()=>{Qe={}},am=i=>{i(Qe)},ii=(i,e)=>{qo&&(Qe.meta=Qe.meta??{},Qe.meta[i]=e)},X=class{constructor(e){this.name=e}next(e){if(!qo)return;Qe.series=Qe.series??{};let t=Qe.series[this.name]??[];t.push([Date.now(),e]),Qe.series[this.name]=t}};var YP=new X("best_bitrate"),dm=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;var Go=i=>(e,t)=>i*(Number(e.bitrate)-Number(t.bitrate)),ai=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=cm()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},pm='Assertion "ABR Tracks is empty array" failed',Ka=(i,e,t,r)=>{let a=[...e].sort(Go(1)),s=[...t].sort(Go(1)),n=s.filter(c=>ce(c.bitrate)&&ce(i.bitrate)?i.bitrate/c.bitrate>r:!0),o=(0,$t.default)(s,Math.round(s.length*a.indexOf(i)/(a.length+1)))??(0,$t.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,$t.default)(n,-1):(0,$t.default)(s,0)},um=i=>"quality"in i,hm=(i,e,t,r)=>{let a=t&&r&&r.history[t.id]&&cm()-r.history[t.id]<=i.trackCooldown&&(!r.last||t.id!==r.last.id);if(t?.id&&r&&!a&&r.recordSelection(t),a&&r?.last){let s=r.last;r?.recordSwitch(s);let n=um(s)?"video":"audio",o=um(s)?s.quality:s.bitrate;return e({message:`
|
|
7
|
+
[last ${n} selected] ${o}
|
|
8
|
+
`}),s}return r?.recordSwitch(t),t},lt=(i,{container:e,throughput:t,tuning:r,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:c,history:u,visible:d,droppedVideoMaxQualityLimit:l,abrLogger:p})=>{lm(i,pm);let h=r.usePixelRatio?window.devicePixelRatio??1:1,m=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*h*r.containerSizeFactor,height:e.height*h*r.containerSizeFactor},b=m&&GP(m),g=r.considerPlaybackRate&&ce(o)?o:1,v=i.filter(k=>!nm(k.quality)).sort((k,w)=>Ho(k.quality,w.quality)?-1:1),A=(0,$t.default)(v,-1)?.quality,y=(0,$t.default)(v,0)?.quality,S=Uo(a)||ce(a.min)&&ce(a.max)&&jo(a.max,a.min)||ce(a.min)&&y&&Ho(a.min,y)||ce(a.max)&&A&&jo(a.max,A),T=g*dm(n??.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),E={},O=v.filter(k=>{if(!(b?jo(k.quality,b):!0))return E[k.quality]="FitsContainer",!1;if(!(ce(t)&&isFinite(t)&&ce(k.bitrate)?t-s>=k.bitrate*T:!0))return E[k.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&ce(r.minBufferToSwitchUp)&&c&&!nm(c.quality)&&(n??0)<r.minBufferToSwitchUp&&Ho(k.quality,c.quality))return E[k.quality]="Buffer",!1;if(!!l&&sm(k.quality,l))return E[k.quality]="DroppedFramesLimit",!1;let te=S||(Uo(a.max)||om(k.quality,a.max))&&(Uo(a.min)||sm(k.quality,a.min)),x=ce(d)&&!d?om(k.quality,r.backgroundVideoQualityLimit):!0;return!te||!x?(E[k.quality]="FitsQualityLimits",!1):!0})[0];O&&O.bitrate&&YP.next(O.bitrate);let N=O??v[Math.ceil((v.length-1)/2)]??i[0];return N.quality!==u?.last?.quality&&p({message:`
|
|
9
|
+
[VIDEO TRACKS ABR]
|
|
10
|
+
[available video tracks]
|
|
11
|
+
${i.map(k=>`{ id: ${k.id}, quality: ${k.quality}, bitrate: ${k.bitrate} }`).join(`
|
|
9
12
|
`)}
|
|
10
13
|
|
|
11
14
|
[tuning]
|
|
12
|
-
${Object.entries(r??{}).map(([
|
|
15
|
+
${Object.entries(r??{}).map(([k,w])=>`${k}: ${w}`).join(`
|
|
13
16
|
`)}
|
|
14
17
|
|
|
15
18
|
[limit params]
|
|
16
|
-
containerQualityLimit: ${
|
|
19
|
+
containerQualityLimit: ${b},
|
|
17
20
|
throughput: ${t},
|
|
18
21
|
reserve: ${s},
|
|
19
22
|
playbackRate: ${o},
|
|
20
|
-
playbackRateFactor: ${
|
|
23
|
+
playbackRateFactor: ${g},
|
|
21
24
|
forwardBufferHealth: ${n},
|
|
22
|
-
bitrateFactor: ${
|
|
25
|
+
bitrateFactor: ${T},
|
|
23
26
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
24
|
-
droppedVideoMaxQualityLimit: ${
|
|
25
|
-
limitsAreInvalid: ${
|
|
27
|
+
droppedVideoMaxQualityLimit: ${l},
|
|
28
|
+
limitsAreInvalid: ${S},
|
|
26
29
|
maxQualityLimit: ${a?.max},
|
|
27
30
|
minQualityLimit: ${a?.min},
|
|
28
31
|
|
|
29
|
-
[limited tracks]
|
|
30
|
-
${Object.entries(
|
|
32
|
+
[limited video tracks]
|
|
33
|
+
${Object.entries(E).map(([k,w])=>`${k}: ${w}`).join(`
|
|
31
34
|
`)||"All tracks are available"}
|
|
32
35
|
|
|
33
|
-
[best track] ${
|
|
34
|
-
[selected track] ${
|
|
35
|
-
`});let
|
|
36
|
-
[
|
|
37
|
-
`}),P}return u?.recordSwitch(R),R},vt=_P;var W=i=>new URL(i).hostname;import{assertNever as hf,assertNonNullable as mf,combine as ak,debounce as sk,ErrorCategory as ff,filter as bf,filterChanged as nk,isNonNullable as Ko,map as ss,merge as Sf,observableFrom as ok,once as uk,Subscription as lk,ValueSubject as Jo,videoQualityToHeight as ck,videoSizeToQuality as dk}from"@vkontakte/videoplayer-shared";var uf=i=>{if(i instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(i.message))throw i;return!(i instanceof DOMException&&(i.code===20||i.name==="AbortError"))},ue=async i=>{let e=i.muted;try{await i.play()}catch(t){if(!uf(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{await i.play()}catch(r){return uf(r)&&(i.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as rs,isNullable as qP,assertNonNullable as ci}from"@vkontakte/videoplayer-shared";import{isNonNullable as lf,assertNonNullable as ts,now as NP}from"@vkontakte/videoplayer-shared";function Q(){return NP()}function Yo(i){return Q()-i}function Wo(i){let e=i.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,a=n=>r.test(n);return{resolve:(n,o,l=!1)=>{a(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let u=n.indexOf("?")>-1?"&":"?";return l&&(n+=u+"lowLat=1",u="&"),o&&(n+=u+"_rnd="+Math.floor(999999999*Math.random())),n}}}function cf(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function Sr(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,l=!1,u=0,c,d,p=!1,h="arraybuffer",f=7e3,b=2e3,S=()=>{if(l)return;ts(c);let B=Yo(c),G;if(B<b){G=b-B,setTimeout(S,G);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new a,M()},v=B=>(s=B,V),A=B=>(d=B,V),y=()=>(h="json",V),g=()=>{if(!l){if(--u>=0){S(),r&&r();return}l=!0,d&&d(),t&&t()}},T=B=>(p=B,V),M=()=>{c=Q(),n=new a,n.open("get",i);let B=0,G,Ae=0,de=()=>(ts(c),Math.max(c,Math.max(G||0,Ae||0)));if(s&&n.addEventListener("progress",k=>{let w=Q();s.updateChunk&&k.loaded>B&&(s.updateChunk(de(),k.loaded-B),B=k.loaded,G=w)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>g())),n.addEventListener("load",()=>{if(l)return;ts(n);let k=n.status;if(k>=200&&k<300){if(n.response.byteLength&&s){let w=n.response.byteLength-B;w&&s.updateChunk&&s.updateChunk(de(),w)}n.responseType==="json"&&!Object.values(n.response).length?g():(d&&d(),e(n.response))}else g()}),n.addEventListener("error",()=>{g()}),p){let k=()=>{ts(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Ae=Q(),n.removeEventListener("readystatechange",k))};n.addEventListener("readystatechange",k)}return n.responseType=h,n.send(),V},V={withBitrateReporting:v,withParallel:T,withJSONResponse:y,withRetryCount:B=>(u=B,V),withRetryInterval:(B,G)=>(lf(B)&&(b=B),lf(G)&&(f=G),V),withTimeout:B=>(o=B,V),withFinally:A,send:M,abort:()=>{n&&(n.abort(),n=void 0),l=!0,d&&d()}};return V}var ui=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,a=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,a+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let l=s.bytes*n/o;a+=l,s.start=t,s.bytes-=l}}}if(a>0&&r>0){let s=a*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(a)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var li=class{constructor(e,t,r,a,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=a,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=Q(),a=l=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=l,e._errorCB?e._errorCB(l):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=l=>{e._complete=1,e._responseData=l,e._downloadTime=Q()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(l,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Sr(t,s,()=>a("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Q()}_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=Q();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,a){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=a,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=a,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var is=1e4,Qo=3;var UP=6e4,HP=10,jP=1,GP=500,di=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.chunkRateEstimator=new ui(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Wo(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Wo(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,a;r!==0&&(a=t.buffered.start(r-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){let{videoElement:t}=this.params,r,a,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!a||s.bitrate>a.bitrate)&&(a=s):(!r||r.bitrate>s.bitrate)&&(r=s));return a||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||rs(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:a,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),a.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,a.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{cf(a,"progress",()=>{a.buffered.length?(a.currentTime=a.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new li(Qo,is,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:a}=this.params,s=!1,n=null,o=null,l=null,u=null,c=!1,d=()=>{let g=s&&(!c||c===this.rep);return g||t("Not running!"),g},p=(g,T,M)=>{l&&l.abort(),l=Sr(this.urlResolver.resolve(g,!1),T,M,()=>this._retryCallback()).withTimeout(is).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Qo).withFinally(()=>{l=null}).send()},h=(g,T,M)=>{ci(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(g,!1),T,M,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=g=>{let T=r.playbackRate;r.playbackRate!==g&&(t(`Playback rate switch: ${T}=>${g}`),r.playbackRate=g)},b=g=>{this.lowLatency=g,t(`lowLatency changed to ${g}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let g=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let M=Q()-1e4,x=0;for(let O=0;O<this.bufferStates.length;O++){let P=this.bufferStates[O];g=Math.min(g,P.buf),P.ts<M&&x++}this.bufferStates.splice(0,x),t(`update playback rate; minBuffer=${g} drop=${x} jitter=${this.sourceJitter}`);let R=g-jP;this.sourceJitter>=0?R-=this.sourceJitter/2:this.sourceJitter-=1,R>3?f(1.15):R>1?f(1.1):R>.3?f(1.05):f(1)}},v=g=>{let T,M=()=>T&&T.start?T.start.length:0,x=k=>T.start[k]/1e3,R=k=>T.dur[k]/1e3,O=k=>T.fragIndex+k,P=(k,w)=>({chunkIdx:O(k),startTS:x(k),dur:R(k),discontinuity:w}),V=()=>{let k=0;if(T&&T.dur){let w=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,H=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,z=w;this.sourceJitter>1&&(z+=this.sourceJitter-1);let pe=T.dur.length-1;for(;pe>=0&&(z-=T.dur[pe],!(z<=0));--pe);k=Math.min(pe,T.dur.length-1-H),k=Math.max(k,0)}return P(k,!0)},B=k=>{let w=M();if(!(w<=0)){if(rs(k)){for(let H=0;H<w;H++)if(x(H)>k)return P(H)}return V()}},G=k=>{let w=M(),H=k?k.chunkIdx+1:0,z=H-T.fragIndex;if(!(w<=0)){if(!k||z<0||z-w>HP)return t(`Resync: offset=${z} bChunks=${w} chunk=`+JSON.stringify(k)),V();if(!(z>=w))return P(H-T.fragIndex,!1)}},Ae=(k,w,H)=>{u&&u.abort(),u=Sr(this.urlResolver.resolve(k,!0,this.lowLatency),w,H,()=>this._retryCallback()).withTimeout(is).withRetryCount(Qo).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(k,w)=>{Ae(g,H=>{if(!d())return;T=H;let z=!!T.lowLatency;z!==this.lowLatency&&b(z);let pe=0;for(let Re=0;Re<T.dur.length;++Re)pe+=T.dur[Re];pe>0&&(ci(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(pe/T.dur.length)),a({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,k(B(w))},()=>this._handleNetworkError())},nextChunk:G}},A=()=>{s=!1,o&&o.abort(),l&&l.abort(),u&&u.abort(),ci(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:g=>{let{videoElement:T,logger:M}=this.params,x=v(e.jidxUrl),R,O,P,V,B=0,G,Ae,de,k=()=>{G&&(clearTimeout(G),G=void 0);let D=Math.max(GP,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),j=B+D,X=Q(),Y=Math.min(1e4,j-X);B=X;let ge=()=>{u||d()&&x.seek(()=>{d()&&(B=Q(),w(),k())})};Y>0?G=window.setTimeout(()=>{this.paused?k():ge()},Y):ge()},w=()=>{let D;for(;D=x.nextChunk(V);)V=D,Wt(D);let j=x.nextChunk(P);if(j){if(P&&j.discontinuity){M("Detected discontinuity; restarting playback"),this.paused?k():(A(),this._initPlayerWith(e));return}Re(j)}else k()},H=(D,j)=>{if(!d()||!this.sourceBuffer)return;let X,Y,ge,lt=Fe=>{window.setTimeout(()=>{d()&&H(D,j)},Fe)};if(this.sourceBuffer.updating)M("Source buffer is updating; delaying appendBuffer"),lt(100);else{let Fe=Q(),Le=T.currentTime;!this.paused&&T.buffered.length>1&&Ae===Le&&Fe-de>500&&(M("Stall suspected; trying to fix"),this._fixupStall()),Ae!==Le&&(Ae=Le,de=Fe);let Pt=this._getBufferSizeSec();if(Pt>30)M(`Buffered ${Pt} seconds; delaying appendBuffer`),lt(2e3);else try{this.sourceBuffer.appendBuffer(D),this.videoPlayStarted?(this.bufferStates.push({ts:Fe,buf:Pt}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),j&&j()}catch(Qe){if(Qe.name==="QuotaExceededError")M("QuotaExceededError; delaying appendBuffer"),ge=this.sourceBuffer.buffered.length,ge!==0&&(X=this.sourceBuffer.buffered.start(0),Y=Le,Y-X>4&&this.sourceBuffer.remove(X,Y-3)),lt(1e3);else throw Qe}}},z=()=>{O&&R&&(M([`Appending chunk, sz=${O.byteLength}:`,JSON.stringify(P)]),H(O,function(){O=null,w()}))},pe=D=>e.fragUrlTemplate.replace("%%id%%",D.chunkIdx),Re=D=>{d()&&h(pe(D),(j,X)=>{if(d()){if(X/=1e3,O=j,P=D,n=D.startTS,X){let Y=Math.min(10,D.dur/X);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Y:Y}z()}},()=>this._handleNetworkError())},Wt=D=>{d()&&(ci(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(pe(D),!1)))},xt=D=>{d()&&(e.cachedHeader=D,H(D,()=>{R=!0,z()}))};s=!0,x.seek(D=>{if(d()){if(B=Q(),!D){k();return}V=D,!qP(g)||D.startTS>g?Re(D):(P=D,w())}},g),e.cachedHeader?xt(e.cachedHeader):p(e.headerUrl,xt,()=>this._handleNetworkError())},stop:A,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),rs(a)&&(a+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,ci(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return rs(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let 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=Q();if(this.chunkRateEstimator.addInterval(p,f,h)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:S}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,l=!0,u=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(l&&d>o&&Yo(n)<3e4)return;r(d)}l=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&u(),h},notifySwitch:d=>{let p=Q();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Sr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(is).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;ue(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:a}=this.params,s=n=>{let o=[];return n?.length?(n.forEach((l,u)=>{l.video&&a.canPlayType(l.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(l.codecs)&&(l.index=u,o.push(l))}),o.sort(function(l,u){return l.video&&u.video?u.video.height-l.video.height:u.bitrate-l.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},UP))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as YP,filter as df,fromEvent as WP,interval as QP,isHigher as zP,isInvariantQuality as KP,isLower as JP,merge as XP,Subject as pf,Subscription as ZP}from"@vkontakte/videoplayer-shared";var zo=class{constructor(){this.onDroopedVideoFramesLimit$=new pf;this.subscription=new ZP;this.playing=!1;this.tracks=[];this.forceChecker$=new pf;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!KP(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,a=t-this.prevDroppedVideoFrames,s=1-(r-a)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&zP(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(WP(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=QP(this.droppedFramesChecker.checkTime).pipe(df(()=>this.playing),df(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(YP(this.droppedFramesChecker.checkTime)),r=XP(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){let t=Object.entries(this.limitCounts).filter(([,r])=>r>=this.droppedFramesChecker.countLimit).sort(([r],[a])=>JP(r,a)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},as=zo;import{map as ek,Observable as tk}from"@vkontakte/videoplayer-shared";import{fromEvent as rk}from"@vkontakte/videoplayer-shared";var pi=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var ik=(i,e)=>new tk(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(l=>t.next(l.isIntersecting||pi()))},{...r,...e});a.observe(i);let s=rk(document,"visibilitychange").pipe(ek(n=>!document.hidden||pi())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),ke=ik;var pk=["paused","playing","ready"],hk=["paused","playing","ready"],hi=class{constructor(e){this.subscription=new lk;this.videoState=new L("stopped");this.representations$=new Jo([]);this.textTracksManager=new xe;this.droppedFramesManager=new as;this.maxSeekBackTime$=new Jo(1/0);this.zeroTime$=new Jo(void 0);this.liveOffset=new et;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:ff.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,r=[];for(let a of t){let s=a.name??a.index.toString(10),n=St(a.name)??dk(a.video),o=a.bitrate/1e3,l={...a.video};if(!n)continue;let u={id:s,quality:n,bitrate:o,size:l};r.push({track:u,representation:a})}this.representations$.next(r),this.params.output.availableVideoTracks$.next(r.map(({track:a})=>a)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,r=this.representations$.getValue().find(({representation:a})=>a===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),Ko(r)&&this.params.output.currentVideoTrack$.next(r);break}case"bandwidth":{let{size:t,duration:r}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,r);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(hk.includes(e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&pk.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(K(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let l=a?.from;l&&l==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let 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.dash.reinit(K(this.params.source.url,l))}return;default:return hf(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:ff.WTF,message:"DashLiveProvider internal logic error",thrown:a})};Sf(this.videoState.stateChangeStarted$.pipe(ss(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ss(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=ae(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),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(W(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.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=oe(this.video);this.subscription.add(this.representations$.pipe(ss(a=>a.map(({track:s})=>s)),bf(a=>!!a.length),uk()).subscribe(a=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:a}))),this.subscription.add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(nk(),ss(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(ak({zeroTime:this.zeroTime$.pipe(bf(Ko)),position:r.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(Ge(this.video,this.params.desiredState.isLooped,t)).add(ne(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Ee(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(ke(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&ck(a);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:a})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return hf(a.to)}},t)).add(Sf(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,ok(["init"])).pipe(sk(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),se(this.video)}createLiveDashPlayer(){let e=new di({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),a=!r&&Ko(t)?t:vt(e.map(({track:u})=>u),{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=a?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),l&&this.setAutoQuality(r),n||l||s!==o){let u=e.find(({track:c})=>c.id===s)?.representation;mf(u,"Representations missing"),this.dash.startPlay(u,r)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:r})=>r.id===e.id)?.representation;mf(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),a=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(K(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var gf=hi;var rt=(i,e)=>{let t=0;for(let r=0;r<i.length;r++){let a=i.start(r)*1e3,s=i.end(r)*1e3;a<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as _w,assertNonNullable as Nw,debounce as Fw,ErrorCategory as ku,filter as Cb,filterChanged as wu,fromEvent as qw,isLowerOrEqual as Db,isNonNullable as Uw,isInvariantQuality as Hw,map as Ob,merge as ks,observableFrom as jw,observeElementSize as Gw,once as Vb,Subscription as Yw,ValueSubject as Ww}from"@vkontakte/videoplayer-shared";var ns=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let a=0,s=r.length;a<s;a++)if(r[a].callback===t){r.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let a=0,s=r.length;a<s;a++){let n=r[a];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},gr=class extends ns{constructor(){super(),this.listeners||ns.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)}},mi=class{constructor(){Object.defineProperty(this,"signal",{value:new gr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document>"u")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch{r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(mi.prototype[Symbol.toStringTag]="AbortController",gr.prototype[Symbol.toStringTag]="AbortSignal");function os(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function Xo(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!os({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||a)&&(s=function(u,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(u,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(l,u)=>{let c=s&&s.prototype.isPrototypeOf(l)?l.signal:u?u.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch{d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([p,n(l,u)])}return n(l,u)},Request:s}}var fi=os({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),vf=fi?Xo({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,it=fi?vf.fetch:window.fetch,QD=fi?vf.Request:window.Request,at=fi?mi:window.AbortController,zD=fi?gr:window.AbortSignal;var If=He(ni(),1);var st=()=>window.ManagedMediaSource||window.MediaSource,us=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),yf=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),Tf=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as ps,clientChecker as cs}from"@vkontakte/videoplayer-shared";var ds=document.createElement("video"),bk='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Sk='video/mp4; codecs="hev1.1.6.L93.B0"',Ef='video/webm; codecs="vp09.00.10.08"',xf='video/webm; codecs="av01.0.00M.08"',gk='audio/mp4; codecs="mp4a.40.2"',vk='audio/webm; codecs="opus"',Bt={mms:us(),mse:yf(),hls:!!(ds.canPlayType?.("application/x-mpegurl")||ds.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},le={mp4:!!ds.canPlayType?.("video/mp4"),webm:!!ds.canPlayType?.("video/webm"),cmaf:!0},ce={h264:!!st()?.isTypeSupported?.(bk),h265:!!st()?.isTypeSupported?.(Sk),vp9:!!st()?.isTypeSupported?.(Ef),av1:!!st()?.isTypeSupported?.(xf),aac:!!st()?.isTypeSupported?.(gk),opus:!!st()?.isTypeSupported?.(vk)},vr=(ce.h264||ce.h265)&&ce.aac,_t,yk=async()=>{if(!window.navigator.mediaCapabilities)return;let i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:xf}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:Ef}})]);_t={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{yk()}catch(i){console.error(i)}var yr=Bt.hls&&le.mp4,Pf=()=>Object.keys(ce).filter(i=>ce[i]),kf=(i,e=!1,t=!1)=>{let r=Bt.mse||Bt.mms&&t;return i.filter(a=>{switch(a){case"DASH_SEP":return r&&le.mp4&&vr;case"DASH_WEBM":return r&&le.webm&&ce.vp9&&ce.opus;case"DASH_WEBM_AV1":return r&&le.webm&&ce.av1&&ce.opus;case"DASH_STREAMS":return r&&(le.mp4&&vr||le.webm&&(ce.vp9||ce.av1)&&(ce.opus||ce.aac));case"DASH_LIVE":return Bt.mse&&le.mp4&&vr;case"DASH_LIVE_CMAF":return r&&le.mp4&&vr&&le.cmaf;case"DASH_ONDEMAND":return r&&le.mp4&&vr;case"HLS":case"HLS_ONDEMAND":return yr||e&&Bt.mse&&le.mp4&&vr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return yr;case"MPEG":return le.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Bt.webrtc&&Bt.ws&&ce.h264&&(le.mp4||le.webm);default:return ps(a)}})},ls=i=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(i){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return _t?_t[t].smooth?[t,e]:_t[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return _t?_t[t].powerEfficient?[t,e]:_t[e].powerEfficient?[e,t]:[t,e]:[e,t];default:ps(i)}return[e,t]},wf=({webmCodec:i,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...ls(i),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],a=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(cs.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...a,"MPEG",...ls(i),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...ls(i),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...ls(i),...a,"HLS","HLS_ONDEMAND"];default:ps(e)}return yr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Af=({androidPreferredFormat:i,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],a=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...a],n=[...a,...r],o,l=cs.isMac&&cs.isSafari;if(cs.isAndroid)switch(i){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:ps(i)}else yr&&!l?o=n:l?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"]},Zo=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Rf=i=>{if(i.size!==0){if(i.size===1)return i.values().next().value.split(".").at(0);for(let e of i){let t=(0,If.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return i.values().next().value.split(".").at(0)}};import{ErrorCategory as bi}from"@vkontakte/videoplayer-shared";var Lf=i=>{if(!i)return{id:"EmptyResponse",category:bi.PARSER,message:"Empty response"};if(i.length<=2&&i.match(/^\d+$/))return{id:`UVError#${i}`,category:bi.NETWORK,message:`UV Error ${i}`};let e=i.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:bi.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(i,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:bi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:bi.PARSER,message:"Response is valid XML, but parser failed"}};var Si=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};import{abortable as Eu,assertNonNullable as Gt,combine as ys,ErrorCategory as Tt,filter as Ts,filterChanged as kb,fromEvent as wr,interval as xu,isNonNullable as wb,map as Pu,merge as Ar,Subject as Ab,Subscription as Rb,tap as $w,throttle as Mw,clientChecker as Cw,ValueSubject as J}from"@vkontakte/videoplayer-shared";var kr=He(ni(),1);var Tk=(i,e={})=>{let r=e.timeout||1,a=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-a-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-a))}})},1)},Ik=i=>window.clearTimeout(i),$f=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",eu=$f?Tk:window.requestIdleCallback,l0=$f?Ik:window.cancelIdleCallback;var vb=He(Ja(),1);import{assertNever as Ek,ErrorCategory as Mf,clientChecker as tu,Subject as Cf}from"@vkontakte/videoplayer-shared";var xk=16,Df=!1;try{Df=tu.isSafari&&!!tu.macVersion&&tu.macVersion<=xk}catch(i){console.error(i)}var ru=class{constructor(e){this.bufferFull$=new Cf;this.error$=new Cf;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:Mf.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let a={operation:"append",data:e,signal:t,callback:r};this.queue.push(a),this.pull()})}async remove(e,t,r){return r&&r.aborted?!1:new Promise(a=>{let s={operation:"remove",from:e,to:t,signal:r,callback:a};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let r;Df&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:a}of this.queue)a(!1);r&&(this.queue=[r]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Mf.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:Ek(t)}}},Of=ru;var iu=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};import{abortable as Pr,assertNonNullable as We,ErrorCategory as Ut,fromEvent as Su,getExponentialDelay as gu,isNonNullable as gb,isNullable as _e,once as Tw,Subject as Iw,Subscription as Ew,ValueSubject as Fi}from"@vkontakte/videoplayer-shared";var _=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let a=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,a),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 a=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,a}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Tr=class extends _{};var gi=class extends _{};var vi=class extends _{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let a=this.readString(4);this.compatibleBrands.push(a),r-=4}}};var yi=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ti=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ii=class extends _{constructor(e,t){super(e,t),this.data=this.content}};var U=class extends _{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Nt=class extends U{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let a=this.readUint32(),s=a>>>31,n=a<<1>>>1,o=this.readUint32();a=this.readUint32();let l=a>>>28,u=a<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:l,SAPDeltaTime:u})}}};var Ei=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var xi=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Pi=class extends U{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 ki=class extends U{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var wi=class extends U{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Ai=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ri=class extends U{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 Li=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var $i=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Mi=class extends U{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Ci=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Di=class extends U{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 Oi=class extends U{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Vi=class extends U{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let a=0;a<this.sampleCount;a++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var kk={ftyp:vi,moov:yi,moof:Ti,mdat:Ii,sidx:Nt,trak:Ei,mdia:Ai,mfhd:Mi,tkhd:Ri,traf:Ci,tfhd:Di,tfdt:Oi,trun:Vi,minf:Li,sv3d:xi,st3d:Pi,prhd:ki,proj:$i,equi:wi,uuid:gi,unknown:Tr},Ft=class i{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch{break}return t}createBox(e,t){let r=kk[e];return r?new r(t,new i):new Tr(t,new i)}};var Ir=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var Ak=new TextDecoder("ascii"),Rk=i=>Ak.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",Lk=i=>{let e=new Nt(i,new Ft),t=e.earliestPresentationTime/e.timescale*1e3,r=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},$k=(i,e)=>{let r=new Ft().parse(i),a=new Ir(r),s=a.findAll("moof"),n=e?a.findAll("uuid"):a.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],l=n[n.length-1],u=o.source.byteOffset,d=l.source.byteOffset-o.source.byteOffset+l.size;return new DataView(i.buffer,u,d)},Mk=(i,e)=>{let r=new Ft().parse(i),s=new Ir(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),l=s[s.length-1].children.find(d=>d.type==="trun"),u=0;return l.sampleDuration.length?u=l.sampleDuration.reduce((d,p)=>d+p,0):u=n.defaultSampleDuration*l.sampleCount,(Number(o.baseMediaDecodeTime)+u)/e*1e3},Ck=i=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new Ft().parse(i),a=new Ir(r);if(a.find("sv3d")){e.is3dVideo=!0;let n=a.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=a.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let l=a.find("equi");l&&(e.projectionData.bounds.top=l.projectionBoundsTop,e.projectionData.bounds.right=l.projectionBoundsRight,e.projectionData.bounds.bottom=l.projectionBoundsBottom,e.projectionData.bounds.left=l.projectionBoundsLeft)}return e},Vf={validateData:Rk,parseInit:Ck,getIndexRange:()=>{},parseSegments:Lk,parseFeedableSegmentChunk:$k,getSegmentEndTime:Mk};import{assertNonNullable as su,isNonNullable as Ff,isNullable as Ok}from"@vkontakte/videoplayer-shared";import{assertNever as Dk}from"@vkontakte/videoplayer-shared";var Bf={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"}},_f=i=>{let e=i.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=Bi(i,t),a=r in Bf,s=a?Bf[r].type:"binary",n=i.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let l=new DataView(i.buffer,i.byteOffset+t+1,o-1),u=n&255>>o,c=Bi(l),d=u*2**((o-1)*8)+c,p=t+o,h;return p+d>i.byteLength?h=new DataView(i.buffer,i.byteOffset+p):h=new DataView(i.buffer,i.byteOffset+p,d),{tag:a?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},Bi=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*2**16+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*2**32+i.getUint32(1);case 6:return i.getUint16(0)*2**32+i.getUint32(2);case 7:{let t=i.getUint8(0)*281474976710656+i.getUint16(1)*4294967296+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Be=(i,e)=>{switch(e){case"int":return i.getInt8(0);case"uint":return Bi(i);case"float":return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case"string":return new TextDecoder("ascii").decode(i);case"utf8":return new TextDecoder("utf-8").decode(i);case"date":return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case"master":return i;case"binary":return i;default:Dk(e)}},qt=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=_f(r);if(!e(a))return;a.type==="master"&&qt(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},Nf=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=_f(i);return qt(a.value,({tag:s,type:n,value:o})=>(s===17143?e=Be(o,n):s===17026?t=Be(o,n):s===17029&&(r=Be(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var qf=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Vk=[231,22612,22743,167,171,163,160,175],Bk=i=>{let e,t,r,a,s=!1,n=!1,o=!1,l,u,c=!1,d=0;return qt(i,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let S=Be(f,h);u=Bi(S)}else p!==21420&&(u=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=Be(f,h):p===17545?a=Be(f,h):p===21420&&u===475249515?l=Be(f,h):p===374648427?qt(f,({tag:S,type:v,value:A})=>S===30321?(c=Be(A,v)===1,!1):!0):s&&n&&qf.includes(p)&&(o=!0),!o}),su(e,"Failed to parse webm Segment start"),su(t,"Failed to parse webm Segment end"),su(a,"Failed to parse webm Segment duration"),r=r??1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(a/1e9*r*1e3),cuesSeekPosition:l,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},_k=i=>{if(Ok(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Nk=(i,e)=>{let t=!1,r=!1,a=o=>Ff(o.time)&&Ff(o.position),s=[],n;return qt(i,({tag:o,type:l,value:u})=>{switch(o){case 475249515:t=!0;break;case 187:n&&a(n)&&s.push(n),n={};break;case 179:n&&(n.time=Be(u,l));break;case 183:break;case 241:n&&(n.position=Be(u,l));break;default:t&&qf.includes(o)&&(r=!0)}return!(t&&r)}),n&&a(n)&&s.push(n),s.map((o,l)=>{let{time:u,position:c}=o,d=s[l+1];return{status:"none",time:{from:u,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},Fk=i=>{let e=0,t=!1;try{qt(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):Vk.includes(r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||=[163,160,175].includes(r.tag)),!0):!1)}catch{}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},Uf={validateData:Nf,parseInit:Bk,getIndexRange:_k,parseSegments:Nk,parseFeedableSegmentChunk:Fk};var Er=i=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(i);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return Uf;case"mp4":return Vf}}throw new ReferenceError(`Unsupported mime type ${i}`)};var pu=He(cb(),1);var du=i=>{let e=i.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[a,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[a,s,n]=r;return!!(a&&parseInt(a,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let a=r[0];if(!a||a.length!==6)return!1;let[s,n]=a.toUpperCase(),o=s+n;return["6E","7A","F4"].includes(o)}}return!1};import{isNonNullable as pb,isNullable as hb}from"@vkontakte/videoplayer-shared";var db=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var mb=i=>{if(!i.startsWith("P"))return;let e=(n,o)=>{let l=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(l)?0:l)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),a=r?.[1]==="-"?-1:1,s={days:e(r?.[5],a),hours:e(r?.[6],a),minutes:e(r?.[7],a),seconds:e(r?.[8],a)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},nt=(i,e)=>{let t=i;t=(0,pu.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[a,s]of Object.entries(r)){let n=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=(0,pu.default)(t,n,(o,l)=>hb(s)?o:hb(l)?s:s.padStart(parseInt(l,10),"0"))}return t},fb=(i,e)=>{let r=new DOMParser().parseFromString(i,"application/xml"),a={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=s.querySelector("BaseURL")?.textContent?.trim()??"",l=n.children,u=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),d=c?new Date(c).getTime():void 0,p,h=s.getAttribute("mediaPresentationDuration"),f=n.getAttribute("duration"),S=s.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=mb(h);else if(f){let g=mb(f);pb(g)&&(p=g)}else S&&(p=parseInt(S,10));let v=0,A=s.getAttribute("profiles")?.split(",")??[];for(let g of l){let T=g.getAttribute("id")??"id"+(v++).toString(10),M=g.getAttribute("mimeType")??"",x=g.getAttribute("codecs")??"",R=g.getAttribute("contentType")??M?.split("/")[0],O=g.getAttribute("profiles")?.split(",")??[],P=g.getAttribute("lang")??void 0,V=g.querySelector("Label")?.textContent?.trim()??void 0,B=g.querySelectorAll("Representation"),G=g.querySelector("SegmentTemplate"),Ae=g.querySelector("Role")?.getAttribute("value")??void 0,de=R,k={id:T,language:P,isDefault:Ae==="main",label:V,codecs:x,hdr:de==="video"&&du(x),mime:M,representations:[]};for(let w of B){let H=w.getAttribute("lang")??void 0,z=w.getAttribute("label")??void 0,pe=w.querySelector("BaseURL")?.textContent?.trim()??"",Re=new URL(pe||o,e).toString(),Wt=w.getAttribute("mimeType")??M,xt=w.getAttribute("codecs")??x??"",D;if(R==="text"){let j=w.getAttribute("id")||"",X=j.includes("_auto"),Y=w.querySelector("SegmentTemplate");if(Y){let ge={representationId:w.getAttribute("id")??void 0,bandwidth:w.getAttribute("bandwidth")??void 0},lt=parseInt(w.getAttribute("bandwidth")??"",10)/1e3,Fe=parseInt(Y.getAttribute("startNumber")??"",10)??1,Le=parseInt(Y.getAttribute("timescale")??"",10),Pt=Y.querySelectorAll("SegmentTimeline S")??[],Qe=Y.getAttribute("media");if(!Qe)throw new ReferenceError("No media attribute in SegmentTemplate");let ua=[],la=0,ca="",Qt=0,Lr=Fe,Z=0;for(let $e of Pt){let kt=parseInt($e.getAttribute("d")??"",10),ve=parseInt($e.getAttribute("r")??"",10)||0,ct=parseInt($e.getAttribute("t")??"",10);Z=Number.isFinite(ct)?ct:Z;let wt=kt/Le*1e3,zt=Z/Le*1e3;for(let qe=0;qe<ve+1;qe++){let dt=nt(Qe,{...ge,segmentNumber:Lr.toString(10),segmentTime:(Z+qe*kt).toString(10)}),Kt=(zt??0)+qe*wt,Mr=Kt+wt;Lr++,ua.push({time:{from:Kt,to:Mr},url:dt})}Z+=(ve+1)*kt,la+=(ve+1)*wt}Qt=Z/Le*1e3,ca=nt(Qe,{...ge,segmentNumber:Lr.toString(10),segmentTime:Z.toString(10)});let $r={time:{from:Qt,to:1/0},url:ca},ze={type:"template",baseUrl:Re,segmentTemplateUrl:Qe,initUrl:"",totalSegmentsDurationMs:la,segments:ua,nextSegmentBeyondManifest:$r,timescale:Le};D={id:j,kind:"text",segmentReference:ze,profiles:[],duration:p,bitrate:lt,mime:"",codecs:"",width:0,height:0,isAuto:X}}else D={id:w.getAttribute("id")||"",isAuto:X,kind:"text",url:Re}}else{let j=w.getAttribute("contentType")??Wt?.split("/")[0]??R,X=g.getAttribute("profiles")?.split(",")??[],Y=parseInt(w.getAttribute("width")??"",10),ge=parseInt(w.getAttribute("height")??"",10),lt=parseInt(w.getAttribute("bandwidth")??"",10)/1e3,Fe=w.getAttribute("frameRate")??"",Le=w.getAttribute("quality")??void 0,Pt=Fe?db(Fe):void 0,Qe=w.getAttribute("id")??"id"+(v++).toString(10),ua=j==="video"?`${ge}p`:j==="audio"?`${lt}Kbps`:xt,la=`${Qe}@${ua}`,ca=[...A,...O,...X],Qt,Lr=w.querySelector("SegmentBase"),Z=w.querySelector("SegmentTemplate")??G;if(Lr){let ze=w.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[$e,kt]=ze.split("-").map(dt=>parseInt(dt,10)),ve={from:$e,to:kt},ct=w.querySelector("SegmentBase")?.getAttribute("indexRange"),[wt,zt]=ct?ct.split("-").map(dt=>parseInt(dt,10)):[],qe=ct?{from:wt,to:zt}:void 0;Qt={type:"byteRange",url:Re,initRange:ve,indexRange:qe}}else if(Z){let ze={representationId:w.getAttribute("id")??void 0,bandwidth:w.getAttribute("bandwidth")??void 0},$e=parseInt(Z.getAttribute("timescale")??"",10),kt=Z.getAttribute("initialization")??"",ve=Z.getAttribute("media"),ct=parseInt(Z.getAttribute("startNumber")??"",10)??1,wt=nt(kt,ze);if(!ve)throw new ReferenceError("No media attribute in SegmentTemplate");let zt=Z.querySelectorAll("SegmentTimeline S")??[],qe=[],dt=0,Kt="",Mr=0;if(zt.length){let da=ct,Me=0;for(let Jt of zt){let Ue=parseInt(Jt.getAttribute("d")??"",10),At=parseInt(Jt.getAttribute("r")??"",10)||0,pa=parseInt(Jt.getAttribute("t")??"",10);Me=Number.isFinite(pa)?pa:Me;let Us=Ue/$e*1e3,kS=Me/$e*1e3;for(let ha=0;ha<At+1;ha++){let wS=nt(ve,{...ze,segmentNumber:da.toString(10),segmentTime:(Me+ha*Ue).toString(10)}),Uu=(kS??0)+ha*Us,AS=Uu+Us;da++,qe.push({time:{from:Uu,to:AS},url:wS})}Me+=(At+1)*Ue,dt+=(At+1)*Us}Mr=Me/$e*1e3,Kt=nt(ve,{...ze,segmentNumber:da.toString(10),segmentTime:Me.toString(10)})}else if(pb(p)){let Me=parseInt(Z.getAttribute("duration")??"",10)/$e*1e3,Jt=Math.ceil(p/Me),Ue=0;for(let At=1;At<Jt;At++){let pa=nt(ve,{...ze,segmentNumber:At.toString(10),segmentTime:Ue.toString(10)});qe.push({time:{from:Ue,to:Ue+Me},url:pa}),Ue+=Me}Mr=Ue,Kt=nt(ve,{...ze,segmentNumber:Jt.toString(10),segmentTime:Ue.toString(10)})}let PS={time:{from:Mr,to:1/0},url:Kt};Qt={type:"template",baseUrl:Re,segmentTemplateUrl:ve,initUrl:wt,totalSegmentsDurationMs:dt,segments:qe,nextSegmentBeyondManifest:PS,timescale:$e}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!j||!Wt)continue;let $r={video:"video",audio:"audio",text:"text"}[j];if(!$r)continue;de||=$r,D={id:la,kind:$r,segmentReference:Qt,profiles:ca,duration:p,bitrate:lt,mime:Wt,codecs:xt,width:Y,height:ge,fps:Pt,quality:Le}}k.language||=H,k.label||=z,k.mime||=Wt,k.codecs||=xt,k.hdr||=de==="video"&&du(xt),k.representations.push(D)}de&&a[de].push(k)}return{dynamic:u,liveAvailabilityStartTime:d,duration:p,streams:a}};var _i=He(ni(),1);import{videoSizeToQuality as yw}from"@vkontakte/videoplayer-shared";var bb=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s})=>{let n=(s?St(s):void 0)??yw({width:e,height:t});return n&&{id:i,quality:n,bitrate:r,size:{width:e,height:t},fps:a}},Sb=({id:i,bitrate:e})=>({id:i,bitrate:e}),hs=(i,e,t)=>{let r=e.indexOf(i);return(0,_i.default)(t,Math.round(t.length*r/e.length))??(0,_i.default)(t,-1)},ms=({language:i,label:e},{id:t,url:r,isAuto:a})=>({id:t,url:r,isAuto:a,type:"internal",language:i,label:e}),fu=({id:i,language:e,label:t,codecs:r,isDefault:a})=>({id:i,language:e,label:t,codec:(0,_i.default)(r.split("."),0),isDefault:a}),bu=({id:i,language:e,label:t,hdr:r,codecs:a})=>({id:i,language:e,hdr:r,label:t,codec:(0,_i.default)(a.split("."),0)}),fs=i=>"url"in i,ot=i=>i.type==="template",Ni=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var qi=class{constructor(e,t,r,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:l=!1,manifest:u}){this.currentSegmentLength$=new Fi(0);this.onLastSegment$=new Fi(!1);this.fullyBuffered$=new Fi(!1);this.playingRepresentation$=new Fi(void 0);this.playingRepresentationInit$=new Fi(void 0);this.error$=new Iw;this.gaps=[];this.subscription=new Ew;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new at;this.destroyAbortController=new at;this.bufferLimit=1/0;this.failedDownloads=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Pr(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);We(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Of(this.sourceBuffer),this.subscription.add(Su(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,l=this.mediaSource.readyState;l!=="open"&&(o={id:`SegmentEjection_source_${l}`,category:Ut.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:Ut.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add(Su(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Ut.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 l=Math.min(this.bufferLimit,iu(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=l,this.tuning.useNewPruneBufferStrategy){let u=rt(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,n*2,u<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 r=this.initData.get(t.id),a=this.segments.get(t.id),s=this.parsedInitData.get(t.id);We(r,"No init buffer for starting representation"),We(a,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(a,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=Pr(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);We(r,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if(_e(s)||_e(a)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),We(a,"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();gb(n)&&(this.isLive||(a.forEach(o=>o.status="none"),this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Pr(this.destroyAbortController.signal,async function*(e){let t=e?.flatMap(l=>l.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let l of this.representations.keys()){let u=t.find(p=>p.id===l);u&&this.representations.set(l,u);let c=this.representations.get(l);if(!c||!ot(c.segmentReference))return;let d=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,d)}let r=this.switchingToRepresentationId??this.downloadingRepresentationId,a=this.representations.get(r);We(a);let s=this.segments.get(r);We(s,"No segments for starting representation");let n=this.initData.get(r);if(We(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,a),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=a,this.tuning=s,this.compatibilityMode=l,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!u?.dynamic,this.initData=new Map(r.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new at,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(_e(e)||_e(this.downloadingRepresentationId)||_e(this.playingRepresentationId)||_e(this.sourceBuffer)||!_e(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(We(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let a=r.find(u=>e>=u.time.from&&e<u.time.to);this.currentSegmentLength$.next((a?.time.to??0)-(a?.time.from??0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=rt(this.sourceBuffer.buffered,e),d=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=a.time.to-e+100&&(s=d)}if(isFinite(this.bufferLimit)&&iu(this.sourceBuffer.buffered)>=this.bufferLimit){let u=rt(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<c);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(o.includes(a))u="high";else{let c=(0,kr.default)(o,0);c&&c.time.from-a.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(o,t,u)}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!o.length&&rt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,kr.default)(r,-1);l&&l.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===l))}searchGaps(e,t){this.gaps=[];let r=0,a=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+a}),r=s.time.to;gb(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,a=[],s=0,n=t.length-1;do a.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[a[0]]:a}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind].flatMap(a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){let t=e?.streams[this.kind].flatMap(r=>r.representations)??[];for(let r of t){if(!r||!ot(r.segmentReference))return;let a=r.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=this.segments.get(r.id)??[],n=(0,kr.default)(s,-1)?.time.to??0,o=a?.findIndex(l=>Math.floor(n)>=Math.floor(l.time.from)&&Math.floor(n)<=Math.floor(l.time.to));if(o===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(r.segmentReference);this.segments.set(r.id,l)}else{let l=a.slice(o+1);this.segments.set(r.id,[...s,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;We(e);let t=this.segments.get(e);if(t?.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){for(let t of this.representations.values()){let r=t.segmentReference;if(!ot(r))return;let a=this.segments.get(t.id)??[],s=a.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(s&&!isFinite(s.time.to)&&(s.time.to=e.time.to),!!!a.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),l=nt(r.segmentTemplateUrl,{segmentTime:o});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);return r?r.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&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(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(a=>t>=a.time.from&&t<a.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let a=e.findIndex(({status:d,time:{from:p,to:h}},f)=>{let b=p<=r&&h>=r,S=p>r||b||f===0&&r===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),A=this.preloadOnly&&p<=r+v||h<=r+v;return(d==="none"||d==="partially_ejected"&&S&&A&&this.sourceBuffer&&!Si(this.sourceBuffer.buffered,r))&&S&&A});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let s=e,n=0,o=0,l=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<s.length&&(n<=u||o<=c);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}async loadSegments(e,t,r="auto"){t.segmentReference.type==="template"?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){e.status="downloading";let a={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(a);let{range:s,url:n,signal:o,onProgress:l,onProgressTasks:u}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Pr(o,async function*(){let c=gu(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:l,priority:r,isLowLatency:this.isActiveLowLatency()});if(!c)return;let d=new DataView(c);if(!isFinite(a.segment.time.to)){let p=t.segmentReference.timescale,h=Er(t.mime);a.segment.time.to=h.getSegmentEndTime(d,p)}l&&a.feedingBytes&&u?await Promise.all(u):await this.sourceBufferTaskQueue.append(d,o),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Ni(c)||this.failedDownloads++}}async loadByteRangeSegments(e,t,r="auto"){if(!e.length)return;for(let l of e)l.status="downloading",this.activeSegments.add({segment:l,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:a,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Pr(n,async function*(){let l=gu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(u,l),Su(window,"online").pipe(Tw()).subscribe(()=>{u(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:a,onProgress:o,signal:n,priority:r}),this.failedDownloads=0}catch(l){this.abortActiveSegments(e),Ni(l)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(ot(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,kr.default)(e,0).byte.from,to:(0,kr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:a,signal:s,onProgress:(o,l)=>{if(!s.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:l,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:a?a.from:0,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:Ut.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}}}}prepareTemplateFetchSegmentParams(e,t){if(!ot(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let a=r.toString(),{signal:s}=this.downloadAbortController,n=[],l=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(u,c)=>{if(!s.aborted)try{let d=this.onSomeTemplateDataLoaded({dataView:u,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Ut.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:a,signal:s,onProgress:l,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:a,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:l}=o;if(o.representationId===t){if(s.aborted){a();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let u=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=Er(n.mime).parseFeedableSegmentChunk(u,this.isLive);c?.byteLength&&(l.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){let o={dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let l=o.segmentReference.type,u=e.byteLength;for(let c of this.activeSegments){let{segment:d}=c,p=l==="byteRange",h=p?d.byte.to-d.byte.from+1:u;if(c.representationId!==t||!(!p||d.byte.from>=r&&d.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let b=p?d.byte.from-r:0,S=p?d.byte.to-r:e.byteLength,v=b<a,A=S<=a;if(d.status==="downloading"&&v&&A){d.status="downloaded";let y=new DataView(e.buffer,e.byteOffset+b,h);this.sourceBufferTaskQueue.append(y,s).then(g=>g&&!s.aborted?this.onSegmentFullyAppended(c,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&v&&(c.loadedBytes=Math.min(h,a-b),c.loadedBytes>c.feedingBytes)){let y=new DataView(e.buffer,e.byteOffset+b+c.feedingBytes,c.loadedBytes-c.feedingBytes),g=c.loadedBytes===h?y:Er(o.mime).parseFeedableSegmentChunk(y);g?.byteLength&&(d.status="partially_fed",c.feedingBytes+=g.byteLength,this.sourceBufferTaskQueue.append(g,s).then(T=>{if(s.aborted)n();else if(T)c.fedBytes+=g.byteLength,c.fedBytes===h&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<h)return;n()}}))}}}async onSomeByteRangesDataLoadedNew({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let l of this.activeSegments){let{segment:u}=l;if(l.representationId!==t)continue;if(s.aborted){n();continue}let c=u.byte.from-r,d=u.byte.to-r,p=d-c+1,h=c<a,f=d<=a;if(h){if(u.status==="downloading"&&f){u.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+c,p);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(l,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(u.status==="downloading"||u.status==="partially_fed")&&(l.loadedBytes=Math.min(p,a-c),l.loadedBytes>l.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+c+l.feedingBytes,l.loadedBytes-l.feedingBytes),S=l.loadedBytes===p?b:Er(o.mime).parseFeedableSegmentChunk(b);S?.byteLength&&(u.status="partially_fed",l.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?(l.fedBytes+=S.byteLength,l.fedBytes===p&&this.onSegmentFullyAppended(l,t)):n())}}}}onSegmentFullyAppended(e,t){this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",fs(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let a of this.segments.get(r.id)??[])a.status==="fed"&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){(this.tuning.useDashAbortPartiallyFedSegment?e.status==="partially_fed"||e.status==="partially_ejected":e.status==="partially_ejected")?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status="none"),e.status="partially_ejected"):e.status="none";for(let r of this.activeSegments.values())if(r.segment===e){this.activeSegments.delete(r);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[a,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=eu(()=>(0,vb.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",r=!1){let a=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?Pr(this.destroyAbortController.signal,async function*(){let o=gu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Er(e.mime),a)).then(async o=>{if(!o)return;let{init:l,dataView:u,segments:c}=o,d=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&ot(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),l&&this.parsedInitData.set(e.id,l)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:Ut.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,r=!1){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,r):this.pruneBufferOld(e,t,r)}async pruneBufferNew(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||_e(e)||this.sourceBuffer.updating)return!1;let a=[],s=0,n=l=>{l.sort((c,d)=>c.from-d.from);let u=[l[0]];for(let c=1;c<l.length;c++){let{from:d,to:p}=l[c],h=u[u.length-1];h.to>=d?h.to=Math.max(h.to,p):u.push(l[c])}return u},o=l=>{if(s>=t)return a;a.push(l.time),a=n(a);let u=fs(l)?l.size??0:l.byte.to-l.byte.from;s+=u};for(let l of this.segments.values())for(let u of l){let c=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&u.status==="fed"&&o(u)}for(let l=0;l<this.sourceBuffer.buffered.length;l++){let u=this.sourceBuffer.buffered.start(l)*1e3,c=this.sourceBuffer.buffered.end(l)*1e3,d=0;for(let p of this.segments.values())for(let h of p)h.status==="none"&&Math.round(h.time.from)<=Math.round(u)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:u,to:c},url:"",status:"none"};o(p)}}if(a.length&&r){let l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let c of u)c.time.from>=e+l&&c.status==="fed"&&o(c)}return a.length?(await Promise.all(a.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,c)=>u||c,!1):!1}async pruneBufferOld(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||_e(e)||this.sourceBuffer.updating)return!1;let a=0,s=1/0,n=-1/0,o=!1,l=u=>{s=Math.min(s,u.time.from),n=Math.max(n,u.time.to);let c=fs(u)?u.size??0:u.byte.to-u.byte.from;a+=c};for(let u of this.segments.values())for(let c of u){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;c.status==="fed"&&l(c)}if(o=isFinite(s)&&isFinite(n),!o){a=0,s=1/0,n=-1/0;for(let u of this.segments.values())for(let c of u){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||a>t)break;c.status==="fed"&&l(c)}}if(o=isFinite(s)&&isFinite(n),!o)for(let u=0;u<this.sourceBuffer.buffered.length;u++){let c=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3;for(let p of this.segments.values())for(let h of p)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(d)){s=c,n=d;break}}if(o=isFinite(s)&&isFinite(n),!o&&r){a=0,s=1/0,n=-1/0;let u=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+u&&d.status==="fed"&&l(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)}}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let a={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){a=void 0;break}o>r.time.from&&o<r.time.to&&(a.from=o),n<r.time.to&&n>r.time.from&&(a.to=n)}}a&&a.to-a.from>1&&!this.gaps.some(s=>a&&s.from===a.from&&s.to===a.to)&&this.gaps.push(a)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=eu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Ut.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(_e(this.sourceBuffer)||_e(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let a=Math.round(this.sourceBuffer.buffered.start(r)*1e3),s=Math.round(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:a,to:s})}let t=1;for(let r of this.segments.values())for(let a of r){let{status:s}=a;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(a.time.from),o=Math.ceil(a.time.to),l=e.some(c=>c.from-t<=n&&c.to+t>=o),u=e.filter(c=>n>=c.from-t&&n<=c.to+t||o>=c.from-t&&o<=c.to+t);l||(u.length===1?a.status="partially_ejected":this.gaps.some(c=>c.from===a.time.from||c.to===a.time.to)?a.status="partially_ejected":a.status="none")}}};var Ui=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var yb=i=>{let e=i.get("X-Delivery-Type"),t=i.get("X-Reused"),r=e===null?"http1":e??void 0,a=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:r,reused:a}};import{abortable as Hi,assertNever as Tb,fromEvent as Ib,merge as xw,now as vu,Subscription as Pw,ValueSubject as yu}from"@vkontakte/videoplayer-shared";var bs=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new yu(void 0);this.lastConnectionReused$=new yu(void 0);this.lastRequestFirstBytes$=new yu(void 0);this.abortAllController=new at;this.subscription=new Pw;this.fetchManifest=Hi(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=Ui(t));let r=yield it(t,{signal:this.abortAllController.signal}).catch(ji);return r?(this.onHeadersReceived(r.headers),r.text()):null}.bind(this));this.fetch=Hi(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:a,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:l=!1}={}){let u=e,c=new Headers;if(r)switch(t){case 0:{c.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let R=new URL(u,location.href);R.searchParams.append("bytes",`${r.from}-${r.to}`),u=R.toString();break}default:Tb(t)}this.requestQuic&&(u=Ui(u));let d=this.abortAllController.signal,p;if(n){let R=new at;if(p=xw(Ib(this.abortAllController.signal,"abort"),Ib(n,"abort")).subscribe(()=>{try{R.abort()}catch(O){ji(O)}}),this.abortAllController.signal.aborted||n.aborted)try{R.abort()}catch(O){ji(O)}d=R.signal}let h=vu(),f=yield it(u,{priority:s,headers:c,signal:d}).catch(ji),b=vu();if(!f)return p?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(b-h),!f.ok||!f.body)return p?.unsubscribe(),Promise.reject(new Error(`Fetch error ${f.status}: ${f.statusText}`));if(this.onHeadersReceived(f.headers),!a&&!o)return p?.unsubscribe(),f.arrayBuffer();let[S,v]=f.body.tee(),A=S.getReader();o&&this.throughputEstimator?.trackStream(v,l);let y=0,g=new Uint8Array(0),T=!1,M=R=>{p?.unsubscribe(),T=!0,ji(R)},x=Hi(d,async function*({done:R,value:O}){if(y===0&&this.lastRequestFirstBytes$.next(vu()-h),d.aborted){p?.unsubscribe();return}if(!R&&O){let P=new Uint8Array(g.length+O.length);P.set(g),P.set(O,g.length),g=P,y+=O.byteLength,a?.(new DataView(g.buffer),y),yield A?.read().then(x,M)}}.bind(this));return yield A?.read().then(x,M),p?.unsubscribe(),T?null:g.buffer}.bind(this));this.fetchByteRangeRepresentation=Hi(this.abortAllController.signal,async function*(e,t,r){if(e.type!=="byteRange")return null;let{from:a,to:s}=e.initRange,n=a,o=s,l=!1,u,c;e.indexRange&&(u=e.indexRange.from,c=e.indexRange.to,l=s+1===u,l&&(n=Math.min(u,a),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,a-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=e.indexRange??t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(l)b=new DataView(d,f.from-n,f.to-f.from+1);else{let v=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!v)return null;b=new DataView(v)}let S=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(d),segments:S}}.bind(this));this.fetchTemplateRepresentation=Hi(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),a=yield this.fetch(r,{priority:t,measureThroughput:!1});return a?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(a)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r}onHeadersReceived(e){let{type:t,reused:r}=yb(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){let{type:a}=e;switch(a){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,r)??null;case"template":return await this.fetchTemplateRepresentation(e,r)??null;default:Tb(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},ji=i=>{if(!Ni(i))throw i};var Ht=(i,e,t)=>t*e+(1-t)*i,Tu=(i,e)=>i.reduce((t,r)=>t+r,0)/e,Eb=(i,e,t,r)=>{let a=0,s=t,n=Tu(i,e),o=e<r?e:r;for(let l=0;l<o;l++)i[s]>n?a++:a--,s=(i.length+s-1)%i.length;return Math.abs(a)===o};import{isNullable as kw,ValueSubject as xb}from"@vkontakte/videoplayer-shared";var yt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new xb(e.initial),this.debounced$=new xb(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new te(`raw_${t}`),this.smoothedSeries$=new te(`smoothed_${t}`),this.reportedSeries$=new te(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,r++);this.takenMeasures=r,t/=r;let a=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*a,n=this.smoothed-this.params.deviationFactor*a;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(kw(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 Ss=class extends yt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Ht(this.slow,e,this.params.emaAlphaSlow),this.fast=Ht(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var gs=class extends yt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Tu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ht(this.emaSmoothed,e,this.params.emaAlpha);let r=Eb(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var vs=class extends yt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?Ht(this.smoothed,t,this.params.emaAlpha):t}};var jt=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new Ss({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new gs({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new vs({initial:e,label:"liveEdgeDelay",...t})}};var Iu=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};import{isNullable as ww,ValueSubject as Aw}from"@vkontakte/videoplayer-shared";var Gi=class i{constructor(e,t){this.currentRepresentation$=new Aw(null);this.currentSegment=null;this.currentSegmentId=0;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(ww(e))return;let t=null,r=null;for(let a of this.representations){let s=a.segmentReference.segments.find(n=>n.time.from<=e&&n.time.to>=e);if(s){t=s,r=a;break}}!t||!r||this.currentSegment?.time.from===t.time.from&&this.currentSegment.time.to===t.time.to||(this.currentSegment=t,this.currentSegmentId=(this.currentSegmentId+1)%Number.MAX_SAFE_INTEGER,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(t.url,r.segmentReference.baseUrl).toString(),id:`subtitle-${this.currentSegmentId.toString(10)}`}))}destroy(){this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let r=i.filterRepresentations(t.representations);if(r){this.representations=r;break}}}static isSupported(e){return!!e?.some(t=>i.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&ot(t.segmentReference))}};var Lb=["timeupdate","progress","play","seeked","stalled","waiting"];var Is=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Rb;this.representationSubscription=new Rb;this.state$=new L("none");this.currentVideoRepresentation$=new J(void 0);this.currentVideoRepresentationInit$=new J(void 0);this.currentAudioRepresentation$=new J(void 0);this.currentVideoSegmentLength$=new J(0);this.currentAudioSegmentLength$=new J(0);this.error$=new Ab;this.lastConnectionType$=new J(void 0);this.lastConnectionReused$=new J(void 0);this.lastRequestFirstBytes$=new J(void 0);this.currentLiveTextRepresentation$=new J(null);this.isLive$=new J(!1);this.liveDuration$=new J(0);this.liveAvailabilityStartTime$=new J(void 0);this.bufferLength$=new J(0);this.liveLoadBufferLength$=new J(0);this.livePositionFromPlayer$=new J(0);this.timeInWaiting=0;this.isActiveLowLatency$=new J(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new Ab;this.gapWatchdogActive=!1;this.destroyController=new at;this.initManifest=Eu(this.destroyController.signal,async function*(e,t,r){this.element=e,this.manifestUrlString=K(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Tt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Eu(this.destroyController.signal,async function*(){let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(s=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Tt.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return null;let t=null;try{t=fb(e??"",this.manifestUrlString)}catch(s){let n=Lf(e)??{id:"ManifestParsing",category:Tt.PARSER,message:"Failed to parse MPD manifest",thrown:s};this.error$.next(n)}if(!t)return null;let r=(s,n,o)=>!!(this.element?.canPlayType?.(n)&&st()?.isTypeSupported?.(`${n}; codecs="${o}"`)||s==="text");t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let a={text:t.streams.text,video:[],audio:[]};for(let s of["video","audio"]){let o=t.streams[s].filter(({mime:c,codecs:d})=>r(s,c,d)),l=new Set(o.map(({codecs:c})=>c)),u=Rf(l);if(u&&(a[s]=o.filter(({codecs:c})=>c.startsWith(u))),s==="video"){let c=this.tuning.preferHDR,d=a.video.some(h=>h.hdr),p=a.video.some(h=>!h.hdr);Cw.isHDR&&c&&d?a.video=a.video.filter(h=>h.hdr):p&&(a.video=a.video.filter(h=>!h.hdr))}}return{...t,streams:a}}.bind(this));this.initRepresentations=Eu(this.destroyController.signal,async function*(e,t,r){Gt(this.manifest),Gt(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=d=>{this.representationSubscription.add(wr(d,"error").pipe(Ts(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:Tt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=this.tuning.useManagedMediaSource?Tf():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&us())if(r){let d=document.createElement("source");a(d),d.type="application/x-mpegurl",d.src=r.url,this.element.appendChild(d)}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((d,p)=>[...d,...p.representations],[]);if(this.videoBufferManager=new qi("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],wb(t)){let d=this.manifest.streams.audio.reduce((p,h)=>[...p,...h.representations],[]);this.audioBufferManager=new qi("audio",this.source,d,n),this.bufferManagers.push(this.audioBufferManager)}if(Gi.isSupported(this.manifest.streams.text)&&(this.liveTextManager=new Gi(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(xu(1e3).subscribe(d=>{if(this.element?.paused){let p=Co(this.manifestUrlString,2);this.manifestUrlString=K(this.manifestUrlString,p+1e3,2)}})),this.representationSubscription.add(Ar(...Lb.filter(d=>d!=="waiting").map(d=>wr(this.element,d))).pipe(Pu(d=>this.element?rt(this.element.buffered,this.element.currentTime*1e3):0),kb(),Ts(d=>!!d),$w(d=>{this.stallWatchdogSubscription?.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(kb()).subscribe(p=>Iu(this.element,1))),this.representationSubscription.add(ys({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(Ts(({bufferLength:p,isActiveLowLatency:h})=>h&&!!p)).subscribe(({bufferLength:p})=>this.liveEstimatedDelay.next(p))),this.representationSubscription.add(ys({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:p,isActiveLowLatency:h})=>{if(!h)return;let f=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,b=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,v=p-f,A=1;Math.abs(v)>b&&(A=1+Math.sign(v)*S),Iu(this.element,A)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let h=0;if(p){let f=(this.element?.currentTime??0)*1e3;h=Math.min(...this.bufferManagers.map(S=>S.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==h&&this.liveLoadBufferLength$.next(h)}));let d=0;this.representationSubscription.add(ys({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Mw(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:h})=>{if(Gt(this.element),this.isUpdatingLive)return;let f=this.element.playbackRate,b=Co(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),A=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,g=isFinite(p)?p:h,T=this.isActiveLowLatency$.getValue(),M=S<=this.tuning.live.activeLiveDelay&&b===0;this.isActiveLowLatency$.next(T&&M);let x="none";if(T?x="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&M?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(R=>R.proceedLowLatencyLive()),x="active_low_latency"):b!==0&&g<v?x="live_forward_buffering":g<v+y&&(x="live_with_target_offset"),isFinite(p)&&(d=p>d?p:d),x==="live_forward_buffering"||x==="live_with_target_offset"){let R=d-(v+A),O=this.normolizeLiveOffset(Math.trunc(b+R/f)),P=Math.abs(O-b),V;!p||P<=this.tuning.dashCmafLive.offsetCalculationError?V=b:O>0&&P>this.tuning.dashCmafLive.offsetCalculationError?V=O:V=0,this.manifestUrlString=K(this.manifestUrlString,V,2)}x!=="none"&&x!=="active_low_latency"&&(d=0,this.updateLive())}))}let l=Ar(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe(Pu(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),u=Ar(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe(Pu(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue())));this.representationSubscription.add(Ar(this.forceEnded$,ys({allBuffersFull:l,someBufferEnded:u}).pipe(Ts(({allBuffersFull:d,someBufferEnded:p})=>d&&p))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{this.source?.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:Tt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add(Ar(...this.bufferManagers.map(d=>d.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(d=>this.source?.addEventListener("sourceopen",d)));let c=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(d=>d.representations).flatMap(d=>d.duration??0)];this.source.duration=Math.max(...c)/1e3,this.audioBufferManager&&wb(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=xu(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Tt.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new bs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=jt.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){Gt(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=K(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest?.streams.video),await this.audioBufferManager?.seekLive(this.manifest?.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){Gt(this.element),this.state$.setState("running"),this.subscription.add(Ar(...Lb.map(e=>wr(this.element,e)),wr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Tt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(wr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(wr(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Si(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(this.element){if(this.timeInWaiting+=1e3,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset);else{let t=this.element.currentTime*1e3;this.videoBufferManager?.maintain(t),this.audioBufferManager?.maintain(t)}}};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=xu(1e3).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:Tt.FATAL,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,r)}seek(e,t){Gt(this.element),Gt(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),Si(this.element.buffered,r)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(r),this.audioBufferManager?.maintain(r),this.element.currentTime=r/1e3}stop(){this.element?.querySelectorAll("source").forEach(e=>e.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let t=this.element.currentTime*1e3,r=[],a=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let s of this.bufferManagers)for(let n of s.gaps)s.playingRepresentation$.getValue()===n.representation&&n.from-a<=t&&n.to+a>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?r.push(1/0):r.push(n.to));if(r.length){let s=Math.max(...r)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,s===1/0?this.forceEnded$.next():this.element.currentTime=s/1e3}}};var Es=class{constructor(e,t){this.fov=e,this.orientation=t}};var xs=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let a=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:a,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=r??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let a=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*a,this.fadeStartSpeed.y*a,this.fadeStartSpeed.z*a),a>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var $b=`attribute vec2 a_vertex;
|
|
36
|
+
[best video track] ${O?.quality}
|
|
37
|
+
[selected video track] ${N?.quality}
|
|
38
|
+
`}),hm(r,p,N,u)},fm=(i,e,t,{throughput:r,tuning:a,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:c})=>{lm(t,pm);let u=a.considerPlaybackRate&&ce(s)?s:1,d=[...t].sort(Go(-1)),l=i.bitrate;WP(l);let p=u*dm(n??.5,a.bitrateAudioFactorAtEmptyBuffer,a.bitrateAudioFactorAtFullBuffer),h;return ce(r)&&isFinite(r)&&(h=d.find(m=>ce(m.bitrate)?r-l>=m.bitrate*p:!0)),h||(h=Ka(i,e,t,a.minVideoAudioRatio)),h?.bitrate!==o?.last?.bitrate&&c({message:`
|
|
39
|
+
[AUDIO TRACKS ABR]
|
|
40
|
+
[available audio tracks]
|
|
41
|
+
${t.map(m=>`{ id: ${m.id}, bitrate: ${m.bitrate} }`).join(`
|
|
42
|
+
`)}
|
|
43
|
+
|
|
44
|
+
[tuning]
|
|
45
|
+
${Object.entries(a??{}).map(([m,b])=>`${m}: ${b}`).join(`
|
|
46
|
+
`)}
|
|
47
|
+
|
|
48
|
+
[limit params]
|
|
49
|
+
throughput: ${r},
|
|
50
|
+
reserve: ${l},
|
|
51
|
+
playbackRate: ${s},
|
|
52
|
+
playbackRateFactor: ${u},
|
|
53
|
+
forwardBufferHealth: ${n},
|
|
54
|
+
bitrateFactor: ${p},
|
|
55
|
+
minBufferToSwitchUp: ${a.minBufferToSwitchUp},
|
|
56
|
+
|
|
57
|
+
[selected audio track] ${h?.id}
|
|
58
|
+
`}),h&&hm(a,c,h,o)};var Y=i=>new URL(i).hostname;import{assertNever as ym,assertNonNullable as Tm,combine as hA,debounce as fA,ErrorCategory as Im,filter as Em,filterChanged as mA,isNonNullable as Ko,map as ts,merge as xm,observableFrom as bA,once as gA,Subscription as SA,ValueSubject as Jo,videoQualityToHeight as vA,videoSizeToQuality as yA}from"@vkontakte/videoplayer-shared";var mm=i=>{if(i instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(i.message))throw i;return!(i instanceof DOMException&&(i.code===20||i.name==="AbortError"))},le=async i=>{let e=i.muted;try{await i.play()}catch(t){if(!mm(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{await i.play()}catch(r){return mm(r)&&(i.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as Xa,isNullable as KP,assertNonNullable as oi}from"@vkontakte/videoplayer-shared";import{isNonNullable as bm,assertNonNullable as Ja,now as QP}from"@vkontakte/videoplayer-shared";function Q(){return QP()}function Wo(i){return Q()-i}function Yo(i){let e=i.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,a=n=>r.test(n);return{resolve:(n,o,c=!1)=>{a(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let u=n.indexOf("?")>-1?"&":"?";return c&&(n+=u+"lowLat=1",u="&"),o&&(n+=u+"_rnd="+Math.floor(999999999*Math.random())),n}}}function gm(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function pr(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,c=!1,u=0,d,l,p=!1,h="arraybuffer",m=7e3,b=2e3,g=()=>{if(c)return;Ja(d);let $=Wo(d),q;if($<b){q=b-$,setTimeout(g,q);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new a,E()},v=$=>(s=$,w),A=$=>(l=$,w),y=()=>(h="json",w),S=()=>{if(!c){if(--u>=0){g(),r&&r();return}c=!0,l&&l(),t&&t()}},T=$=>(p=$,w),E=()=>{d=Q(),n=new a,n.open("get",i);let $=0,q,ke=0,te=()=>(Ja(d),Math.max(d,Math.max(q||0,ke||0)));if(s&&n.addEventListener("progress",x=>{let R=Q();s.updateChunk&&x.loaded>$&&(s.updateChunk(te(),x.loaded-$),$=x.loaded,q=R)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>S())),n.addEventListener("load",()=>{if(c)return;Ja(n);let x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&s){let R=n.response.byteLength-$;R&&s.updateChunk&&s.updateChunk(te(),R)}n.responseType==="json"&&!Object.values(n.response).length?S():(l&&l(),e(n.response))}else S()}),n.addEventListener("error",()=>{S()}),p){let x=()=>{Ja(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ke=Q(),n.removeEventListener("readystatechange",x))};n.addEventListener("readystatechange",x)}return n.responseType=h,n.send(),w},w={withBitrateReporting:v,withParallel:T,withJSONResponse:y,withRetryCount:$=>(u=$,w),withRetryInterval:($,q)=>(bm($)&&(b=$),bm(q)&&(m=q),w),withTimeout:$=>(o=$,w),withFinally:A,send:E,abort:()=>{n&&(n.abort(),n=void 0),c=!0,l&&l()}};return w}var si=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,a=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,a+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let c=s.bytes*n/o;a+=c,s.start=t,s.bytes-=c}}}if(a>0&&r>0){let s=a*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(a)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var ni=class{constructor(e,t,r,a,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=a,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=Q(),a=c=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=c,e._errorCB?e._errorCB(c):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=c=>{e._complete=1,e._responseData=c,e._downloadTime=Q()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(c,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=pr(t,s,()=>a("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Q()}_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=Q();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,a){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=a,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=a,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var Za=1e4,Qo=3;var JP=6e4,XP=10,ZP=1,eA=500,ui=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.chunkRateEstimator=new si(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Yo(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Yo(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,a;r!==0&&(a=t.buffered.start(r-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){let{videoElement:t}=this.params,r,a,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!a||s.bitrate>a.bitrate)&&(a=s):(!r||r.bitrate>s.bitrate)&&(r=s));return a||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Xa(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:a,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),a.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,a.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{gm(a,"progress",()=>{a.buffered.length?(a.currentTime=a.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new ni(Qo,Za,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:a}=this.params,s=!1,n=null,o=null,c=null,u=null,d=!1,l=()=>{let S=s&&(!d||d===this.rep);return S||t("Not running!"),S},p=(S,T,E)=>{c&&c.abort(),c=pr(this.urlResolver.resolve(S,!1),T,E,()=>this._retryCallback()).withTimeout(Za).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Qo).withFinally(()=>{c=null}).send()},h=(S,T,E)=>{oi(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(S,!1),T,E,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=S=>{let T=r.playbackRate;r.playbackRate!==S&&(t(`Playback rate switch: ${T}=>${S}`),r.playbackRate=S)},b=S=>{this.lowLatency=S,t(`lowLatency changed to ${S}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let S=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let E=Q()-1e4,D=0;for(let N=0;N<this.bufferStates.length;N++){let k=this.bufferStates[N];S=Math.min(S,k.buf),k.ts<E&&D++}this.bufferStates.splice(0,D),t(`update playback rate; minBuffer=${S} drop=${D} jitter=${this.sourceJitter}`);let O=S-ZP;this.sourceJitter>=0?O-=this.sourceJitter/2:this.sourceJitter-=1,O>3?m(1.15):O>1?m(1.1):O>.3?m(1.05):m(1)}},v=S=>{let T,E=()=>T&&T.start?T.start.length:0,D=x=>T.start[x]/1e3,O=x=>T.dur[x]/1e3,N=x=>T.fragIndex+x,k=(x,R)=>({chunkIdx:N(x),startTS:D(x),dur:O(x),discontinuity:R}),w=()=>{let x=0;if(T&&T.dur){let R=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,G=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,z=R;this.sourceJitter>1&&(z+=this.sourceJitter-1);let he=T.dur.length-1;for(;he>=0&&(z-=T.dur[he],!(z<=0));--he);x=Math.min(he,T.dur.length-1-G),x=Math.max(x,0)}return k(x,!0)},$=x=>{let R=E();if(!(R<=0)){if(Xa(x)){for(let G=0;G<R;G++)if(D(G)>x)return k(G)}return w()}},q=x=>{let R=E(),G=x?x.chunkIdx+1:0,z=G-T.fragIndex;if(!(R<=0)){if(!x||z<0||z-R>XP)return t(`Resync: offset=${z} bChunks=${R} chunk=`+JSON.stringify(x)),w();if(!(z>=R))return k(G-T.fragIndex,!1)}},ke=(x,R,G)=>{u&&u.abort(),u=pr(this.urlResolver.resolve(x,!0,this.lowLatency),R,G,()=>this._retryCallback()).withTimeout(Za).withRetryCount(Qo).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(x,R)=>{ke(S,G=>{if(!l())return;T=G;let z=!!T.lowLatency;z!==this.lowLatency&&b(z);let he=0;for(let Ve=0;Ve<T.dur.length;++Ve)he+=T.dur[Ve];he>0&&(oi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(he/T.dur.length)),a({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,x($(R))},()=>this._handleNetworkError())},nextChunk:q}},A=()=>{s=!1,o&&o.abort(),c&&c.abort(),u&&u.abort(),oi(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:S=>{let{videoElement:T,logger:E}=this.params,D=v(e.jidxUrl),O,N,k,w,$=0,q,ke,te,x=()=>{q&&(clearTimeout(q),q=void 0);let B=Math.max(eA,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),W=$+B,re=Q(),we=Math.min(1e4,W-re);$=re;let tt=()=>{u||l()&&D.seek(()=>{l()&&($=Q(),R(),x())})};we>0?q=window.setTimeout(()=>{this.paused?x():tt()},we):tt()},R=()=>{let B;for(;B=D.nextChunk(w);)w=B,Ut(B);let W=D.nextChunk(k);if(W){if(k&&W.discontinuity){E("Detected discontinuity; restarting playback"),this.paused?x():(A(),this._initPlayerWith(e));return}Ve(W)}else x()},G=(B,W)=>{if(!l()||!this.sourceBuffer)return;let re,we,tt,Ht=rt=>{window.setTimeout(()=>{l()&&G(B,W)},rt)};if(this.sourceBuffer.updating)E("Source buffer is updating; delaying appendBuffer"),Ht(100);else{let rt=Q(),jt=T.currentTime;!this.paused&&T.buffered.length>1&&ke===jt&&rt-te>500&&(E("Stall suspected; trying to fix"),this._fixupStall()),ke!==jt&&(ke=jt,te=rt);let Ar=this._getBufferSizeSec();if(Ar>30)E(`Buffered ${Ar} seconds; delaying appendBuffer`),Ht(2e3);else try{this.sourceBuffer.appendBuffer(B),this.videoPlayStarted?(this.bufferStates.push({ts:rt,buf:Ar}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),W&&W()}catch(sa){if(sa.name==="QuotaExceededError")E("QuotaExceededError; delaying appendBuffer"),tt=this.sourceBuffer.buffered.length,tt!==0&&(re=this.sourceBuffer.buffered.start(0),we=jt,we-re>4&&this.sourceBuffer.remove(re,we-3)),Ht(1e3);else throw sa}}},z=()=>{N&&O&&(E([`Appending chunk, sz=${N.byteLength}:`,JSON.stringify(k)]),G(N,function(){N=null,R()}))},he=B=>e.fragUrlTemplate.replace("%%id%%",B.chunkIdx),Ve=B=>{l()&&h(he(B),(W,re)=>{if(l()){if(re/=1e3,N=W,k=B,n=B.startTS,re){let we=Math.min(10,B.dur/re);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*we:we}z()}},()=>this._handleNetworkError())},Ut=B=>{l()&&(oi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(he(B),!1)))},gt=B=>{l()&&(e.cachedHeader=B,G(B,()=>{O=!0,z()}))};s=!0,D.seek(B=>{if(l()){if($=Q(),!B){x();return}w=B,!KP(S)||B.startTS>S?Ve(B):(k=B,R())}},S),e.cachedHeader?gt(e.cachedHeader):p(e.headerUrl,gt,()=>this._handleNetworkError())},stop:A,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),Xa(a)&&(a+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,oi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Xa(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=l=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&l<this.bitrate&&(h=this._getBufferSizeSec(),m=l/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(l)}`);return}p=this._selectQuality(l),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${l}`)},s={updateChunk:(p,h)=>{let m=Q();if(this.chunkRateEstimator.addInterval(p,m,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,c=!0,u=()=>{let l=s.get();if(l&&o&&this.autoQuality){if(c&&l>o&&Wo(n)<3e4)return;r(l)}c=this.autoQuality};return{updateChunk:(l,p)=>{let h=s.updateChunk(l,p);return h&&u(),h},notifySwitch:l=>{let p=Q();l<o&&(n=p),o=l}}}_fetchManifest(e,t,r){this.manifestRequest=pr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Za).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;le(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:a}=this.params,s=n=>{let o=[];return n?.length?(n.forEach((c,u)=>{c.video&&a.canPlayType(c.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(c.codecs)&&(c.index=u,o.push(c))}),o.sort(function(c,u){return c.video&&u.video?u.video.height-c.video.height:u.bitrate-c.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},JP))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as tA,filter as Sm,fromEvent as rA,interval as iA,isHigher as aA,isInvariantQuality as sA,isLower as nA,merge as oA,Subject as vm,Subscription as uA}from"@vkontakte/videoplayer-shared";var zo=class{constructor(){this.onDroopedVideoFramesLimit$=new vm;this.subscription=new uA;this.playing=!1;this.tracks=[];this.forceChecker$=new vm;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!sA(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,a=t-this.prevDroppedVideoFrames,s=1-(r-a)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&aA(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(rA(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=iA(this.droppedFramesChecker.checkTime).pipe(Sm(()=>this.playing),Sm(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(tA(this.droppedFramesChecker.checkTime)),r=oA(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){let t=Object.entries(this.limitCounts).filter(([,r])=>r>=this.droppedFramesChecker.countLimit).sort(([r],[a])=>nA(r,a)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},es=zo;import{map as cA,Observable as lA}from"@vkontakte/videoplayer-shared";import{fromEvent as dA}from"@vkontakte/videoplayer-shared";var ci=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var pA=(i,e)=>new lA(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(c=>t.next(c.isIntersecting||ci()))},{...r,...e});a.observe(i);let s=dA(document,"visibilitychange").pipe(cA(n=>!document.hidden||ci())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),Pe=pA;var TA=["paused","playing","ready"],IA=["paused","playing","ready"],li=class{constructor(e){this.subscription=new SA;this.videoState=new L("stopped");this.representations$=new Jo([]);this.textTracksManager=new Ee;this.droppedFramesManager=new es;this.maxSeekBackTime$=new Jo(1/0);this.zeroTime$=new Jo(void 0);this.liveOffset=new Ye;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Im.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,r=[];for(let a of t){let s=a.name??a.index.toString(10),n=ct(a.name)??yA(a.video),o=a.bitrate/1e3,c={...a.video};if(!n)continue;let u={id:s,quality:n,bitrate:o,size:c};r.push({track:u,representation:a})}this.representations$.next(r),this.params.output.availableVideoTracks$.next(r.map(({track:a})=>a)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,r=this.representations$.getValue().find(({representation:a})=>a===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),Ko(r)&&this.params.output.currentVideoTrack$.next(r);break}case"bandwidth":{let{size:t,duration:r}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,r);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(IA.includes(e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&TA.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(K(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let c=a?.from;c&&c==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let 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.dash.reinit(K(this.params.source.url,c))}return;default:return ym(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:Im.WTF,message:"DashLiveProvider internal logic error",thrown:a})};xm(this.videoState.stateChangeStarted$.pipe(ts(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ts(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=se(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),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(Y(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.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=ue(this.video);this.subscription.add(this.representations$.pipe(ts(a=>a.map(({track:s})=>s)),Em(a=>!!a.length),gA()).subscribe(a=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:a}))),this.subscription.add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(mA(),ts(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(hA({zeroTime:this.zeroTime$.pipe(Em(Ko)),position:r.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(Fe(this.video,this.params.desiredState.isLooped,t)).add(oe(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Ie(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Pe(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&vA(a);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:a})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return ym(a.to)}},t)).add(xm(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,bA(["init"])).pipe(fA(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),ne(this.video)}createLiveDashPlayer(){let e=new ui({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),a=!r&&Ko(t)?t:lt(e.map(({track:u})=>u),{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=a?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),c&&this.setAutoQuality(r),n||c||s!==o){let u=e.find(({track:d})=>d.id===s)?.representation;Tm(u,"Representations missing"),this.dash.startPlay(u,r)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:r})=>r.id===e.id)?.representation;Tm(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),a=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(K(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var Pm=li;var ze=(i,e)=>{let t=0;for(let r=0;r<i.length;r++){let a=i.start(r)*1e3,s=i.end(r)*1e3;a<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as Wk,assertNonNullable as Yk,debounce as Qk,ErrorCategory as Pu,filter as qb,filterChanged as Au,fromEvent as zk,isNonNullable as Kk,map as Ub,merge as Ts,observableFrom as Jk,observeElementSize as Xk,once as Hb,Subscription as Zk,ValueSubject as ew}from"@vkontakte/videoplayer-shared";var rs=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let a=0,s=r.length;a<s;a++)if(r[a].callback===t){r.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let a=0,s=r.length;a<s;a++){let n=r[a];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},hr=class extends rs{constructor(){super(),this.listeners||rs.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},di=class{constructor(){Object.defineProperty(this,"signal",{value:new hr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document>"u")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch{r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(di.prototype[Symbol.toStringTag]="AbortController",hr.prototype[Symbol.toStringTag]="AbortSignal");function is(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function Xo(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!is({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||a)&&(s=function(u,d){let l;d&&d.signal&&(l=d.signal,delete d.signal);let p=new t(u,d);return l&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:l}),p},s.prototype=t.prototype);let n=e;return{fetch:(c,u)=>{let d=s&&s.prototype.isPrototypeOf(c)?c.signal:u?u.signal:void 0;if(d){let l;try{l=new DOMException("Aborted","AbortError")}catch{l=new Error("Aborted"),l.name="AbortError"}if(d.aborted)return Promise.reject(l);let p=new Promise((h,m)=>{d.addEventListener("abort",()=>m(l),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([p,n(c,u)])}return n(c,u)},Request:s}}var pi=is({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Am=pi?Xo({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ke=pi?Am.fetch:window.fetch,t0=pi?Am.Request:window.Request,Je=pi?di:window.AbortController,r0=pi?hr:window.AbortSignal;var Rm=_e(ri(),1);var Xe=()=>window.ManagedMediaSource||window.MediaSource,as=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),km=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),wm=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as us,clientChecker as ns}from"@vkontakte/videoplayer-shared";var os=document.createElement("video"),PA='video/mp4; codecs="avc1.42000a,mp4a.40.2"',AA='video/mp4; codecs="hev1.1.6.L93.B0"',$m='video/webm; codecs="vp09.00.10.08"',Lm='video/webm; codecs="av01.0.00M.08"',kA='audio/mp4; codecs="mp4a.40.2"',wA='audio/webm; codecs="opus"',Lt={mms:as(),mse:km(),hls:!!(os.canPlayType?.("application/x-mpegurl")||os.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},de={mp4:!!os.canPlayType?.("video/mp4"),webm:!!os.canPlayType?.("video/webm"),cmaf:!0},pe={h264:!!Xe()?.isTypeSupported?.(PA),h265:!!Xe()?.isTypeSupported?.(AA),vp9:!!Xe()?.isTypeSupported?.($m),av1:!!Xe()?.isTypeSupported?.(Lm),aac:!!Xe()?.isTypeSupported?.(kA),opus:!!Xe()?.isTypeSupported?.(wA)},fr=(pe.h264||pe.h265)&&pe.aac,Mt,RA=async()=>{if(!window.navigator.mediaCapabilities)return;let i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:Lm}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:$m}})]);Mt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{RA()}catch(i){console.error(i)}var mr=Lt.hls&&de.mp4,Mm=()=>Object.keys(pe).filter(i=>pe[i]),Cm=(i,e=!1,t=!1)=>{let r=Lt.mse||Lt.mms&&t;return i.filter(a=>{switch(a){case"DASH_SEP":return r&&de.mp4&&fr;case"DASH_WEBM":return r&&de.webm&&pe.vp9&&pe.opus;case"DASH_WEBM_AV1":return r&&de.webm&&pe.av1&&pe.opus;case"DASH_STREAMS":return r&&(de.mp4&&fr||de.webm&&(pe.vp9||pe.av1)&&(pe.opus||pe.aac));case"DASH_LIVE":return Lt.mse&&de.mp4&&fr;case"DASH_LIVE_CMAF":return r&&de.mp4&&fr&&de.cmaf;case"DASH_ONDEMAND":return r&&de.mp4&&fr;case"HLS":case"HLS_ONDEMAND":return mr||e&&Lt.mse&&de.mp4&&fr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return mr;case"MPEG":return de.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Lt.webrtc&&Lt.ws&&pe.h264&&(de.mp4||de.webm);default:return us(a)}})},ss=i=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(i){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return Mt?Mt[t].smooth?[t,e]:Mt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Mt?Mt[t].powerEfficient?[t,e]:Mt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:us(i)}return[e,t]},Dm=({webmCodec:i,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...ss(i),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],a=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(ns.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...a,"MPEG",...ss(i),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...ss(i),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...ss(i),...a,"HLS","HLS_ONDEMAND"];default:us(e)}return mr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Bm=({androidPreferredFormat:i,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],a=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...a],n=[...a,...r],o,c=ns.isMac&&ns.isSafari;if(ns.isAndroid)switch(i){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:us(i)}else mr&&!c?o=n:c?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"]},Zo=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Vm=i=>{if(i.size!==0){if(i.size===1)return i.values().next().value.split(".").at(0);for(let e of i){let t=(0,Rm.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return i.values().next().value.split(".").at(0)}};import{ErrorCategory as hi}from"@vkontakte/videoplayer-shared";var Om=i=>{if(!i)return{id:"EmptyResponse",category:hi.PARSER,message:"Empty response"};if(i.length<=2&&i.match(/^\d+$/))return{id:`UVError#${i}`,category:hi.NETWORK,message:`UV Error ${i}`};let e=i.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:hi.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(i,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:hi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:hi.PARSER,message:"Response is valid XML, but parser failed"}};var fi=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};import{abortable as Iu,assertNonNullable as Ft,combine as ms,ErrorCategory as pt,filter as bs,filterChanged as Db,fromEvent as Er,interval as Eu,isNonNullable as Bb,map as xu,merge as xr,Subject as Vb,Subscription as Ob,tap as _k,throttle as Nk,clientChecker as Fk,ValueSubject as Z,flattenObject as Hi,getTraceSubscriptionMethod as qk}from"@vkontakte/videoplayer-shared";var Tr=_e(ri(),1);var $A=(i,e={})=>{let r=e.timeout||1,a=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-a-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-a))}})},1)},LA=i=>window.clearTimeout(i),_m=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",eu=_m?$A:window.requestIdleCallback,b0=_m?LA:window.cancelIdleCallback;var kb=_e(Ya(),1);import{assertNever as MA,ErrorCategory as Nm,clientChecker as tu,Subject as Fm}from"@vkontakte/videoplayer-shared";var CA=16,qm=!1;try{qm=tu.isSafari&&!!tu.macVersion&&tu.macVersion<=CA}catch(i){console.error(i)}var ru=class{constructor(e){this.bufferFull$=new Fm;this.error$=new Fm;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:Nm.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let a={operation:"append",data:e,signal:t,callback:r};this.queue.push(a),this.pull()})}async remove(e,t,r){return r&&r.aborted?!1:new Promise(a=>{let s={operation:"remove",from:e,to:t,signal:r,callback:a};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let r;qm&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:a}of this.queue)a(!1);r&&(this.queue=[r]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Nm.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:MA(t)}}},Um=ru;var iu=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};import{abortable as yr,assertNonNullable as Ue,ErrorCategory as Ot,fromEvent as bu,getExponentialDelay as gu,isNonNullable as Su,isNullable as Ae,once as $k,Subject as Lk,Subscription as Mk,ValueSubject as Oi}from"@vkontakte/videoplayer-shared";var _=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let a=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,a),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 a=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,a}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var br=class extends _{};var mi=class extends _{};var bi=class extends _{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let a=this.readString(4);this.compatibleBrands.push(a),r-=4}}};var gi=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Si=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var vi=class extends _{constructor(e,t){super(e,t),this.data=this.content}};var j=class extends _{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Ct=class extends j{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let a=this.readUint32(),s=a>>>31,n=a<<1>>>1,o=this.readUint32();a=this.readUint32();let c=a>>>28,u=a<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:c,SAPDeltaTime:u})}}};var yi=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ti=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ii=class extends j{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 Ei=class extends j{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var xi=class extends j{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Pi=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ai=class extends j{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var ki=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var wi=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ri=class extends j{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var $i=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Li=class extends j{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 Mi=class extends j{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Ci=class extends j{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let a=0;a<this.sampleCount;a++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var BA={ftyp:bi,moov:gi,moof:Si,mdat:vi,sidx:Ct,trak:yi,mdia:Pi,mfhd:Ri,tkhd:Ai,traf:$i,tfhd:Li,tfdt:Mi,trun:Ci,minf:ki,sv3d:Ti,st3d:Ii,prhd:Ei,proj:wi,equi:xi,uuid:mi,unknown:br},Dt=class i{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch{break}return t}createBox(e,t){let r=BA[e];return r?new r(t,new i):new br(t,new i)}};var gr=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var OA=new TextDecoder("ascii"),_A=i=>OA.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",NA=i=>{let e=new Ct(i,new Dt),t=e.earliestPresentationTime/e.timescale*1e3,r=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},FA=(i,e)=>{let r=new Dt().parse(i),a=new gr(r),s=a.findAll("moof"),n=e?a.findAll("uuid"):a.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],c=n[n.length-1],u=o.source.byteOffset,l=c.source.byteOffset-o.source.byteOffset+c.size;return new DataView(i.buffer,u,l)},qA=(i,e)=>{let r=new Dt().parse(i),s=new gr(r).findAll("traf"),n=s[s.length-1].children.find(l=>l.type==="tfhd"),o=s[s.length-1].children.find(l=>l.type==="tfdt"),c=s[s.length-1].children.find(l=>l.type==="trun"),u=0;return c.sampleDuration.length?u=c.sampleDuration.reduce((l,p)=>l+p,0):u=n.defaultSampleDuration*c.sampleCount,(Number(o.baseMediaDecodeTime)+u)/e*1e3},UA=i=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new Dt().parse(i),a=new gr(r);if(a.find("sv3d")){e.is3dVideo=!0;let n=a.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=a.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let c=a.find("equi");c&&(e.projectionData.bounds.top=c.projectionBoundsTop,e.projectionData.bounds.right=c.projectionBoundsRight,e.projectionData.bounds.bottom=c.projectionBoundsBottom,e.projectionData.bounds.left=c.projectionBoundsLeft)}return e},Hm={validateData:_A,parseInit:UA,getIndexRange:()=>{},parseSegments:NA,parseFeedableSegmentChunk:FA,getSegmentEndTime:qA};import{assertNonNullable as su,isNonNullable as Ym,isNullable as jA}from"@vkontakte/videoplayer-shared";import{assertNever as HA}from"@vkontakte/videoplayer-shared";var jm={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"}},Gm=i=>{let e=i.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=Di(i,t),a=r in jm,s=a?jm[r].type:"binary",n=i.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let c=new DataView(i.buffer,i.byteOffset+t+1,o-1),u=n&255>>o,d=Di(c),l=u*2**((o-1)*8)+d,p=t+o,h;return p+l>i.byteLength?h=new DataView(i.buffer,i.byteOffset+p):h=new DataView(i.buffer,i.byteOffset+p,l),{tag:a?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+l,value:h,valueSize:l}},Di=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*2**16+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*2**32+i.getUint32(1);case 6:return i.getUint16(0)*2**32+i.getUint32(2);case 7:{let t=i.getUint8(0)*281474976710656+i.getUint16(1)*4294967296+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},De=(i,e)=>{switch(e){case"int":return i.getInt8(0);case"uint":return Di(i);case"float":return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case"string":return new TextDecoder("ascii").decode(i);case"utf8":return new TextDecoder("utf-8").decode(i);case"date":return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case"master":return i;case"binary":return i;default:HA(e)}},Bt=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=Gm(r);if(!e(a))return;a.type==="master"&&Bt(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},Wm=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=Gm(i);return Bt(a.value,({tag:s,type:n,value:o})=>(s===17143?e=De(o,n):s===17026?t=De(o,n):s===17029&&(r=De(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Qm=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],GA=[231,22612,22743,167,171,163,160,175],WA=i=>{let e,t,r,a,s=!1,n=!1,o=!1,c,u,d=!1,l=0;return Bt(i,({tag:p,type:h,value:m,valueSize:b})=>{if(p===21419){let g=De(m,h);u=Di(g)}else p!==21420&&(u=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=De(m,h):p===17545?a=De(m,h):p===21420&&u===475249515?c=De(m,h):p===374648427?Bt(m,({tag:g,type:v,value:A})=>g===30321?(d=De(A,v)===1,!1):!0):s&&n&&Qm.includes(p)&&(o=!0),!o}),su(e,"Failed to parse webm Segment start"),su(t,"Failed to parse webm Segment end"),su(a,"Failed to parse webm Segment duration"),r=r??1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(a/1e9*r*1e3),cuesSeekPosition:c,is3dVideo:d,stereoMode:l,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},YA=i=>{if(jA(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},QA=(i,e)=>{let t=!1,r=!1,a=o=>Ym(o.time)&&Ym(o.position),s=[],n;return Bt(i,({tag:o,type:c,value:u})=>{switch(o){case 475249515:t=!0;break;case 187:n&&a(n)&&s.push(n),n={};break;case 179:n&&(n.time=De(u,c));break;case 183:break;case 241:n&&(n.position=De(u,c));break;default:t&&Qm.includes(o)&&(r=!0)}return!(t&&r)}),n&&a(n)&&s.push(n),s.map((o,c)=>{let{time:u,position:d}=o,l=s[c+1];return{status:"none",time:{from:u,to:l?l.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:l?e.segmentStart+l.position-1:e.segmentEnd-1}}})},zA=i=>{let e=0,t=!1;try{Bt(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):GA.includes(r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||=[163,160,175].includes(r.tag)),!0):!1)}catch{}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},zm={validateData:Wm,parseInit:WA,getIndexRange:YA,parseSegments:QA,parseFeedableSegmentChunk:zA};var Sr=i=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(i);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return zm;case"mp4":return Hm}}throw new ReferenceError(`Unsupported mime type ${i}`)};var pu=_e(gb(),1);var du=i=>{let e=i.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[a,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[a,s,n]=r;return!!(a&&parseInt(a,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let a=r[0];if(!a||a.length!==6)return!1;let[s,n]=a.toUpperCase(),o=s+n;return["6E","7A","F4"].includes(o)}}return!1};import{isNonNullable as vb,isNullable as yb}from"@vkontakte/videoplayer-shared";var Sb=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var Tb=i=>{if(!i.startsWith("P"))return;let e=(n,o)=>{let c=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(c)?0:c)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),a=r?.[1]==="-"?-1:1,s={days:e(r?.[5],a),hours:e(r?.[6],a),minutes:e(r?.[7],a),seconds:e(r?.[8],a)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},Vt=(i,e)=>{let t=i;t=(0,pu.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[a,s]of Object.entries(r)){let n=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=(0,pu.default)(t,n,(o,c)=>yb(s)?o:yb(c)?s:s.padStart(parseInt(c,10),"0"))}return t},Eb=(i,e)=>{let r=new DOMParser().parseFromString(i,"application/xml"),a={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=s.querySelector("BaseURL")?.textContent?.trim()??"",c=n.children,u=s.getAttribute("type")==="dynamic",d=s.getAttribute("availabilityStartTime"),l=d?new Date(d).getTime():void 0,p,h=s.getAttribute("mediaPresentationDuration"),m=n.getAttribute("duration"),g=s.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=Tb(h);else if(m){let S=Tb(m);vb(S)&&(p=S)}else g&&(p=parseInt(g,10));let v=0,A=s.getAttribute("profiles")?.split(",")??[];for(let S of c){let T=S.getAttribute("id")??"id"+(v++).toString(10),E=S.getAttribute("mimeType")??"",D=S.getAttribute("codecs")??"",O=S.getAttribute("contentType")??E?.split("/")[0],N=S.getAttribute("profiles")?.split(",")??[],k=S.getAttribute("lang")??void 0,w=S.querySelector("Label")?.textContent?.trim()??void 0,$=S.querySelectorAll("Representation"),q=S.querySelector("SegmentTemplate"),ke=S.querySelector("Role")?.getAttribute("value")??void 0,te=O,x={id:T,language:k,isDefault:ke==="main",label:w,codecs:D,hdr:te==="video"&&du(D),mime:E,representations:[]};for(let R of $){let G=R.getAttribute("lang")??void 0,z=R.getAttribute("label")??void 0,he=R.querySelector("BaseURL")?.textContent?.trim()??"",Ve=new URL(he||o,e).toString(),Ut=R.getAttribute("mimeType")??E,gt=R.getAttribute("codecs")??D??"",B;if(O==="text"){let W=R.getAttribute("id")||"",re=W.includes("_auto");B={id:W,isAuto:re,kind:"text",url:Ve}}else{let W=R.getAttribute("contentType")??Ut?.split("/")[0]??O,re=S.getAttribute("profiles")?.split(",")??[],we=parseInt(R.getAttribute("width")??"",10),tt=parseInt(R.getAttribute("height")??"",10),Ht=parseInt(R.getAttribute("bandwidth")??"",10)/1e3,rt=R.getAttribute("frameRate")??"",jt=R.getAttribute("quality")??void 0,Ar=rt?Sb(rt):void 0,sa=R.getAttribute("id")??"id"+(v++).toString(10),Dg=W==="video"?`${tt}p`:W==="audio"?`${Ht}Kbps`:gt,Bg=`${sa}@${Dg}`,Vg=[...A,...N,...re],Vs,Og=R.querySelector("SegmentBase"),St=R.querySelector("SegmentTemplate")??q;if(Og){let vt=R.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[yt,_s]=vt.split("-").map(Gt=>parseInt(Gt,10)),it={from:yt,to:_s},kr=R.querySelector("SegmentBase")?.getAttribute("indexRange"),[Ns,na]=kr?kr.split("-").map(Gt=>parseInt(Gt,10)):[],wr=kr?{from:Ns,to:na}:void 0;Vs={type:"byteRange",url:Ve,initRange:it,indexRange:wr}}else if(St){let vt={representationId:R.getAttribute("id")??void 0,bandwidth:R.getAttribute("bandwidth")??void 0},yt=parseInt(St.getAttribute("timescale")??"",10),_s=St.getAttribute("initialization")??"",it=St.getAttribute("media"),kr=parseInt(St.getAttribute("startNumber")??"",10)??1,Ns=Vt(_s,vt);if(!it)throw new ReferenceError("No media attribute in SegmentTemplate");let na=St.querySelectorAll("SegmentTimeline S")??[],wr=[],Gt=0,Fs="",qs=0;if(na.length){let oa=kr,Re=0;for(let Wt of na){let Oe=parseInt(Wt.getAttribute("d")??"",10),Tt=parseInt(Wt.getAttribute("r")??"",10)||0,ua=parseInt(Wt.getAttribute("t")??"",10);Re=Number.isFinite(ua)?ua:Re;let Us=Oe/yt*1e3,Ng=Re/yt*1e3;for(let ca=0;ca<Tt+1;ca++){let Fg=Vt(it,{...vt,segmentNumber:oa.toString(10),segmentTime:(Re+ca*Oe).toString(10)}),Uu=(Ng??0)+ca*Us,qg=Uu+Us;oa++,wr.push({time:{from:Uu,to:qg},url:Fg})}Re+=(Tt+1)*Oe,Gt+=(Tt+1)*Us}qs=Re/yt*1e3,Fs=Vt(it,{...vt,segmentNumber:oa.toString(10),segmentTime:Re.toString(10)})}else if(vb(p)){let Re=parseInt(St.getAttribute("duration")??"",10)/yt*1e3,Wt=Math.ceil(p/Re),Oe=0;for(let Tt=1;Tt<Wt;Tt++){let ua=Vt(it,{...vt,segmentNumber:Tt.toString(10),segmentTime:Oe.toString(10)});wr.push({time:{from:Oe,to:Oe+Re},url:ua}),Oe+=Re}qs=Oe,Fs=Vt(it,{...vt,segmentNumber:Wt.toString(10),segmentTime:Oe.toString(10)})}let _g={time:{from:qs,to:1/0},url:Fs};Vs={type:"template",baseUrl:Ve,segmentTemplateUrl:it,initUrl:Ns,totalSegmentsDurationMs:Gt,segments:wr,nextSegmentBeyondManifest:_g,timescale:yt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!W||!Ut)continue;let Os={video:"video",audio:"audio",text:"text"}[W];if(!Os)continue;te||=Os,B={id:Bg,kind:Os,segmentReference:Vs,profiles:Vg,duration:p,bitrate:Ht,mime:Ut,codecs:gt,width:we,height:tt,fps:Ar,quality:jt}}x.language||=G,x.label||=z,x.mime||=Ut,x.codecs||=gt,x.hdr||=te==="video"&&du(gt),x.representations.push(B)}te&&a[te].push(x)}return{dynamic:u,liveAvailabilityStartTime:l,duration:p,streams:a}};var Bi=_e(ri(),1);import{videoSizeToQuality as Rk}from"@vkontakte/videoplayer-shared";var xb=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s})=>{let n=(s?ct(s):void 0)??Rk({width:e,height:t});return n&&{id:i,quality:n,bitrate:r,size:{width:e,height:t},fps:a}},Pb=({id:i,bitrate:e})=>({id:i,bitrate:e}),cs=(i,e,t)=>{let r=e.indexOf(i);return(0,Bi.default)(t,Math.round(t.length*r/e.length))??(0,Bi.default)(t,-1)},Ab=({language:i,label:e},{id:t,url:r,isAuto:a})=>({id:t,url:r,isAuto:a,type:"internal",language:i,label:e}),fu=({id:i,language:e,label:t,codecs:r,isDefault:a})=>({id:i,language:e,label:t,codec:(0,Bi.default)(r.split("."),0),isDefault:a}),mu=({id:i,language:e,label:t,hdr:r,codecs:a})=>({id:i,language:e,hdr:r,label:t,codec:(0,Bi.default)(a.split("."),0)}),ls=i=>"url"in i,Ze=i=>i.type==="template",Vi=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var _i=class{constructor(e,t,r,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:c=!1,manifest:u}){this.currentSegmentLength$=new Oi(0);this.onLastSegment$=new Oi(!1);this.fullyBuffered$=new Oi(!1);this.playingRepresentation$=new Oi(void 0);this.playingRepresentationInit$=new Oi(void 0);this.error$=new Lk;this.gaps=[];this.subscription=new Mk;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=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.loadByteRangeSegmentsTimeoutId=0;this.startWith=yr(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Ue(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Um(this.sourceBuffer),this.subscription.add(bu(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,c=this.mediaSource.readyState;c!=="open"&&(o={id:`SegmentEjection_source_${c}`,category:Ot.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:Ot.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add(bu(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Ot.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 c=Math.min(this.bufferLimit,iu(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=c,this.tuning.useNewPruneBufferStrategy){let u=ze(this.sourceBuffer.buffered,o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,n*2,u<d)}else this.pruneBufferOld(o,n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),a=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Ue(r,"No init buffer for starting representation"),Ue(a,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(a,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=yr(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);Ue(r,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if(Ae(s)||Ae(a)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),Ue(a,"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();Su(n)&&(this.isLive||(a.forEach(o=>o.status="none"),this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=yr(this.destroyAbortController.signal,async function*(e){let t=e?.flatMap(c=>c.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let u=t.find(p=>p.id===c);u&&this.representations.set(c,u);let d=this.representations.get(c);if(!d||!Ze(d.segmentReference))return;let l=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,l)}let r=this.switchingToRepresentationId??this.downloadingRepresentationId,a=this.representations.get(r);Ue(a);let s=this.segments.get(r);Ue(s,"No segments for starting representation");let n=this.initData.get(r);if(Ue(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,a),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=a,this.tuning=s,this.compatibilityMode=c,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!u?.dynamic,this.resetAccumulateBufferAfterStall(),this.startAccumulateBuffer(),this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}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()){if(Ae(e)||Ae(this.downloadingRepresentationId)||Ae(this.playingRepresentationId)||Ae(this.sourceBuffer)||!Ae(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(Ue(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let a=r.find(u=>e>=u.time.from&&e<u.time.to);this.currentSegmentLength$.next((a?.time.to??0)-(a?.time.from??0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=ze(this.sourceBuffer.buffered,e),l=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=a.time.to-e+100&&(s=l)}if(isFinite(this.bufferLimit)&&iu(this.sourceBuffer.buffered)>=this.bufferLimit){let u=ze(this.sourceBuffer.buffered,e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<d);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(o.includes(a))u="high";else{let d=(0,Tr.default)(o,0);d&&d.time.from-a.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(o,t,u)}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!o.length&&ze(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let c=(0,Tr.default)(r,-1);c&&c.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===c))}searchGaps(e,t){this.gaps=[];let r=0,a=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+a}),r=s.time.to;Su(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,a=[],s=0,n=t.length-1;do a.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[a[0]]:a}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind].flatMap(a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){let t=e?.streams[this.kind].flatMap(r=>r.representations)??[];for(let r of t){if(!r||!Ze(r.segmentReference))return;let a=r.segmentReference.segments.map(c=>({...c,status:"none",size:void 0})),s=this.segments.get(r.id)??[],n=(0,Tr.default)(s,-1)?.time.to??0,o=a?.findIndex(c=>Math.floor(n)>=Math.floor(c.time.from)&&Math.floor(n)<=Math.floor(c.time.to));if(o===-1){this.liveUpdateSegmentIndex=0;let c=this.getActualLiveStartingSegments(r.segmentReference);this.segments.set(r.id,c)}else{let c=a.slice(o+1);this.segments.set(r.id,[...s,...c])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Ue(e);let t=this.segments.get(e);if(t?.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}startAccumulateBuffer(){this.bufferAccumulation.enabled=!0}resetAccumulateBufferAfterStall(){this.bufferAccumulation={enabled:!1,targetBufferSizeMs:this.tuning.accumulationBufferStallSizeMs,accumulatedBufferSizeMs:0,accumulated:[]}}updateLowLatencyLiveIfNeeded(e){for(let t of this.representations.values()){let r=t.segmentReference;if(!Ze(r))return;let a=this.segments.get(t.id)??[],s=a.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(s&&!isFinite(s.time.to)&&(s.time.to=e.time.to),!!!a.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),c=Vt(r.segmentTemplateUrl,{segmentTime:o});a.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);return r?r.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&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(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(a=>t>=a.time.from&&t<a.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let a=e.findIndex(({status:l,time:{from:p,to:h}},m)=>{let b=p<=r&&h>=r,g=p>r||b||m===0&&r===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),A=this.preloadOnly&&p<=r+v||h<=r+v;return(l==="none"||l==="partially_ejected"&&g&&A&&this.sourceBuffer&&!fi(this.sourceBuffer.buffered,r))&&g&&A});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let s=e,n=0,o=0,c=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let l=a;l<s.length&&(n<=u||o<=d);l++){let p=s[l];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")c.push(p);else break}return c}async loadSegments(e,t,r="auto"){t.segmentReference.type==="template"?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){e.status="downloading";let a={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(a);let{range:s,url:n,signal:o,onProgress:c,onProgressTasks:u}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await yr(o,async function*(){let d=gu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:c,priority:r,isLowLatency:this.isActiveLowLatency()});if(!d)return;let l=new DataView(d);if(!isFinite(a.segment.time.to)){let p=t.segmentReference.timescale,h=Sr(t.mime);a.segment.time.to=h.getSegmentEndTime(l,p)}c&&a.feedingBytes&&u?await Promise.all(u):await this.sourceBufferTaskQueue.append(l,o),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Vi(d)||this.failedDownloads++}}async loadByteRangeSegments(e,t,r="auto"){if(!e.length)return;for(let c of e)c.status="downloading",this.activeSegments.add({segment:c,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:a,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await yr(n,async function*(){let c=gu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(u,c),bu(window,"online").pipe($k()).subscribe(()=>{u(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:a,onProgress:o,signal:n,priority:r}),this.failedDownloads=0}catch(c){this.abortActiveSegments(e),Vi(c)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(Ze(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,Tr.default)(e,0).byte.from,to:(0,Tr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:a,signal:s,onProgress:(o,c)=>{if(!s.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:a?a.from:0,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:Ot.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ze(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let a=r.toString(),{signal:s}=this.downloadAbortController,n=[],c=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(u,d)=>{if(!s.aborted)try{let l=this.onSomeTemplateDataLoaded({dataView:u,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(l)}catch(l){this.error$.next({id:"SegmentFeeding",category:Ot.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}:void 0;return{url:a,signal:s,onProgress:c,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:a,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:c}=o;if(o.representationId===t){if(s.aborted){a();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let u=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=Sr(n.mime).parseFeedableSegmentChunk(u,this.isLive);d?.byteLength&&(c.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){let o={dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let c=o.segmentReference.type,u=e.byteLength;for(let d of this.activeSegments){let{segment:l}=d,p=c==="byteRange",h=p?l.byte.to-l.byte.from+1:u;if(d.representationId!==t||!(!p||l.byte.from>=r&&l.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let b=p?l.byte.from-r:0,g=p?l.byte.to-r:e.byteLength,v=b<a,A=g<=a;if(l.status==="downloading"&&v&&A){l.status="downloaded";let y=new DataView(e.buffer,e.byteOffset+b,h),S=this.getCurrentPosition();Su(S)&&(this.bufferAccumulation.accumulatedBufferSizeMs=l.time.to-S,this.bufferAccumulation.accumulated.push({segmentView:y,segmentProgress:d}),this.activeSegments.delete(d));let T=({segmentView:E,segmentProgress:D})=>this.sourceBufferTaskQueue.append(E,s).then(O=>O&&!s.aborted?this.onSegmentFullyAppended(D,t):n());this.bufferAccumulation.enabled&&this.bufferAccumulation.targetBufferSizeMs<this.bufferAccumulation.accumulatedBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(T),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||Ae(S))&&(T({segmentView:y,segmentProgress:d}),this.resetAccumulateBufferAfterStall())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&v&&!A&&(d.loadedBytes=Math.min(h,a-b),d.loadedBytes>d.feedingBytes)){let y=new DataView(e.buffer,e.byteOffset+b+d.feedingBytes,d.loadedBytes-d.feedingBytes),S=d.loadedBytes===h?y:Sr(o.mime).parseFeedableSegmentChunk(y);S?.byteLength&&(l.status="partially_fed",d.feedingBytes+=S.byteLength,this.sourceBufferTaskQueue.append(S,s).then(T=>{if(s.aborted)n();else if(T)d.fedBytes+=S.byteLength,d.fedBytes===h&&this.onSegmentFullyAppended(d,t);else{if(d.feedingBytes<h)return;n()}}))}}}async onSomeByteRangesDataLoadedNew({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let c of this.activeSegments){let{segment:u}=c;if(c.representationId!==t)continue;if(s.aborted){n();continue}let d=u.byte.from-r,l=u.byte.to-r,p=l-d+1,h=d<a,m=l<=a;if(h){if(u.status==="downloading"&&m){u.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+d,p);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(c,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(u.status==="downloading"||u.status==="partially_fed")&&(c.loadedBytes=Math.min(p,a-d),c.loadedBytes>c.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+d+c.feedingBytes,c.loadedBytes-c.feedingBytes),g=c.loadedBytes===p?b:Sr(o.mime).parseFeedableSegmentChunk(b);g?.byteLength&&(u.status="partially_fed",c.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(c.fedBytes+=g.byteLength,c.fedBytes===p&&this.onSegmentFullyAppended(c,t)):n())}}}}onSegmentFullyAppended(e,t){this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",ls(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let a of this.segments.get(r.id)??[])a.status==="fed"&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){(this.tuning.useDashAbortPartiallyFedSegment?e.status==="partially_fed"||e.status==="partially_ejected":e.status==="partially_ejected")?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status="none"),e.status="partially_ejected"):e.status="none";for(let r of this.activeSegments.values())if(r.segment===e){this.activeSegments.delete(r);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[a,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=eu(()=>(0,kb.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",r=!1){let a=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?yr(this.destroyAbortController.signal,async function*(){let o=gu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Sr(e.mime),a)).then(async o=>{if(!o)return;let{init:c,dataView:u,segments:d}=o,l=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,l);let p=d;this.isLive&&Ze(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),c&&this.parsedInitData.set(e.id,c)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:Ot.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,r=!1){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,r):this.pruneBufferOld(e,t,r)}async pruneBufferNew(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Ae(e)||this.sourceBuffer.updating)return!1;let a=[],s=0,n=c=>{c.sort((d,l)=>d.from-l.from);let u=[c[0]];for(let d=1;d<c.length;d++){let{from:l,to:p}=c[d],h=u[u.length-1];h.to>=l?h.to=Math.max(h.to,p):u.push(c[d])}return u},o=c=>{if(s>=t)return a;a.push(c.time),a=n(a);let u=ls(c)?c.size??0:c.byte.to-c.byte.from;s+=u};for(let c of this.segments.values())for(let u of c){let d=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,l=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||l)&&u.status==="fed"&&o(u)}for(let c=0;c<this.sourceBuffer.buffered.length;c++){let u=this.sourceBuffer.buffered.start(c)*1e3,d=this.sourceBuffer.buffered.end(c)*1e3,l=0;for(let p of this.segments.values())for(let h of p)h.status==="none"&&Math.round(h.time.from)<=Math.round(u)&&Math.round(h.time.to)>=Math.round(d)&&l++;if(l===this.segments.size){let p={time:{from:u,to:d},url:"",status:"none"};o(p)}}if(a.length&&r){let c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let d of u)d.time.from>=e+c&&d.status==="fed"&&o(d)}return a.length?(await Promise.all(a.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,d)=>u||d,!1):!1}async pruneBufferOld(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Ae(e)||this.sourceBuffer.updating)return!1;let a=0,s=1/0,n=-1/0,o=!1,c=u=>{s=Math.min(s,u.time.from),n=Math.max(n,u.time.to);let d=ls(u)?u.size??0:u.byte.to-u.byte.from;a+=d};for(let u of this.segments.values())for(let d of u){if(d.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;d.status==="fed"&&c(d)}if(o=isFinite(s)&&isFinite(n),!o){a=0,s=1/0,n=-1/0;for(let u of this.segments.values())for(let d of u){if(d.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||a>t)break;d.status==="fed"&&c(d)}}if(o=isFinite(s)&&isFinite(n),!o)for(let u=0;u<this.sourceBuffer.buffered.length;u++){let d=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3;for(let p of this.segments.values())for(let h of p)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(d)&&Math.round(h.time.to)>=Math.round(l)){s=d,n=l;break}}if(o=isFinite(s)&&isFinite(n),!o&&r){a=0,s=1/0,n=-1/0;let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let d of this.segments.values())for(let l of d)l.time.from>e+u&&l.status==="fed"&&c(l)}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)}}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let a={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){a=void 0;break}o>r.time.from&&o<r.time.to&&(a.from=o),n<r.time.to&&n>r.time.from&&(a.to=n)}}a&&a.to-a.from>1&&!this.gaps.some(s=>a&&s.from===a.from&&s.to===a.to)&&this.gaps.push(a)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=eu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Ot.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(Ae(this.sourceBuffer)||Ae(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let a=Math.round(this.sourceBuffer.buffered.start(r)*1e3),s=Math.round(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:a,to:s})}let t=1;for(let r of this.segments.values())for(let a of r){let{status:s}=a;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(a.time.from),o=Math.ceil(a.time.to),c=e.some(d=>d.from-t<=n&&d.to+t>=o),u=e.filter(d=>n>=d.from-t&&n<=d.to+t||o>=d.from-t&&o<=d.to+t);c||(u.length===1?a.status="partially_ejected":this.gaps.some(d=>d.from===a.time.from||d.to===a.time.to)?a.status="partially_ejected":a.status="none")}}};var Ni=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var wb=i=>{let e=i.get("X-Delivery-Type"),t=i.get("X-Reused"),r=e===null?"http1":e??void 0,a=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:r,reused:a}};import{abortable as Fi,assertNever as Rb,fromEvent as $b,merge as Ck,now as qi,Subscription as Dk,ValueSubject as vu,flattenObject as Ir}from"@vkontakte/videoplayer-shared";var ds=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:a=!1}){this.lastConnectionType$=new vu(void 0);this.lastConnectionReused$=new vu(void 0);this.lastRequestFirstBytes$=new vu(void 0);this.abortAllController=new Je;this.subscription=new Dk;this.fetchManifest=Fi(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Ni(r));let a=yield Ke(r,{signal:this.abortAllController.signal}).catch(Ui);return a?(t.log("success",Ir({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(a.headers),a.text()):(t.error("error",Ir({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Fi(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:a,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:c=!1}={}){let u=e,d=new Headers,l=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let w=new URL(u,location.href);w.searchParams.append("bytes",`${r.from}-${r.to}`),u=w.toString();break}default:Rb(t)}this.requestQuic&&(u=Ni(u));let p=this.abortAllController.signal,h;if(n){let w=new Je;if(h=Ck($b(this.abortAllController.signal,"abort"),$b(n,"abort")).subscribe(()=>{try{w.abort()}catch($){Ui($)}}),this.abortAllController.signal.aborted||n.aborted)try{w.abort()}catch($){Ui($)}p=w.signal}let m=qi();l.log("startRequest",Ir({url:u,priority:s,rangeMethod:t,range:r,isLowLatency:c,requestStartedAt:m}));let b=yield Ke(u,{priority:s,headers:d,signal:p}).catch(Ui),g=qi();if(!b)return l.error("error",{message:"No response in request"}),l.end(),h?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(g-m),!b.ok||!b.body){h?.unsubscribe();let w=`Fetch error ${b.status}: ${b.statusText}`;return l.error("error",{message:w}),l.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!a&&!o){h?.unsubscribe();let w=qi(),$={requestStartedAt:m,requestEndedAt:w,duration:w-m};return l.log("endRequest",Ir($)),l.end(),b.arrayBuffer()}let[v,A]=b.body.tee(),y=v.getReader();o&&this.throughputEstimator?.trackStream(A,c);let S=0,T=new Uint8Array(0),E=!1,D=w=>{h?.unsubscribe(),E=!0,Ui(w)},O=Fi(p,async function*({done:w,value:$}){if(S===0&&this.lastRequestFirstBytes$.next(qi()-m),p.aborted){h?.unsubscribe();return}if(!w&&$){let q=new Uint8Array(T.length+$.length);q.set(T),q.set($,T.length),T=q,S+=$.byteLength,a?.(new DataView(T.buffer),S),yield y?.read().then(O,D)}}.bind(this));yield y?.read().then(O,D),h?.unsubscribe();let N=qi(),k={failed:E,requestStartedAt:m,requestEndedAt:N,duration:N-m};return E?(l.error("endRequest",Ir(k)),l.end(),null):(l.log("endRequest",Ir(k)),l.end(),T.buffer)}.bind(this));this.fetchByteRangeRepresentation=Fi(this.abortAllController.signal,async function*(e,t,r){if(e.type!=="byteRange")return null;let{from:a,to:s}=e.initRange,n=a,o=s,c=!1,u,d;e.indexRange&&(u=e.indexRange.from,d=e.indexRange.to,c=s+1===u,c&&(n=Math.min(u,a),o=Math.max(d,s))),n=Math.min(n,0);let l=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!l)return null;let p=new DataView(l,a-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let b;if(c)b=new DataView(l,m.from-n,m.to-m.from+1);else{let v=yield this.fetch(e.url,{range:m,priority:r,measureThroughput:!1});if(!v)return null;b=new DataView(v)}let g=t.parseSegments(b,h,m);return{init:h,dataView:new DataView(l),segments:g}}.bind(this));this.fetchTemplateRepresentation=Fi(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),a=yield this.fetch(r,{priority:t,measureThroughput:!1});return a?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(a)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=a,this.tracer=r.createComponentTracer("Fetcher")}onHeadersReceived(e){let{type:t,reused:r}=wb(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){let{type:a}=e;switch(a){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,r)??null;case"template":return await this.fetchTemplateRepresentation(e,r)??null;default:Rb(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Ui=i=>{if(!Vi(i))throw i};var _t=(i,e,t)=>t*e+(1-t)*i,yu=(i,e)=>i.reduce((t,r)=>t+r,0)/e,Lb=(i,e,t,r)=>{let a=0,s=t,n=yu(i,e),o=e<r?e:r;for(let c=0;c<o;c++)i[s]>n?a++:a--,s=(i.length+s-1)%i.length;return Math.abs(a)===o};import{isNullable as Bk,ValueSubject as Mb}from"@vkontakte/videoplayer-shared";var dt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Mb(e.initial),this.debounced$=new Mb(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new X(`raw_${t}`),this.smoothedSeries$=new X(`smoothed_${t}`),this.reportedSeries$=new X(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,r++);this.takenMeasures=r,t/=r;let a=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*a,n=this.smoothed-this.params.deviationFactor*a;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(Bk(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 ps=class extends dt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=_t(this.slow,e,this.params.emaAlphaSlow),this.fast=_t(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var hs=class extends dt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=yu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=_t(this.emaSmoothed,e,this.params.emaAlpha);let r=Lb(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var fs=class extends dt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?_t(this.smoothed,t,this.params.emaAlpha):t}};var Nt=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new ps({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new hs({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new fs({initial:e,label:"liveEdgeDelay",...t})}};var Tu=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};var _b=["timeupdate","progress","play","seeked","stalled","waiting"];var gs=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Ob;this.representationSubscription=new Ob;this.state$=new L("none");this.currentVideoRepresentation$=new Z(void 0);this.currentVideoRepresentationInit$=new Z(void 0);this.currentAudioRepresentation$=new Z(void 0);this.currentVideoSegmentLength$=new Z(0);this.currentAudioSegmentLength$=new Z(0);this.error$=new Vb;this.lastConnectionType$=new Z(void 0);this.lastConnectionReused$=new Z(void 0);this.lastRequestFirstBytes$=new Z(void 0);this.isLive$=new Z(!1);this.liveDuration$=new Z(0);this.liveAvailabilityStartTime$=new Z(void 0);this.bufferLength$=new Z(0);this.liveLoadBufferLength$=new Z(0);this.livePositionFromPlayer$=new Z(0);this.timeInWaiting=0;this.isActiveLowLatency$=new Z(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new Vb;this.gapWatchdogActive=!1;this.destroyController=new Je;this.initManifest=Iu(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=K(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:pt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Iu(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:pt.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t;try{t=Eb(e??"",this.manifestUrlString)}catch(n){let o=Om(e)??{id:"ManifestParsing",category:pt.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(o)}if(!t)return null;let r=(n,o,c)=>!!(this.element?.canPlayType?.(o)&&Xe()?.isTypeSupported?.(`${o}; codecs="${c}"`)||n==="text");t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let a={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let c=t.streams[n].filter(({mime:l,codecs:p})=>r(n,l,p)),u=new Set(c.map(({codecs:l})=>l)),d=Vm(u);if(d&&(a[n]=c.filter(({codecs:l})=>l.startsWith(d))),n==="video"){let l=this.tuning.preferHDR,p=a.video.some(m=>m.hdr),h=a.video.some(m=>!m.hdr);Fk.isHDR&&l&&p?a.video=a.video.filter(m=>m.hdr):h&&(a.video=a.video.filter(m=>!m.hdr))}}let s={...t,streams:a};return this.tracer.log("updateManifestEnd",Hi(s)),s}.bind(this));this.initRepresentations=Iu(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initRepresentationsStart",Hi({initialVideo:e,initialAudio:t,sourceHls:r})),Ft(this.manifest),Ft(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=l=>{this.representationSubscription.add(Er(l,"error").pipe(bs(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:pt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=this.tuning.useManagedMediaSource?wm():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&as())if(r){let l=document.createElement("source");a(l),l.type="application/x-mpegurl",l.src=r.url,this.element.appendChild(l)}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((l,p)=>[...l,...p.representations],[]);if(this.videoBufferManager=new _i("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Bb(t)){let l=this.manifest.streams.audio.reduce((p,h)=>[...p,...h.representations],[]);this.audioBufferManager=new _i("audio",this.source,l,n),this.bufferManagers.push(this.audioBufferManager)}if(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(Eu(1e3).subscribe(l=>{if(this.element?.paused){let p=Co(this.manifestUrlString,2);this.manifestUrlString=K(this.manifestUrlString,p+1e3,2)}})),this.representationSubscription.add(xr(..._b.filter(l=>l!=="waiting").map(l=>Er(this.element,l))).pipe(xu(l=>this.element?ze(this.element.buffered,this.element.currentTime*1e3):0),Db(),bs(l=>!!l),_k(l=>{this.stallWatchdogSubscription?.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Db()).subscribe(p=>Tu(this.element,1))),this.representationSubscription.add(ms({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(bs(({bufferLength:p,isActiveLowLatency:h})=>h&&!!p)).subscribe(({bufferLength:p})=>this.liveEstimatedDelay.next(p))),this.representationSubscription.add(ms({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:p,isActiveLowLatency:h})=>{if(!h)return;let m=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,b=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,g=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,v=p-m,A=1;Math.abs(v)>b&&(A=1+Math.sign(v)*g),Tu(this.element,A)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let h=0;if(p){let m=(this.element?.currentTime??0)*1e3;h=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??m))-m}this.liveLoadBufferLength$.getValue()!==h&&this.liveLoadBufferLength$.next(h)}));let l=0;this.representationSubscription.add(ms({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Nk(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:h})=>{if(Ft(this.element),this.isUpdatingLive)return;let m=this.element.playbackRate,b=Co(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*m),A=this.tuning.dashCmafLive.normalizedActualBufferOffset*m,y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*m,S=isFinite(p)?p:h,T=this.isActiveLowLatency$.getValue(),E=g<=this.tuning.live.activeLiveDelay&&b===0;this.isActiveLowLatency$.next(T&&E);let D="none";if(T?D="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&E?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(O=>O.proceedLowLatencyLive()),D="active_low_latency"):b!==0&&S<v?D="live_forward_buffering":S<v+y&&(D="live_with_target_offset"),isFinite(p)&&(l=p>l?p:l),D==="live_forward_buffering"||D==="live_with_target_offset"){let O=l-(v+A),N=this.normolizeLiveOffset(Math.trunc(b+O/m)),k=Math.abs(N-b),w;!p||k<=this.tuning.dashCmafLive.offsetCalculationError?w=b:N>0&&k>this.tuning.dashCmafLive.offsetCalculationError?w=N:w=0,this.manifestUrlString=K(this.manifestUrlString,w,2)}D!=="none"&&D!=="active_low_latency"&&(l=0,this.updateLive())}))}let c=xr(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe(xu(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),u=xr(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe(xu(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue())));this.representationSubscription.add(xr(this.forceEnded$,ms({allBuffersFull:c,someBufferEnded:u}).pipe(bs(({allBuffersFull:l,someBufferEnded:p})=>l&&p))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(l=>!l.updating))try{this.source?.endOfStream()}catch(l){this.error$.next({id:"EndOfStream",category:pt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:l})}})),this.representationSubscription.add(xr(...this.bufferManagers.map(l=>l.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.source.readyState!=="open"&&(yield new Promise(l=>this.source?.addEventListener("sourceopen",l)));let d=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(l=>l.representations).flatMap(l=>{let p=[];return l.duration&&p.push(l.duration),Ze(l.segmentReference)&&l.segmentReference.totalSegmentsDurationMs&&p.push(l.segmentReference.totalSegmentsDurationMs),p})];this.source.duration=Math.max(...d)/1e3,this.audioBufferManager&&Bb(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Eu(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:pt.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new ds({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=Nt.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator}),this.initTracerSubscription()}async seekLive(e){Ft(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=K(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest?.streams.video),await this.audioBufferManager?.seekLive(this.manifest?.streams.audio))}initBuffer(){Ft(this.element),this.state$.setState("running"),this.subscription.add(xr(..._b.map(e=>Er(this.element,e)),Er(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:pt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Er(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Er(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&fi(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element)return;this.timeInWaiting+=1e3;let t={timeInWaiting:this.timeInWaiting};if(this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset),t={...t,liveLastSeekOffset:this.liveLastSeekOffset};else{let r=this.element.currentTime*1e3;this.videoBufferManager?.maintain(r),this.audioBufferManager?.maintain(r),t={...t,position:r}}this.tracer.log("stallIntervalCallback",Hi(t))};this.videoBufferManager?.startAccumulateBuffer(),this.audioBufferManager?.startAccumulateBuffer(),this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=Eu(1e3).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:pt.FATAL,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,r)}seek(e,t){Ft(this.element),Ft(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),fi(this.element.buffered,r)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.startAccumulateBuffer(),this.videoBufferManager.maintain(r),this.audioBufferManager?.startAccumulateBuffer(),this.audioBufferManager?.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",Hi({requestedPosition:e,forcePrecise:t,position:r}))}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>e.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=qk(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,a=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?a.push(1/0):a.push(o.to));if(a.length){let n=Math.max(...a)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t={...t,gapEnds:a,jumpTo:n,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Hi(t)))}}};var Ss=class{constructor(e,t){this.fov=e,this.orientation=t}};var vs=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let a=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:a,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=r??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let a=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*a,this.fadeStartSpeed.y*a,this.fadeStartSpeed.z*a),a>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Nb=`attribute vec2 a_vertex;
|
|
38
59
|
attribute vec2 a_texel;
|
|
39
60
|
|
|
40
61
|
varying vec2 v_texel;
|
|
@@ -45,7 +66,7 @@ void main(void) {
|
|
|
45
66
|
// save texel vector to pass to fragment shader
|
|
46
67
|
v_texel = a_texel;
|
|
47
68
|
}
|
|
48
|
-
`;var
|
|
69
|
+
`;var Fb=`#ifdef GL_ES
|
|
49
70
|
precision highp float;
|
|
50
71
|
precision highp int;
|
|
51
72
|
#else
|
|
@@ -88,5 +109,5 @@ void main(void) {
|
|
|
88
109
|
// sample using new coordinates
|
|
89
110
|
gl_FragColor = texture2D(u_texture, tc);
|
|
90
111
|
}
|
|
91
|
-
`;var Ps=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let a=this.canvas.getContext("webgl");if(!a)throw new Error("Could not initialize WebGL context");this.gl=a,this.container.appendChild(this.canvas),this.camera=new Es(this.params.fov,this.params.orientation),this.cameraRotationManager=new xs(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),a=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(a,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader($b,this.gl.VERTEX_SHADER),r=this.createShader(Mb,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,a=this.frameHeight/(this.frameWidth/this.viewportWidth);return a>this.viewportHeight?t=this.viewportHeight/a:r=a/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,a=this.camera.fov.y/180/2,s=e-r,n=t-a,o=e+r,l=t-a,u=e+r,c=t+a,d=e-r,p=t+a;return[s,n,o,l,u,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var Yt=class{constructor(e){this.subscription=new Yw;this.videoState=new L("stopped");this.elementSize$=new Ww(void 0);this.textTracksManager=new xe;this.droppedFramesManager=new as;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new es;this.textTracks=[];this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state==="requested"&&r?.to!=="paused"&&e!=="stopped"&&t!=="stopped"){let n=this.liveOffset?.getTotalPausedTime()??0;this.seek(a.position-n,a.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="ready"&&I(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset?.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):r?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;default:return _w(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Ps(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.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=ae(e.container,e.tuning),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(W(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Is({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=oe(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:ku.WTF,message:`${a} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,l)=>this.subscription.add(o.subscribe(l,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:a,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Cb(u=>!!u.length),Vb()).subscribe(u=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:u})})),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(Cb(Uw),Vb()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(Ob(u=>u.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(Ge(this.video,t.isLooped,a)),this.subscription.add(ne(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Ee(this.video,t.playbackRate,r.playbackRateState$,a)),s(Gw(this.video),this.elementSize$),s(ke(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},a)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{if(u==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if(Nw(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(fu(h));let f=[];for(let b of h.representations){let S=Sb(b);f.push(S),this.audioTracksMap.set(S,{stream:h,representation:b})}this.audioStreamsMap.set(h,f)}this.params.output.availableAudioStreams$.next(p)}let d=[];for(let p of c.video){d.push(bu(p));let h=[];for(let f of p.representations){let b=bb(f);b&&(h.push(b),this.videoTracksMap.set(b,{stream:p,representation:f}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(d);for(let p of c.text)for(let h of p.representations){let f=ms(p,h);this.textTracksMap.set(f,{stream:p,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size>0&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else u==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a));let n=u=>e.error$.next({id:"RepresentationSwitch",category:ku.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(ks(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$,qw(this.video,"progress")).subscribe(()=>{let u=this.player.state$.getState(),c=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(u)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[p,h]=d,f=this.params.desiredState.autoVideoTrackLimits.getTransition();if(f&&this.params.output.autoVideoTrackLimits$.next(f.to),u==="manifest_ready")this.player.initRepresentations(p.id,h?.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(n),h){let b=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",h.id,b).catch(n)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:u})=>{this.scene3D&&u&&this.scene3D.pointCameraTo(u.x,u.y)})),this.subscription.add(this.elementSize$.subscribe(u=>{this.scene3D&&u&&this.scene3D.setViewportSize(u.width,u.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(wu()).subscribe(u=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:f}])=>f.id===u);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(bu(p))},a)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(wu()).subscribe(u=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===u);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(fu(p))},a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{if(u?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch(c){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${c}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},a)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,a)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,a)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(Ob(({to:u})=>u==="ready"),wu());this.subscription.add(ks(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let u=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add(ks(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=ks(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,jw(["init"])).pipe(Fw(0));this.subscription.add(l.subscribe(this.syncPlayback,a))}selectVideoAudioRepresentations(){let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),a=e.videoTrack.getState()?.id,n=[...this.videoTracksMap.keys()].find(({id:x})=>x===a),o=t.currentVideoTrack$.getValue(),l=e.videoStream.getState()??(n&&this.videoTracksMap.get(n)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!l)return;let u=[...this.videoStreamsMap.keys()].find(({id:x})=>x===l.id),c=u&&this.videoStreamsMap.get(u);if(!c)return;let d=rt(this.video.buffered,this.video.currentTime*1e3),p=r?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=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),b=[...this.audioStreamsMap.keys()].find(({id:x})=>x===f?.id)??this.audioStreamsMap.keys().next().value,S=0;if(b){if(n&&!r){let x=hs(n,c,this.audioStreamsMap.get(b)??[]);S=Math.max(S,x?.bitrate??-1/0)}if(o){let x=hs(o,c,this.audioStreamsMap.get(b)??[]);S=Math.max(S,x?.bitrate??-1/0)}}let v=vt(c,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:S,forwardBufferHealth:h,current:o,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),{backgroundVideoQualityLimit:A}=this.params.tuning.autoTrackSelection;!this.params.output.elementVisible$.getValue()&&r&&(v=c.filter(x=>!Hw(x.quality)).sort((x,R)=>(R.bitrate??0)-(x.bitrate??0)).filter(x=>Db(x.quality,v.quality)&&Db(x.quality,A))[0]??v);let y=r?v??n:n??v,g=b&&hs(y,c,this.audioStreamsMap.get(b)??[]),T=this.videoTracksMap.get(y)?.representation,M=g&&this.audioTracksMap.get(g)?.representation;if(T&&M)return[T,M];if(T&&!M&&this.audioTracksMap.size===0)return[T,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ue(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ku.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),se(this.video)}};var Wi=class extends Yt{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Bb,interval as Qw,map as zw}from"@vkontakte/videoplayer-shared";var Qi=class extends Yt{constructor(e){super(e),this.liveOffset=new et}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(Bb({interval:Qw(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:a})=>{if(this.videoState.getState()==="playing"){let s=e.position$.getValue()+(a-1);s<=0&&e.position$.next(s),this.liveOffset?.resetTo(-s*1e3)}})).add(Bb({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(zw(({liveBufferTime:a,liveAvailabilityStartTime:s})=>a&&s?a+s:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(a=>{if(a){let s=ms(a,a);this.params.desiredState.internalTextTracks.startTransitionTo([s])}else this.params.desiredState.internalTextTracks.startTransitionTo([])}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),a=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(n,a)})}};var Nb=He(Ja(),1);import{assertNever as zi,assertNonNullable as _b,debounce as Kw,ErrorCategory as ws,filter as Jw,isNonNullable as Xw,isNullable as Zw,map as As,merge as eA,Observable as tA,observableFrom as rA,Subscription as iA,videoSizeToQuality as aA}from"@vkontakte/videoplayer-shared";var Ne={};var Rr=(i,e)=>new tA(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),Ki=class{constructor(e){this.subscription=new iA;this.videoState=new L("initializing");this.textTracksManager=new xe;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(e!=="initializing")switch(r?.to!=="paused"&&a.state==="requested"&&this.seek(a.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:zi(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:zi(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:zi(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:zi(e)}break;default:zi(t)}};this.video=ae(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(W(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),se(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:ws.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Nb.default)(import("hls.js").then(a=>{e||(Ne.Hls=a.default,Ne.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){_b(Ne.Hls,"hls.js not loaded"),this.hls=new Ne.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){_b(Ne.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=u=>{t.error$.next({id:"HlsJsProvider",category:ws.WTF,message:"HlsJsProvider internal logic error",thrown:u})},a=oe(this.video),s=(u,c)=>this.subscription.add(u.subscribe(c,r));s(a.timeUpdate$,t.position$),s(a.durationChange$,t.duration$),s(a.ended$,t.endedEvent$),s(a.looped$,t.loopedEvent$),s(a.error$,t.error$),s(a.isBuffering$,t.isBuffering$),s(a.currentBuffer$,t.currentBuffer$),s(a.loadStart$,t.firstBytesEvent$),s(a.loadedMetadata$,t.loadedMetadataEvent$),s(a.playing$,t.firstFrameEvent$),s(a.canplay$,t.canplay$),s(a.seeked$,t.seekedEvent$),s(a.inPiP$,t.inPiP$),s(a.inFullscreen$,t.inFullscreen$),this.subscription.add(Ge(this.video,e.isLooped,r)),this.subscription.add(ne(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ee(this.video,e.playbackRate,a.playbackRateState$,r)),s(ke(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(As(u=>u.to)),this.params.output.playbackState$),this.subscription.add(Rr(this.hls,Ne.Events.ERROR).subscribe(u=>{u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:ws.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${u.err?.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(e.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(e.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(Rr(this.hls,Ne.Events.MANIFEST_PARSED).pipe(As(({levels:u})=>u.reduce((c,d)=>{let p=d.name||d.height.toString(10),{width:h,height:f}=d,b=St(d.attrs.QUALITY??"")??aA({width:h,height:f});if(!b)return c;let S=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:f},fps:S};return this.trackLevels.set(p,{track:v,level:d}),c.push(v),c},[]))),t.availableVideoTracks$),s(Rr(this.hls,Ne.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){let c=[];for(let d of u.subtitleTracks){let p=d.name,h=d.attrs.URI||"",f=d.lang;c.push({id:p,url:h,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(Rr(this.hls,Ne.Events.LEVEL_LOADING).pipe(As(({url:u})=>W(u))),t.hostname$),s(Rr(this.hls,Ne.Events.FRAG_CHANGED),u=>{let{video:c,audio:d}=u.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3)}),this.subscription.add(mt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:r}));let n=u=>Array.from(this.trackLevels.values()).find(({level:c})=>c===u)?.track,o=Rr(this.hls,Ne.Events.LEVEL_SWITCHED).pipe(As(({level:u})=>n(this.hls.levels[u])));o.pipe(Jw(Xw)).subscribe(t.currentVideoTrack$,r),this.subscription.add(mt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),u=>{if(Zw(u))return;let c=this.trackLevels.get(u.id)?.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let l=eA(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,rA(["init"])).pipe(Kw(0));this.subscription.add(l.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await ue(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ws.DOM,thrown:t}))||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0)}};var Fb="X-Playback-Duration",Au=async i=>{let e=await it(i),t=await e.text(),r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return r?parseInt(r,10):e.headers.has(Fb)?parseInt(e.headers.get(Fb),10):void 0};import{assertNever as cA,combine as dA,debounce as pA,ErrorCategory as Ls,filter as hA,filterChanged as mA,isNonNullable as Ub,isNullable as $s,map as Hb,merge as fA,observableFrom as bA,Subscription as SA,ValueSubject as $u,VideoQuality as gA}from"@vkontakte/videoplayer-shared";var Lu=He(Wn(),1);import{videoSizeToQuality as sA,getExponentialDelay as nA}from"@vkontakte/videoplayer-shared";var oA=i=>{let e=null;if(i.QUALITY&&(e=St(i.QUALITY)),!e&&i.RESOLUTION){let[t,r]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=sA({width:t,height:r})}return e??null},uA=(i,e)=>{let t=i.split(`
|
|
92
|
-
`),r=[],a=[];for(let s=0;s<t.length;s++){let n=t[s],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),l=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!l)){if(o){let u=(0,Lu.default)(o[1].split(",").map(S=>S.split("="))),c=u.QUALITY??`stream-${u.BANDWIDTH}`,d=oA(u),p;u.BANDWIDTH&&(p=parseInt(u.BANDWIDTH,10)/1e3||void 0),!p&&u["AVERAGE-BANDWIDTH"]&&(p=parseInt(u["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=u["FRAME-RATE"]?parseFloat(u["FRAME-RATE"]):void 0,f;if(u.RESOLUTION){let[S,v]=u.RESOLUTION.split("x").map(A=>parseInt(A,10));S&&v&&(f={width:S,height:v})}let b=new URL(t[++s],e).toString();d&&r.push({id:c,quality:d,url:b,bandwidth:p,size:f,fps:h})}if(l){let u=(0,Lu.default)(l[1].split(",").map(h=>h.split("=")).map(([h,f])=>[h,f.replace(/^"|"$/g,"")])),c=u.URI?.replace(/playlist$/,"subtitles.vtt"),d=u.LANGUAGE,p=u.NAME;c&&d&&a.push({type:"internal",id:d,label:p,language:d,url:c,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:a}},lA=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),Ru=0,qb=async(i,e=i,t)=>{let a=await(await it(i)).text();Ru+=1;try{let{qualityManifests:s,textTracks:n}=uA(a,e);return{qualityManifests:s,textTracks:n}}catch{if(Ru<=t.manifestRetryMaxCount)return await lA(nA(Ru-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),qb(i,e,t)}return{qualityManifests:[],textTracks:[]}},Rs=qb;var Ji=class{constructor(e){this.subscription=new SA;this.videoState=new L("stopped");this.textTracksManager=new xe;this.manifests$=new $u([]);this.liveOffset=new et;this.manifestStartTime$=new $u(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let u=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),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(a?.to!=="paused"&&u.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(u.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?I(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),I(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):a?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else a?.to==="paused"&&(I(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return cA(t)}};this.params=e,this.video=ae(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:gA.INVARIANT,url:this.params.source.url},Rs(K(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})=>{t.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Ls.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Ls.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),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(W(this.params.source.url)),this.maxSeekBackTime$=new $u(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(l=>l.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:Ls.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=oe(this.video),s=(o,l)=>this.subscription.add(o.subscribe(l,r));s(a.ended$,e.endedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(ne(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ee(this.video,t.playbackRate,a.playbackRateState$,r)),s(ke(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(mA(),Hb(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),l=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&Ub(u.to)){let d=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(W(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),l&&l.from==="changing_manifest"&&this.videoState.setState(l.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(a.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(dA({startTime:this.manifestStartTime$.pipe(hA(Ub)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:l})=>this.params.output.liveTime$.next(o+l*1e3),r)),this.subscription.add(this.manifests$.pipe(Hb(o=>o.map(({id:l,quality:u,size:c,bandwidth:d,fps:p})=>({id:l,quality:u,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=fA(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,bA(["init"])).pipe(pA(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),se(this.video)}prepare(){let e=this.selectManifest();if($s(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:l}=t?.to??r??{};for(let[u,c]of[[o,"mq"],[l,"lq"]]){let d=String(parseFloat(u||""));c&&u&&a.searchParams.set(c,d)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=K(a.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),Au(n).then(o=>{if(!$s(o))this.maxSeekBackTime$.next(o);else{let l=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if($s(l)||!isFinite(l))try{it(n).then(u=>u.text()).then(u=>{let c=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(u)?.[1];if(c){let d=new URL(c,n).toString();Au(d).then(p=>{$s(p)||this.maxSeekBackTime$.next(p)})}})}catch{}}})}playIfAllowed(){ue(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ls.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}};import{assertNever as vA,debounce as yA,ErrorCategory as Mu,fromEvent as Cu,isNonNullable as TA,isNullable as IA,map as jb,merge as Gb,observableFrom as Yb,Subscription as EA,ValueSubject as xA,VideoQuality as PA,clientChecker as kA}from"@vkontakte/videoplayer-shared";var Xi=class{constructor(e){this.subscription=new EA;this.videoState=new L("stopped");this.textTracksManager=new xe;this.manifests$=new xA([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let u=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),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch(a?.to!=="paused"&&u.state==="requested"&&this.seek(u.position),t){case"ready":r==="ready"?I(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):a?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):a?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return vA(t)}};this.params=e,this.video=ae(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:PA.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(W(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Rs(K(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Mu.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(l=>l.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:Mu.WTF,message:"HlsProvider internal logic error",thrown:o})},a=oe(this.video),s=(o,l)=>this.subscription.add(o.subscribe(l));if(s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(jb(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ge(this.video,t.isLooped,r)),this.subscription.add(ne(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ee(this.video,t.playbackRate,a.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),l=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&TA(u.to)){let d=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let p=this.manifests$.getValue().find(h=>h.id===d);if(p){this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(W(p.url));let h=this.params.desiredState.playbackRate.getState(),f=this.params.output.element$.getValue()?.playbackRate;if(h!==f){let b=this.params.output.element$.getValue();b&&(this.params.desiredState.playbackRate.setState(h),b.playbackRate=h)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),l&&l.from==="changing_manifest"&&this.videoState.setState(l.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(jb(o=>o.map(({id:l,quality:u,size:c,bandwidth:d,fps:p})=>({id:l,quality:u,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!kA.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Gb(Cu(o,"addtrack"),Cu(o,"removetrack"),Cu(o,"change"),Yb(["init"])).subscribe(()=>{for(let l=0;l<o.length;l++)o[l].mode="hidden"},r))}let n=Gb(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Yb(["init"])).pipe(yA(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),se(this.video)}prepare(){let e=this.selectManifest();if(IA(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:s,min:n}=t?.to??r??{};for(let[o,l]of[[s,"mq"],[n,"lq"]]){let u=String(parseFloat(o||""));l&&o&&a.searchParams.set(l,u)}}this.video.setAttribute("src",a.toString()),this.video.load()}playIfAllowed(){ue(this.video).then(e=>{e||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Mu.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as wA,assertNonNullable as Wb,debounce as AA,ErrorCategory as Qb,isHigher as RA,isHigherOrEqual as LA,isInvariantQuality as zb,isLowerOrEqual as $A,isNonNullable as MA,merge as CA,observableFrom as DA,Subscription as OA,map as VA}from"@vkontakte/videoplayer-shared";var Zi=class{constructor(e){this.subscription=new OA;this.videoState=new L("stopped");this.trackUrls={};this.textTracksManager=new xe;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:l}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:l*1e3,forcePrecise:!0}),n.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[n.to.id]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(r?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?I(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;default:return wA(e)}};this.params=e,this.video=ae(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,r],a)=>{let s=a.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:Qb.WTF,message:"MpegProvider internal logic error",thrown:o})},a=oe(this.video),s=(o,l)=>this.subscription.add(o.subscribe(l,r));s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(VA(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ge(this.video,t.isLooped,r)),this.subscription.add(ne(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ee(this.video,t.playbackRate,a.playbackRateState$,r)),s(ke(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&MA(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(),u=this.params.output.element$.getValue()?.playbackRate;if(l!==u){let c=this.params.output.element$.getValue();c&&(this.params.desiredState.playbackRate.setState(l),c.playbackRate=l)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=CA(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,DA(["init"])).pipe(AA(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),se(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;Wb(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Wb(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ui(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(W(t))}playIfAllowed(){ue(this.video).then(e=>{e||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Qb.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){let t,r=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){let a=Object.values(this.trackUrls).find(o=>!zb(o.track.quality)&&$A(o.track.quality,e))?.track,s=this.params.desiredState.videoTrack.getState()?.id,n=this.trackUrls[s??"0"]?.track;if(a&&n&&LA(n.quality,a.quality)&&(t=a),!t){let o=Object.values(this.trackUrls).filter(u=>!zb(u.track.quality)&&RA(u.track.quality,e)),l=o.length;l&&(t=o[l-1].track)}t&&(r=t.quality)}else if(!e){let a=Object.values(this.trackUrls).map(s=>s.track);t=vt(a,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};import{assertNever as Jb,debounce as FA,merge as Xb,observableFrom as qA,Subscription as UA,map as Zb,ValueSubject as HA,ErrorCategory as Ou,VideoQuality as jA}from"@vkontakte/videoplayer-shared";import{ErrorCategory as BA}from"@vkontakte/videoplayer-shared";var Kb=["stun:videostun.mycdn.me:80"],_A=1e3,NA=3,Du=()=>null,Ms=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=Du;this.externalStopCallback=Du;this.externalErrorCallback=Du;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:Kb}]};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:BA.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),_A)}normalizeOptions(e={}){let t={stunServerList:Kb,maxRetryNumber:NA,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var ea=class{constructor(e){this.videoState=new L("stopped");this.maxSeekBackTime$=new HA(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;default:return Jb(e)}};this.subscription=new UA,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ae(e.container,e.tuning),this.liveStreamClient=new Ms(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.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),se(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Ou.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};Xb(this.videoState.stateChangeStarted$.pipe(Zb(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Zb(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=oe(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(a.timeUpdate$,e.liveTime$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(ke(this.video),this.params.output.elementVisible$),this.subscription.add(a.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(a.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(ne(this.video,t.volume,a.volumeState$,r)).add(a.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return Jb(n.to)}},r)).add(Xb(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,qA(["init"])).pipe(FA(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(W(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:jA.INVARIANT}),this.video.srcObject=e,I(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Ou.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ue(this.video).then(e=>{e||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ou.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var ta=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as aa,assertNonNullable as It,ErrorCategory as Ds,filter as JA,isNonNullable as sS,isNullable as XA,map as ZA,merge as eR,once as tR,Subject as be,Subscription as nS,ValueSubject as $}from"@vkontakte/videoplayer-shared";import{Observable as GA,map as eS,Subscription as YA,Subject as WA}from"@vkontakte/videoplayer-shared";var tS=i=>new GA(e=>{let t=new YA,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(eS(({from:u,to:c})=>`${u}-${c}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe(eS(({type:u})=>u!==void 0)),n=new WA,o=0,l="unknown";return t.add(r.subscribe(u=>{o&&window.clearTimeout(o),l=u,o=window.setTimeout(()=>n.next(u),i.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(o),l="unknown",o=0})),t.add(s.subscribe(u=>{o&&(window.clearTimeout(o),o=0,u&&(o=window.setTimeout(()=>n.next(l),i.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as rS,Subscription as QA,combine as zA,filter as iS,once as aS}from"@vkontakte/videoplayer-shared";var ra=null,Cs=null;function Vu(){return ra||(ra=new(window.AudioContext||window.webkitAudioContext)),Cs||(Cs=new GainNode(ra,{gain:1}),Cs.connect(ra.destination)),{audioCtx:ra,gainNode:Cs}}import{clientChecker as KA}from"@vkontakte/videoplayer-shared";var ia=class i{constructor(e,t,r,a,s){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=a;this.subscriptions=new QA;this.lastAudioContextResumeId=0;!s||!this.isSupported()||a===1||this.subscriptions.add(this.provider$.pipe(iS(n=>!!n.type),aS()).subscribe(({type:n})=>this.subscribe(n)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){KA.isSafari&&e!=="MPEG"||this.subscriptions.add(zA({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(iS(({playbackState:t,video:r,volume:{muted:a,volume:s}})=>t==="playing"&&!!r&&!a&&!!s),aS()).subscribe(({video:t})=>this.initAudioContextOnce(t)))}isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){let{volumeMultiplier:t}=this,{audioCtx:r,gainNode:a}=Vu(),s=(Math.random()+1)*999999;this.lastAudioContextResumeId=s,r.resume().then(()=>{if(s!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${i.errorId} destroyed`);a.gain.value=t;try{new MediaElementAudioSourceNode(r,{mediaElement:e}).connect(a)}catch(n){this.volumeMultiplierError$.next({id:i.errorId,category:rS.VIDEO_PIPELINE,message:n?.message??"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:n})}}).catch(n=>{this.volumeMultiplierError$.next({id:i.errorId,category:rS.VIDEO_PIPELINE,message:n?.message??"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){let{gainNode:e}=Vu();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};var rR={chunkDuration:5e3,maxParallelRequests:5},sa=class{constructor(e){this.current$=new $({type:void 0});this.providerError$=new be;this.noAvailableProvidersError$=new be;this.volumeMultiplierError$=new be;this.providerOutput={position$:new $(0),duration$:new $(1/0),volume$:new $({muted:!1,volume:1}),availableVideoStreams$:new $([]),currentVideoStream$:new $(void 0),availableVideoTracks$:new $([]),currentVideoTrack$:new $(void 0),availableAudioStreams$:new $([]),currentAudioStream$:new $(void 0),availableAudioTracks$:new $([]),currentVideoSegmentLength$:new $(0),currentAudioSegmentLength$:new $(0),isAudioAvailable$:new $(!0),autoVideoTrackLimitingAvailable$:new $(!1),autoVideoTrackLimits$:new $(void 0),currentBuffer$:new $(void 0),isBuffering$:new $(!0),error$:new be,warning$:new be,willSeekEvent$:new be,seekedEvent$:new be,loopedEvent$:new be,endedEvent$:new be,firstBytesEvent$:new be,loadedMetadataEvent$:new be,firstFrameEvent$:new be,canplay$:new be,isLive$:new $(void 0),isLowLatency$:new $(!1),canChangePlaybackSpeed$:new $(!0),liveTime$:new $(void 0),liveBufferTime$:new $(void 0),availableTextTracks$:new $([]),currentTextTrack$:new $(void 0),hostname$:new $(void 0),httpConnectionType$:new $(void 0),httpConnectionReused$:new $(void 0),inPiP$:new $(!1),inFullscreen$:new $(!1),element$:new $(void 0),elementVisible$:new $(!0),availableSources$:new $(void 0),is3DVideo$:new $(!1),playbackState$:new $("")};this.subscription=new nS;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=kf([...Af(this.params.tuning),...wf(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>sS(e.sources[o])),{forceFormat:r,formatsToAvoid:a}=this.params.tuning,s=[];r?s=[r]:a.length?s=[...t.filter(o=>!a.includes(o)),...t.filter(o=>a.includes(o))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.screenFormatsIterator=new ta(s);let n=[...Zo(!0),...Zo(!1)];this.chromecastFormatsIterator=new ta(n.filter(o=>sS(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new ia(this.providerOutput,this.current$,this.volumeMultiplierError$,this.params.volumeMultiplier??1,this.params.tuning.useVolumeMultiplier)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager.destroy()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(XA(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:Ds.WTF,message:"Failed to create provider",thrown:a})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(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"});let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),a=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:a?r.position:t,forcePrecise:a?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return aa(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:a}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return It(o),new Wi({...n,source:o,sourceHls:l})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return It(o),new Qi({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return It(o),yr||!this.params.tuning.useHlsJs?new Xi({...n,source:o}):new Ki({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return It(o),new Ji({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return It(o),new Zi({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return It(o),new gf({...n,source:o,config:{...rR,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return It(o),new ea({container:r,source:o,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return aa(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:a,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return It(o),new ii({connection:o,meta:s,container:r,source:t,format:e,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return aa(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return aa(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return aa(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=a=>{let s=new URL(a);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:r(e.url)}}return(0,oS.default)(Object.entries(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new nS,t=!1,r=0;return e.add(eR(this.providerOutput.error$,tS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(ZA(a=>({id:`ProviderHangup:${a}`,category:Ds.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let a=this.params.desiredState.playbackState.transitionEnded$.pipe(JA(({to:s})=>s==="playing"),tR()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{let s=this.current$.getValue().destination;if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let n=a.category===Ds.NETWORK,o=a.category===Ds.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),u=r<this.params.tuning.providerErrorLimit&&!o;l&&!o&&(n&&t||!u)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):u?(r++,this.reinitProvider()):this.switchToNextProvider(s??"SCREEN")}})),e}};import{fromEvent as Os,once as iR,combine as aR,Subscription as uS,ValueSubject as Bu,map as sR,filter as nR,isNonNullable as Vs,now as Se,safeStorage as _u}from"@vkontakte/videoplayer-shared";var oR=5e3,lS="one_video_throughput",cS="one_video_rtt",na=window.navigator.connection,dS=()=>{let i=na?.downlink;if(Vs(i)&&i!==10)return i*1e3},pS=()=>{let i=na?.rtt;if(Vs(i)&&i!==3e3)return i},hS=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},Nu=class i{constructor(e){this.subscription=new uS;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=i.load(lS)||(e.useBrowserEstimation?dS():void 0)||oR,r=i.load(cS)??(e.useBrowserEstimation?pS():void 0)??0;if(this.throughput$=new Bu(t),this.rtt$=new Bu(r),this.rttAdjustedThroughput$=new Bu(hS(t,r,e.rttPenaltyRequestSize)),this.throughput=jt.getSmoothedValue(t,-1,e),this.rtt=jt.getSmoothedValue(r,1,e),e.useBrowserEstimation){let a=()=>{let n=dS();n&&this.throughput.next(n);let o=pS();Vs(o)&&this.rtt.next(o)};na&&"onchange"in na&&this.subscription.add(Os(na,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{_u.set(lS,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{_u.set(cS,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(aR({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(sR(({throughput:a,rtt:s})=>hS(a,s,e.rttPenaltyRequestSize)),nR(a=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(a-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=Se(),a=new uS;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(Os(e,"progress").pipe(iR()).subscribe(s=>{t=s.loaded,r=Se()}));break;case 1:case 0:a.add(Os(e,"loadstart").subscribe(()=>{t=0,r=Se()}));break}a.add(Os(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Se(),l=n-t,u=o-r;this.addRawSpeed(l,u,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let a=0,s=Se(),n=0,o=Se(),l=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},u=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(a,Se()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=Se();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=Se()}else n+=d.byteLength;o=Se()}else a+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Se()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Se()-o,this.concurrentDownloads.size),n=0,o=Se());await r?.read().then(u,l)}};this.concurrentDownloads.add(e),r?.read().then(u,l)}addRawSpeed(e,t,r=1,a=!1){if(i.sanityCheck(e,t,a)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let a=e*8/t;return!(!a||!isFinite(a)||a>1e6||a<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){let t=_u.get(e);if(Vs(t))return parseInt(t,10)??void 0}},mS=Nu;import{fillWithDefault as uR,VideoQuality as fS}from"@vkontakte/videoplayer-shared";var bS={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,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:fS.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:fS.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,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance: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,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewPartialSegmentFeeding:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1},SS=i=>({...uR(i,bS),configName:[...i.configName??[],...bS.configName]});import{assertNonNullable as Bs,combine as _s,ErrorCategory as Ns,filter as oa,filterChanged as we,fromEvent as qu,isNonNullable as fR,isNullable as bR,Logger as SR,map as C,mapTo as TS,merge as Et,now as Fs,once as ut,Subject as N,Subscription as IS,tap as ES,ValueSubject as E,isHigher as gR,isInvariantQuality as xS}from"@vkontakte/videoplayer-shared";import{merge as lR,map as cR,filter as gS,isNonNullable as dR}from"@vkontakte/videoplayer-shared";var Fu=({seekState:i,position$:e})=>lR(i.stateChangeEnded$.pipe(cR(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),gS(dR)),e.pipe(gS(()=>i.getState().state==="none")));import{assertNonNullable as pR}from"@vkontakte/videoplayer-shared";var vS=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return pR(e,`Wrong container or containerId {${i.container}}`),e};import{filter as hR,once as mR}from"@vkontakte/videoplayer-shared";var yS=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(hR(a=>a.length>0),mR()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t?.getValue().find(r))&&e.startTransitionTo(i)};var qs=class{constructor(e={configName:[]}){this.subscription=new IS;this.logger=new SR;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new E(!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 E("stopped"),position$:new E(0),duration$:new E(1/0),muted$:new E(!1),volume$:new E(1),availableVideoStreams$:new E([]),currentVideoStream$:new E(void 0),availableQualities$:new E([]),availableQualitiesFps$:new E({}),currentQuality$:new E(void 0),isAutoQualityEnabled$:new E(!0),autoQualityLimitingAvailable$:new E(!1),autoQualityLimits$:new E({}),availableAudioStreams$:new E([]),currentAudioStream$:new E(void 0),availableAudioTracks$:new E([]),isAudioAvailable$:new E(!0),currentPlaybackRate$:new E(1),currentBuffer$:new E({start:0,end:0}),isBuffering$:new E(!0),isStalled$:new E(!1),isEnded$:new E(!1),isLooped$:new E(!1),isLive$:new E(void 0),canChangePlaybackSpeed$:new E(void 0),atLiveEdge$:new E(void 0),atLiveDurationEdge$:new E(void 0),liveTime$:new E(void 0),liveBufferTime$:new E(void 0),currentFormat$:new E(void 0),availableTextTracks$:new E([]),currentTextTrack$:new E(void 0),throughputEstimation$:new E(void 0),rttEstimation$:new E(void 0),videoBitrate$:new E(void 0),hostname$:new E(void 0),httpConnectionType$:new E(void 0),httpConnectionReused$:new E(void 0),surface$:new E("none"),chromecastState$:new E("NOT_AVAILABLE"),chromecastDeviceName$:new E(void 0),intrinsicVideoSize$:new E(void 0),availableSources$:new E(void 0),is3DVideo$:new E(!1),currentVideoSegmentLength$:new E(0),currentAudioSegmentLength$:new E(0)};this.events={inited$:new N,ready$:new N,started$:new N,playing$:new N,paused$:new N,stopped$:new N,willStart$:new N,willResume$:new N,willPause$:new N,willStop$:new N,willDestruct$:new N,watchCoverageRecord$:new N,watchCoverageLive$:new N,managedError$:new N,fatalError$:new N,ended$:new N,looped$:new N,seeked$:new N,willSeek$:new N,firstBytes$:new N,loadedMetadata$:new N,firstFrame$:new N,canplay$:new N,log$:new N};this.experimental={element$:new E(void 0),tuningConfigName$:new E([]),enableDebugTelemetry$:new E(!1),dumpTelemetry:af};if(this.initLogs(),this.tuning=SS(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ba({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new mS(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,r,a)=>{let s=Reflect.get(t,r,a);return typeof s!="function"?s:(...n)=>{try{return s.apply(t,n)}catch(o){let l=n.map(d=>JSON.stringify(d,(p,h)=>{let f=typeof h;return["number","string","boolean"].includes(f)?h:h===null?null:`<${f}>`})),u=`Player.${String(r)}`,c=`Exception calling ${u} (${l.join(", ")})`;throw this.events.fatalError$.next({id:u,category:Ns.WTF,message:c,thrown:o}),o}}}})}initVideo(e){return this.config=e,this.domContainer=vS(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new sa({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){let e=this.desiredState.playbackState;return e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!pi()?qu(document,"visibilitychange").pipe(ut()).subscribe(e):e(),this}pause(){let e=this.desiredState.playbackState;return e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),a=this.info.isLive$.getValue();return e>=r&&!a&&(e=r-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:"requested",position:e*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return 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.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){Bs(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(oa(r=>r.length>0),ut()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){Bs(this.providerContainer);let t=this.providerContainer?.providerOutput.element$.getValue();return t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return yS(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(r){let a=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:a.x+s.x,y:a.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(bR(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return fR(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:a})=>r||a||0,0),height:e.reduce((r,{height:a})=>r||a||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Et(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(C(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(oa(({from:e})=>e==="stopped"),ut()).subscribe(()=>{this.initedAt=Fs(),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();n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Ns.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(C(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(C(n=>n.destination),we()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(C(n=>n.map(({quality:o})=>o).sort((o,l)=>xS(o)?1:xS(l)?-1:gR(l,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let l of n)l.fps&&(o[l.quality]=l.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$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(we()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(we()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(we()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n??{})})).add(e.providerOutput.currentBuffer$.pipe(C(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(_s({hasLiveOffsetByPaused:Et(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(C(n=>n.to),we(),C(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(_s({atLiveEdge:_s({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Fu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(C(({isLive:n,position:o,isLowLatency:l})=>{let u=this.getActiveLiveDelay(l);return n&&Math.abs(o)<u/1e3}),we(),ES(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(C(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(_s({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(C(({isLive:n,position:o,duration:l})=>n&&(Math.abs(l)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),we(),ES(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(C(n=>n.muted),we()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(C(n=>n.volume),we()).subscribe(this.info.volume$)).add(Fu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Et(e.providerOutput.endedEvent$.pipe(TS(!0)),e.providerOutput.seekedEvent$.pipe(TS(!1))).pipe(we()).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(C(n=>({id:n?`No${n}`:"NoProviders",category:Ns.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(ut(),C(n=>n??Fs()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(ut(),C(()=>Fs()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(ut(),C(()=>Fs()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new E(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new E(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(oa(({to:n})=>n==="playing"),ut()).subscribe(()=>r.next(!1)));let a=0,s=Et(e.providerOutput.isBuffering$,t,r).pipe(C(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),we());this.subscription.add(s.subscribe(n=>{n?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})),this.subscription.add(Et(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Et(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(),l=e.providerOutput.element$.getValue(),u=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":l?u?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(C(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new IS;this.subscription.add(t),this.subscription.add(e.current$.pipe(we((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(oa(r=>r.length>0),ut()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){let t,r=this.desiredState.videoTrack.getState()?.quality;r&&(t=e.find(({quality:a})=>a===r),t||this.setAutoQuality(!0)),t||(t=vt(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(Et(this.desiredState.videoTrack.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(C(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;Bs(this.providerContainer),Bs(e),rf(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>tf(t)),this.providerContainer.current$.subscribe(({type:t})=>oi("provider",t)),e.duration$.subscribe(t=>oi("duration",t)),e.availableVideoTracks$.pipe(oa(t=>!!t.length),ut()).subscribe(t=>oi("tracks",t)),this.events.fatalError$.subscribe(new te("fatalError")),this.events.managedError$.subscribe(new te("managedError")),e.position$.subscribe(new te("position")),e.currentVideoTrack$.pipe(C(t=>t?.quality)).subscribe(new te("quality")),this.info.currentBuffer$.subscribe(new te("buffer")),e.isBuffering$.subscribe(new te("isBuffering"))].forEach(t=>this.subscription.add(t)),oi("codecs",Pf())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},r=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Ns.DOM,message:String(a)})})};this.subscription.add(Et(qu(document,"visibilitychange"),qu(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let a=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!e?.released;a&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(a=>a.quality===t);r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as dj,Observable as pj,Subject as hj,ValueSubject as mj,VideoQuality as fj}from"@vkontakte/videoplayer-shared";var bj=`@vkontakte/videoplayer-core@${ju}`;export{ma as ChromecastState,Hs as HttpConnectionType,pj as Observable,re as PlaybackState,qs as Player,bj as SDK_VERSION,hj as Subject,dj as Subscription,js as Surface,ju as VERSION,mj as ValueSubject,pt as VideoFormat,fj as VideoQuality};
|
|
112
|
+
`;var ys=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let a=this.canvas.getContext("webgl");if(!a)throw new Error("Could not initialize WebGL context");this.gl=a,this.container.appendChild(this.canvas),this.camera=new Ss(this.params.fov,this.params.orientation),this.cameraRotationManager=new vs(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),a=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(a,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Nb,this.gl.VERTEX_SHADER),r=this.createShader(Fb,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,a=this.frameHeight/(this.frameWidth/this.viewportWidth);return a>this.viewportHeight?t=this.viewportHeight/a:r=a/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,a=this.camera.fov.y/180/2,s=e-r,n=t-a,o=e+r,c=t-a,u=e+r,d=t+a,l=e-r,p=t+a;return[s,n,o,c,u,d,l,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 qt=class{constructor(e){this.subscription=new Zk;this.videoState=new L("stopped");this.elementSize$=new ew(void 0);this.textTracksManager=new Ee;this.droppedFramesManager=new es;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new ai;this.audioTrackSwitchHistory=new ai;this.textTracks=[];this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state==="requested"&&r?.to!=="paused"&&e!=="stopped"&&t!=="stopped"){let n=this.liveOffset?.getTotalPausedTime()??0;this.seek(a.position-n,a.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="ready"&&I(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset?.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):r?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;default:return Wk(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new ys(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.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=se(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(Y(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new gs({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=ue(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:Pu.WTF,message:`${a} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,c)=>this.subscription.add(o.subscribe(c,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:a,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(qb(u=>!!u.length),Hb()).subscribe(u=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:u})})),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(qb(Kk),Hb()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(Ub(u=>u.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(Fe(this.video,t.isLooped,a)),this.subscription.add(oe(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Ie(this.video,t.playbackRate,r.playbackRateState$,a)),s(Xk(this.video),this.elementSize$),s(Pe(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},a)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{if(u==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(Yk(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of d.audio){p.push(fu(h));let m=[];for(let b of h.representations){let g=Pb(b);m.push(g),this.audioTracksMap.set(g,{stream:h,representation:b})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(p)}let l=[];for(let p of d.video){l.push(mu(p));let h=[];for(let m of p.representations){let b=xb(m);b&&(h.push(b),this.videoTracksMap.set(b,{stream:p,representation:m}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(l);for(let p of d.text)for(let h of p.representations){let m=Ab(p,h);this.textTracksMap.set(m,{stream:p,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size>0&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else u==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a));let n=u=>e.error$.next({id:"RepresentationSwitch",category:Pu.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(Ts(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$,zk(this.video,"progress")).subscribe(()=>{let u=this.player.state$.getState(),d=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(u)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let l=this.selectVideoAudioRepresentations();if(!l)return;let[p,h]=l,m=this.params.desiredState.autoVideoTrackLimits.getTransition();if(m&&this.params.output.autoVideoTrackLimits$.next(m.to),u==="manifest_ready")this.player.initRepresentations(p.id,h?.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(n),h){let b=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",h.id,b).catch(n)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:u})=>{this.scene3D&&u&&this.scene3D.pointCameraTo(u.x,u.y)})),this.subscription.add(this.elementSize$.subscribe(u=>{this.scene3D&&u&&this.scene3D.setViewportSize(u.width,u.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Au()).subscribe(u=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===u);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[l,{stream:p}]=d,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(l),e.currentVideoStream$.next(mu(p))},a)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Au()).subscribe(u=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===u);if(!d){e.currentAudioStream$.next(void 0);return}let[l,{stream:p}]=d,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(fu(p))},a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{if(u?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},a)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,a)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,a)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(Ub(({to:u})=>u==="ready"),Au());this.subscription.add(Ts(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let u=t.autoVideoTrackSwitching.getState(),l=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(l)})),this.subscription.add(Ts(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let c=Ts(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Jk(["init"])).pipe(Qk(0));this.subscription.add(c.subscribe(this.syncPlayback,a))}selectVideoAudioRepresentations(){let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),a=e.videoTrack.getState()?.id,n=[...this.videoTracksMap.keys()].find(({id:E})=>E===a),o=t.currentVideoTrack$.getValue(),c=e.videoStream.getState()??(n&&this.videoTracksMap.get(n)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let u=[...this.videoStreamsMap.keys()].find(({id:E})=>E===c.id),d=u&&this.videoStreamsMap.get(u);if(!d)return;let l=ze(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(l/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),b=[...this.audioStreamsMap.keys()].find(({id:E})=>E===m?.id)??this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r)if(this.params.tuning.useSeparateAudioVideoABR){let E=Ka(n,d,this.audioStreamsMap.get(b)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,E?.bitrate??-1/0)}else{let E=cs(n,d,this.audioStreamsMap.get(b)??[]);g=Math.max(g,E?.bitrate??-1/0)}if(o)if(this.params.tuning.useSeparateAudioVideoABR){let E=Ka(o,d,this.audioStreamsMap.get(b)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,E?.bitrate??-1/0)}else{let E=cs(o,d,this.audioStreamsMap.get(b)??[]);g=Math.max(g,E?.bitrate??-1/0)}}let v=lt(d,{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}),A=r?v??n:n??v,y;this.params.tuning.useSeparateAudioVideoABR?y=b&&fm(A,d,this.audioStreamsMap.get(b)??[],{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}):y=b&&cs(A,d,this.audioStreamsMap.get(b)??[]);let S=this.videoTracksMap.get(A)?.representation,T=y&&this.audioTracksMap.get(y)?.representation;if(S&&T)return[S,T];if(S&&!T&&this.audioTracksMap.size===0)return[S,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){le(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Pu.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),ne(this.video),this.tracer.end()}};var Gi=class extends qt{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as jb,interval as tw,map as rw}from"@vkontakte/videoplayer-shared";var Wi=class extends qt{constructor(e){super(e),this.liveOffset=new Ye}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(jb({interval:tw(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:a})=>{if(this.videoState.getState()==="playing"){let s=e.position$.getValue()+(a-1);s<=0&&e.position$.next(s),this.liveOffset?.resetTo(-s*1e3)}})).add(jb({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(rw(({liveBufferTime:a,liveAvailabilityStartTime:s})=>a&&s?a+s:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),a=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(n,a)})}};var Wb=_e(Ya(),1);import{assertNever as Yi,assertNonNullable as Gb,debounce as iw,ErrorCategory as Is,filter as aw,isNonNullable as sw,isNullable as nw,map as Es,merge as ow,Observable as uw,observableFrom as cw,Subscription as lw,videoSizeToQuality as dw}from"@vkontakte/videoplayer-shared";var Be={};var Pr=(i,e)=>new uw(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),Qi=class{constructor(e){this.subscription=new lw;this.videoState=new L("initializing");this.textTracksManager=new Ee;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(e!=="initializing")switch(r?.to!=="paused"&&a.state==="requested"&&this.seek(a.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:Yi(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Yi(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Yi(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Yi(e)}break;default:Yi(t)}};this.video=se(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(Y(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),ne(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Is.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Wb.default)(import("hls.js").then(a=>{e||(Be.Hls=a.default,Be.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){Gb(Be.Hls,"hls.js not loaded"),this.hls=new Be.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Gb(Be.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=u=>{t.error$.next({id:"HlsJsProvider",category:Is.WTF,message:"HlsJsProvider internal logic error",thrown:u})},a=ue(this.video),s=(u,d)=>this.subscription.add(u.subscribe(d,r));s(a.timeUpdate$,t.position$),s(a.durationChange$,t.duration$),s(a.ended$,t.endedEvent$),s(a.looped$,t.loopedEvent$),s(a.error$,t.error$),s(a.isBuffering$,t.isBuffering$),s(a.currentBuffer$,t.currentBuffer$),s(a.loadStart$,t.firstBytesEvent$),s(a.loadedMetadata$,t.loadedMetadataEvent$),s(a.playing$,t.firstFrameEvent$),s(a.canplay$,t.canplay$),s(a.seeked$,t.seekedEvent$),s(a.inPiP$,t.inPiP$),s(a.inFullscreen$,t.inFullscreen$),this.subscription.add(Fe(this.video,e.isLooped,r)),this.subscription.add(oe(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ie(this.video,e.playbackRate,a.playbackRateState$,r)),s(Pe(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(Es(u=>u.to)),this.params.output.playbackState$),this.subscription.add(Pr(this.hls,Be.Events.ERROR).subscribe(u=>{u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:Is.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${u.err?.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(e.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(e.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(Pr(this.hls,Be.Events.MANIFEST_PARSED).pipe(Es(({levels:u})=>u.reduce((d,l)=>{let p=l.name||l.height.toString(10),{width:h,height:m}=l,b=ct(l.attrs.QUALITY??"")??dw({width:h,height:m});if(!b)return d;let g=l.attrs["FRAME-RATE"]?parseFloat(l.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:b,bitrate:l.bitrate/1e3,size:{width:h,height:m},fps:g};return this.trackLevels.set(p,{track:v,level:l}),d.push(v),d},[]))),t.availableVideoTracks$),s(Pr(this.hls,Be.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){let d=[];for(let l of u.subtitleTracks){let p=l.name,h=l.attrs.URI||"",m=l.lang;d.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(d)}}),s(Pr(this.hls,Be.Events.LEVEL_LOADING).pipe(Es(({url:u})=>Y(u))),t.hostname$),s(Pr(this.hls,Be.Events.FRAG_CHANGED),u=>{let{video:d,audio:l}=u.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((l?.endPTS??0)-(l?.startPTS??0))*1e3)}),this.subscription.add(nt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:r}));let n=u=>Array.from(this.trackLevels.values()).find(({level:d})=>d===u)?.track,o=Pr(this.hls,Be.Events.LEVEL_SWITCHED).pipe(Es(({level:u})=>n(this.hls.levels[u])));o.pipe(aw(sw)).subscribe(t.currentVideoTrack$,r),this.subscription.add(nt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),u=>{if(nw(u))return;let d=this.trackLevels.get(u.id)?.level;if(!d)return;let l=this.hls.levels.indexOf(d),p=this.hls.currentLevel,h=this.hls.levels[p];!h||d.bitrate>h.bitrate?this.hls.nextLevel=l:(this.hls.loadLevel=l,this.hls.loadLevel=l)},{changed$:o,onError:r})),s(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let c=ow(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,cw(["init"])).pipe(iw(0));this.subscription.add(c.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await le(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Is.DOM,thrown:t}))||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0)}};var Yb="X-Playback-Duration",ku=async i=>{let e=await Ke(i),t=await e.text(),r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return r?parseInt(r,10):e.headers.has(Yb)?parseInt(e.headers.get(Yb),10):void 0};import{assertNever as gw,combine as Sw,debounce as vw,ErrorCategory as Ps,filter as yw,filterChanged as Tw,isNonNullable as zb,isNullable as As,map as Kb,merge as Iw,observableFrom as Ew,Subscription as xw,ValueSubject as $u,VideoQuality as Pw}from"@vkontakte/videoplayer-shared";var Ru=_e(Yn(),1);import{videoSizeToQuality as pw,getExponentialDelay as hw}from"@vkontakte/videoplayer-shared";var fw=i=>{let e=null;if(i.QUALITY&&(e=ct(i.QUALITY)),!e&&i.RESOLUTION){let[t,r]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=pw({width:t,height:r})}return e??null},mw=(i,e)=>{let t=i.split(`
|
|
113
|
+
`),r=[],a=[];for(let s=0;s<t.length;s++){let n=t[s],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),c=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!c)){if(o){let u=(0,Ru.default)(o[1].split(",").map(g=>g.split("="))),d=u.QUALITY??`stream-${u.BANDWIDTH}`,l=fw(u),p;u.BANDWIDTH&&(p=parseInt(u.BANDWIDTH,10)/1e3||void 0),!p&&u["AVERAGE-BANDWIDTH"]&&(p=parseInt(u["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=u["FRAME-RATE"]?parseFloat(u["FRAME-RATE"]):void 0,m;if(u.RESOLUTION){let[g,v]=u.RESOLUTION.split("x").map(A=>parseInt(A,10));g&&v&&(m={width:g,height:v})}let b=new URL(t[++s],e).toString();l&&r.push({id:d,quality:l,url:b,bandwidth:p,size:m,fps:h})}if(c){let u=(0,Ru.default)(c[1].split(",").map(h=>h.split("=")).map(([h,m])=>[h,m.replace(/^"|"$/g,"")])),d=u.URI?.replace(/playlist$/,"subtitles.vtt"),l=u.LANGUAGE,p=u.NAME;d&&l&&a.push({type:"internal",id:l,label:p,language:l,url:d,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:a}},bw=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),wu=0,Qb=async(i,e=i,t)=>{let a=await(await Ke(i)).text();wu+=1;try{let{qualityManifests:s,textTracks:n}=mw(a,e);return{qualityManifests:s,textTracks:n}}catch{if(wu<=t.manifestRetryMaxCount)return await bw(hw(wu-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Qb(i,e,t)}return{qualityManifests:[],textTracks:[]}},xs=Qb;var zi=class{constructor(e){this.subscription=new xw;this.videoState=new L("stopped");this.textTracksManager=new Ee;this.manifests$=new $u([]);this.liveOffset=new Ye;this.manifestStartTime$=new $u(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let u=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(a?.to!=="paused"&&u.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(u.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?I(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),I(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):a?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else a?.to==="paused"&&(I(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return gw(t)}};this.params=e,this.video=se(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Pw.INVARIANT,url:this.params.source.url},xs(K(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})=>{t.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Ps.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Ps.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),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(Y(this.params.source.url)),this.maxSeekBackTime$=new $u(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(c=>c.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:Ps.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=ue(this.video),s=(o,c)=>this.subscription.add(o.subscribe(c,r));s(a.ended$,e.endedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(oe(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ie(this.video,t.playbackRate,a.playbackRateState$,r)),s(Pe(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(Tw(),Kb(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),c=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&zb(u.to)){let l=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let p=this.manifests$.getValue().find(h=>h.id===l);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Y(p.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),c&&c.from==="changing_manifest"&&this.videoState.setState(c.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(a.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(Sw({startTime:this.manifestStartTime$.pipe(yw(zb)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:c})=>this.params.output.liveTime$.next(o+c*1e3),r)),this.subscription.add(this.manifests$.pipe(Kb(o=>o.map(({id:c,quality:u,size:d,bandwidth:l,fps:p})=>({id:c,quality:u,size:d,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,r));let n=Iw(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ew(["init"])).pipe(vw(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ne(this.video)}prepare(){let e=this.selectManifest();if(As(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:c}=t?.to??r??{};for(let[u,d]of[[o,"mq"],[c,"lq"]]){let l=String(parseFloat(u||""));d&&u&&a.searchParams.set(d,l)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=K(a.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),ku(n).then(o=>{if(!As(o))this.maxSeekBackTime$.next(o);else{let c=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(As(c)||!isFinite(c))try{Ke(n).then(u=>u.text()).then(u=>{let d=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(u)?.[1];if(d){let l=new URL(d,n).toString();ku(l).then(p=>{As(p)||this.maxSeekBackTime$.next(p)})}})}catch{}}})}playIfAllowed(){le(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ps.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}};import{assertNever as Aw,debounce as kw,ErrorCategory as Lu,fromEvent as Mu,isNonNullable as ww,isNullable as Rw,map as Jb,merge as Xb,observableFrom as Zb,Subscription as $w,ValueSubject as Lw,VideoQuality as Mw,clientChecker as Cw}from"@vkontakte/videoplayer-shared";var Ki=class{constructor(e){this.subscription=new $w;this.videoState=new L("stopped");this.textTracksManager=new Ee;this.manifests$=new Lw([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let u=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:l}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:l*1e3,forcePrecise:!0});return}switch(a?.to!=="paused"&&u.state==="requested"&&this.seek(u.position),t){case"ready":r==="ready"?I(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):a?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):a?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return Aw(t)}};this.params=e,this.video=se(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Mw.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(Y(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),xs(K(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Lu.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(c=>c.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:Lu.WTF,message:"HlsProvider internal logic error",thrown:o})},a=ue(this.video),s=(o,c)=>this.subscription.add(o.subscribe(c));if(s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(Jb(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Fe(this.video,t.isLooped,r)),this.subscription.add(oe(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ie(this.video,t.playbackRate,a.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),c=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&ww(u.to)){let l=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let p=this.manifests$.getValue().find(h=>h.id===l);if(p){this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Y(p.url));let h=this.params.desiredState.playbackRate.getState(),m=this.params.output.element$.getValue()?.playbackRate;if(h!==m){let b=this.params.output.element$.getValue();b&&(this.params.desiredState.playbackRate.setState(h),b.playbackRate=h)}}}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),c&&c.from==="changing_manifest"&&this.videoState.setState(c.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(Jb(o=>o.map(({id:c,quality:u,size:d,bandwidth:l,fps:p})=>({id:c,quality:u,size:d,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,r)),!Cw.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Xb(Mu(o,"addtrack"),Mu(o,"removetrack"),Mu(o,"change"),Zb(["init"])).subscribe(()=>{for(let c=0;c<o.length;c++)o[c].mode="hidden"},r))}let n=Xb(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Zb(["init"])).pipe(kw(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ne(this.video)}prepare(){let e=this.selectManifest();if(Rw(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:s,min:n}=t?.to??r??{};for(let[o,c]of[[s,"mq"],[n,"lq"]]){let u=String(parseFloat(o||""));c&&o&&a.searchParams.set(c,u)}}this.video.setAttribute("src",a.toString()),this.video.load()}playIfAllowed(){le(this.video).then(e=>{e||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Lu.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as Dw,assertNonNullable as eg,debounce as Bw,ErrorCategory as tg,isHigher as Vw,isHigherOrEqual as Ow,isInvariantQuality as rg,isLowerOrEqual as _w,isNonNullable as Nw,merge as Fw,observableFrom as qw,Subscription as Uw,map as Hw}from"@vkontakte/videoplayer-shared";var Ji=class{constructor(e){this.subscription=new Uw;this.videoState=new L("stopped");this.trackUrls={};this.textTracksManager=new Ee;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:c}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0}),n.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[n.to.id]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(r?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?I(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;default:return Dw(e)}};this.params=e,this.video=se(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,r],a)=>{let s=a.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:tg.WTF,message:"MpegProvider internal logic error",thrown:o})},a=ue(this.video),s=(o,c)=>this.subscription.add(o.subscribe(c,r));s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(Hw(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Fe(this.video,t.isLooped,r)),this.subscription.add(oe(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ie(this.video,t.playbackRate,a.playbackRateState$,r)),s(Pe(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&Nw(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(),u=this.params.output.element$.getValue()?.playbackRate;if(c!==u){let d=this.params.output.element$.getValue();d&&(this.params.desiredState.playbackRate.setState(c),d.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=Fw(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,qw(["init"])).pipe(Bw(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),ne(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;eg(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];eg(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ni(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Y(t))}playIfAllowed(){le(this.video).then(e=>{e||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:tg.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){let t,r=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){let a=Object.values(this.trackUrls).find(o=>!rg(o.track.quality)&&_w(o.track.quality,e))?.track,s=this.params.desiredState.videoTrack.getState()?.id,n=this.trackUrls[s??"0"]?.track;if(a&&n&&Ow(n.quality,a.quality)&&(t=a),!t){let o=Object.values(this.trackUrls).filter(u=>!rg(u.track.quality)&&Vw(u.track.quality,e)),c=o.length;c&&(t=o[c-1].track)}t&&(r=t.quality)}else if(!e){let a=Object.values(this.trackUrls).map(s=>s.track);t=lt(a,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};import{assertNever as ag,debounce as Yw,merge as sg,observableFrom as Qw,Subscription as zw,map as ng,ValueSubject as Kw,ErrorCategory as Du,VideoQuality as Jw}from"@vkontakte/videoplayer-shared";import{ErrorCategory as jw}from"@vkontakte/videoplayer-shared";var ig=["stun:videostun.mycdn.me:80"],Gw=1e3,Ww=3,Cu=()=>null,ks=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=Cu;this.externalStopCallback=Cu;this.externalErrorCallback=Cu;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:ig}]};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:jw.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),Gw)}normalizeOptions(e={}){let t={stunServerList:ig,maxRetryNumber:Ww,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Xi=class{constructor(e){this.videoState=new L("stopped");this.maxSeekBackTime$=new Kw(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;default:return ag(e)}};this.subscription=new zw,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=se(e.container,e.tuning),this.liveStreamClient=new ks(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.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),ne(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Du.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};sg(this.videoState.stateChangeStarted$.pipe(ng(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ng(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=ue(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(a.timeUpdate$,e.liveTime$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(Pe(this.video),this.params.output.elementVisible$),this.subscription.add(a.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(a.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(oe(this.video,t.volume,a.volumeState$,r)).add(a.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return ag(n.to)}},r)).add(sg(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Qw(["init"])).pipe(Yw(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Y(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:Jw.INVARIANT}),this.video.srcObject=e,I(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Du.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){le(this.video).then(e=>{e||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Du.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Zi=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 ra,assertNonNullable as ht,ErrorCategory as Rs,filter as aR,isNonNullable as pg,isNullable as sR,map as nR,merge as oR,once as uR,Subject as ge,Subscription as hg,ValueSubject as M,flattenObject as fg}from"@vkontakte/videoplayer-shared";import{Observable as Xw,map as og,Subscription as Zw,Subject as eR}from"@vkontakte/videoplayer-shared";var ug=i=>new Xw(e=>{let t=new Zw,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(og(({from:u,to:d})=>`${u}-${d}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe(og(({type:u})=>u!==void 0)),n=new eR,o=0,c="unknown";return t.add(r.subscribe(u=>{o&&window.clearTimeout(o),c=u,o=window.setTimeout(()=>n.next(u),i.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(o),c="unknown",o=0})),t.add(s.subscribe(u=>{o&&(window.clearTimeout(o),o=0,u&&(o=window.setTimeout(()=>n.next(c),i.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as cg,Subscription as tR,combine as rR,filter as lg,once as dg}from"@vkontakte/videoplayer-shared";var ea=null,ws=null;function Bu(){return ea||(ea=new(window.AudioContext||window.webkitAudioContext)),ws||(ws=new GainNode(ea,{gain:1}),ws.connect(ea.destination)),{audioCtx:ea,gainNode:ws}}import{clientChecker as iR}from"@vkontakte/videoplayer-shared";var ta=class i{constructor(e,t,r,a,s){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=a;this.subscriptions=new tR;this.lastAudioContextResumeId=0;!s||!this.isSupported()||a===1||this.subscriptions.add(this.provider$.pipe(lg(n=>!!n.type),dg()).subscribe(({type:n})=>this.subscribe(n)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){iR.isSafari&&e!=="MPEG"||this.subscriptions.add(rR({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(lg(({playbackState:t,video:r,volume:{muted:a,volume:s}})=>t==="playing"&&!!r&&!a&&!!s),dg()).subscribe(({video:t})=>this.initAudioContextOnce(t)))}isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){let{volumeMultiplier:t}=this,{audioCtx:r,gainNode:a}=Bu(),s=(Math.random()+1)*999999;this.lastAudioContextResumeId=s,r.resume().then(()=>{if(s!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${i.errorId} destroyed`);a.gain.value=t;try{new MediaElementAudioSourceNode(r,{mediaElement:e}).connect(a)}catch(n){this.volumeMultiplierError$.next({id:i.errorId,category:cg.VIDEO_PIPELINE,message:n?.message??"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:n})}}).catch(n=>{this.volumeMultiplierError$.next({id:i.errorId,category:cg.VIDEO_PIPELINE,message:n?.message??"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){let{gainNode:e}=Bu();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};var cR={chunkDuration:5e3,maxParallelRequests:5},ia=class{constructor(e){this.current$=new M({type:void 0});this.providerError$=new ge;this.noAvailableProvidersError$=new ge;this.volumeMultiplierError$=new ge;this.providerOutput={position$:new M(0),duration$:new M(1/0),volume$:new M({muted:!1,volume:1}),availableVideoStreams$:new M([]),currentVideoStream$:new M(void 0),availableVideoTracks$:new M([]),currentVideoTrack$:new M(void 0),availableAudioStreams$:new M([]),currentAudioStream$:new M(void 0),availableAudioTracks$:new M([]),currentVideoSegmentLength$:new M(0),currentAudioSegmentLength$:new M(0),isAudioAvailable$:new M(!0),autoVideoTrackLimitingAvailable$:new M(!1),autoVideoTrackLimits$:new M(void 0),currentBuffer$:new M(void 0),isBuffering$:new M(!0),error$:new ge,warning$:new ge,willSeekEvent$:new ge,seekedEvent$:new ge,loopedEvent$:new ge,endedEvent$:new ge,firstBytesEvent$:new ge,loadedMetadataEvent$:new ge,firstFrameEvent$:new ge,canplay$:new ge,isLive$:new M(void 0),isLowLatency$:new M(!1),canChangePlaybackSpeed$:new M(!0),liveTime$:new M(void 0),liveBufferTime$:new M(void 0),availableTextTracks$:new M([]),currentTextTrack$:new M(void 0),hostname$:new M(void 0),httpConnectionType$:new M(void 0),httpConnectionReused$:new M(void 0),inPiP$:new M(!1),inFullscreen$:new M(!1),element$:new M(void 0),elementVisible$:new M(!0),availableSources$:new M(void 0),is3DVideo$:new M(!1),playbackState$:new M("")};this.subscription=new hg;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=Cm([...Bm(this.params.tuning),...Dm(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>pg(e.sources[o])),{forceFormat:r,formatsToAvoid:a}=this.params.tuning,s=[];r?s=[r]:a.length?s=[...t.filter(o=>!a.includes(o)),...t.filter(o=>a.includes(o))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",fg(s)),this.screenFormatsIterator=new Zi(s);let n=[...Zo(!0),...Zo(!1)];this.chromecastFormatsIterator=new Zi(n.filter(o=>pg(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new ta(this.providerOutput,this.current$,this.volumeMultiplierError$,this.params.volumeMultiplier??1,this.params.tuning.useVolumeMultiplier)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager.destroy(),this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(sR(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:Rs.WTF,message:"Failed to create provider",thrown:a})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),a=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:a?r.position:t,forcePrecise:a?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return ra(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:a}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),c=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return ht(o),new Gi({...n,source:o,sourceHls:c})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return ht(o),new Wi({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return ht(o),mr||!this.params.tuning.useHlsJs?new Ki({...n,source:o}):new Qi({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return ht(o),new zi({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return ht(o),new Ji({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return ht(o),new Pm({...n,source:o,config:{...cR,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return ht(o),new Xi({container:r,source:o,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return ra(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:a,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return ht(o),new Zr({connection:o,meta:s,container:r,source:t,format:e,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return ra(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return ra(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 ra(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=a=>{let s=new URL(a);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:r(e.url)}}return(0,mg.default)(Object.entries(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new hg,t=!1,r=0;return e.add(oR(this.providerOutput.error$,ug({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(nR(a=>({id:`ProviderHangup:${a}`,category:Rs.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let a=this.params.desiredState.playbackState.transitionEnded$.pipe(aR(({to:s})=>s==="playing"),uR()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{let s=this.current$.getValue().destination,n={error:a,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=a.category===Rs.NETWORK,c=a.category===Rs.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=r<this.params.tuning.providerErrorLimit&&!c,l=u&&!c&&(o&&t||!d);n={...n,isNetworkError:o,isFatalError:c,haveFailoverHost:u,tryFailover:l,canReinitProvider:d},l?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(r++,this.reinitProvider()):this.switchToNextProvider(s??"SCREEN")}this.tracer.error("providerError",fg(n))})),e}};import{fromEvent as $s,once as lR,combine as dR,Subscription as bg,ValueSubject as Vu,map as pR,filter as hR,isNonNullable as Ls,now as Se,safeStorage as Ou}from"@vkontakte/videoplayer-shared";var fR=5e3,gg="one_video_throughput",Sg="one_video_rtt",aa=window.navigator.connection,vg=()=>{let i=aa?.downlink;if(Ls(i)&&i!==10)return i*1e3},yg=()=>{let i=aa?.rtt;if(Ls(i)&&i!==3e3)return i},Tg=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},_u=class i{constructor(e){this.subscription=new bg;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=i.load(gg)||(e.useBrowserEstimation?vg():void 0)||fR,r=i.load(Sg)??(e.useBrowserEstimation?yg():void 0)??0;if(this.throughput$=new Vu(t),this.rtt$=new Vu(r),this.rttAdjustedThroughput$=new Vu(Tg(t,r,e.rttPenaltyRequestSize)),this.throughput=Nt.getSmoothedValue(t,-1,e),this.rtt=Nt.getSmoothedValue(r,1,e),e.useBrowserEstimation){let a=()=>{let n=vg();n&&this.throughput.next(n);let o=yg();Ls(o)&&this.rtt.next(o)};aa&&"onchange"in aa&&this.subscription.add($s(aa,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{Ou.set(gg,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{Ou.set(Sg,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(dR({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(pR(({throughput:a,rtt:s})=>Tg(a,s,e.rttPenaltyRequestSize)),hR(a=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(a-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=Se(),a=new bg;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add($s(e,"progress").pipe(lR()).subscribe(s=>{t=s.loaded,r=Se()}));break;case 1:case 0:a.add($s(e,"loadstart").subscribe(()=>{t=0,r=Se()}));break}a.add($s(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Se(),c=n-t,u=o-r;this.addRawSpeed(c,u,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let a=0,s=Se(),n=0,o=Se(),c=d=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},u=async({done:d,value:l})=>{if(d)!t&&this.addRawSpeed(a,Se()-s,1),this.concurrentDownloads.delete(e);else if(l){if(t){let p=Se();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-s;m&&this.addRawSpeed(n,m,1,t),n=l.byteLength,s=Se()}else n+=l.byteLength;o=Se()}else a+=l.byteLength,n+=l.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Se()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Se()-o,this.concurrentDownloads.size),n=0,o=Se());await r?.read().then(u,c)}};this.concurrentDownloads.add(e),r?.read().then(u,c)}addRawSpeed(e,t,r=1,a=!1){if(i.sanityCheck(e,t,a)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let a=e*8/t;return!(!a||!isFinite(a)||a>1e6||a<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){let t=Ou.get(e);if(Ls(t))return parseInt(t,10)??void 0}},Ig=_u;import{fillWithDefault as mR,VideoQuality as Eg}from"@vkontakte/videoplayer-shared";var xg={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:7,bitrateFactorAtFullBuffer:1.2,bitrateAudioFactorAtFullBuffer:5,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:Eg.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Eg.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,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance: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,useDashAbortPartiallyFedSegment:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewPartialSegmentFeeding:!1,useSeparateAudioVideoABR:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1},Pg=i=>({...mR(i,xg),configName:[...i.configName??[],...xg.configName]});import{assertNonNullable as Ms,combine as ft,ErrorCategory as Cs,filter as ee,filterChanged as V,fromEvent as Fu,isNonNullable as IR,isNullable as ER,Logger as xR,map as C,mapTo as Rg,merge as mt,now as Ds,once as et,Subject as F,Subscription as $g,tap as Lg,ValueSubject as P,isHigher as PR,isInvariantQuality as Mg,flattenObject as bt,throttle as qu,getTraceSubscriptionMethod as Cg}from"@vkontakte/videoplayer-shared";import{merge as bR,map as gR,filter as Ag,isNonNullable as SR}from"@vkontakte/videoplayer-shared";var Nu=({seekState:i,position$:e})=>bR(i.stateChangeEnded$.pipe(gR(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),Ag(SR)),e.pipe(Ag(()=>i.getState().state==="none")));import{assertNonNullable as vR}from"@vkontakte/videoplayer-shared";var kg=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return vR(e,`Wrong container or containerId {${i.container}}`),e};import{filter as yR,once as TR}from"@vkontakte/videoplayer-shared";var wg=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(yR(a=>a.length>0),TR()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t?.getValue().find(r))&&e.startTransitionTo(i)};var Bs=class{constructor(e={configName:[]},t){this.subscription=new $g;this.logger=new xR;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 F,ready$:new F,started$:new F,playing$:new F,paused$:new F,stopped$:new F,willStart$:new F,willResume$:new F,willPause$:new F,willStop$:new F,willDestruct$:new F,watchCoverageRecord$:new F,watchCoverageLive$:new F,managedError$:new F,fatalError$:new F,ended$:new F,looped$:new F,seeked$:new F,willSeek$:new F,firstBytes$:new F,loadedMetadata$:new F,firstFrame$:new F,canplay$:new F,log$:new F};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:am};if(this.initLogs(),this.tuning=Pg(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new pa({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Ig(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,a,s)=>{let n=Reflect.get(r,a,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(c){let u=o.map(p=>JSON.stringify(p,(h,m)=>{let b=typeof m;return["number","string","boolean"].includes(b)?m:m===null?null:`<${b}>`})),d=`Player.${String(a)}`,l=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:Cs.WTF,message:l,thrown:c}),c}}}})}initVideo(e){return this.config=e,this.tracer.log("initVideo",bt(e)),this.domContainer=kg(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new ia({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end()}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&&!ci()?(this.tracer.log("request play from hidden tab"),Fu(document,"visibilitychange").pipe(et()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),a=this.info.isLive$.getValue(),s=e;return e>=r&&!a&&(s=r-.1),this.tracer.log("seekTime",{duration:r,isLive:a,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){Ms(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(ee(r=>r.length>0),et()).subscribe(r=>{this.setVideoTrackIdByQuality(r,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",bt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){Ms(this.providerContainer);let t=this.providerContainer?.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",bt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return wg(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let a=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:a.x+s.x,y:a.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(ER(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return IR(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:a})=>r||a||0,0),height:e.reduce((r,{height:a})=>r||a||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(mt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(C(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(ee(({from:e})=>e==="stopped"),et()).subscribe(()=>{this.initedAt=Ds(),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",bt(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Cs.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",bt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(C(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(C(n=>n.destination),V()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(C(n=>n.map(({quality:o})=>o).sort((o,c)=>Mg(o)?1:Mg(c)?-1:PR(c,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let c of n)c.fps&&(o[c.quality]=c.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(V()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(V((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(V((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(V()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(V()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(V()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n??{})})).add(e.providerOutput.currentBuffer$.pipe(C(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(ft({hasLiveOffsetByPaused:mt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(C(n=>n.to),V(),C(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(ft({atLiveEdge:ft({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Nu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(C(({isLive:n,position:o,isLowLatency:c})=>{let u=this.getActiveLiveDelay(c);return n&&Math.abs(o)<u/1e3}),V(),Lg(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(C(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(ft({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(C(({isLive:n,position:o,duration:c})=>n&&(Math.abs(c)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),V(),Lg(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(C(n=>n.muted),V()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(C(n=>n.volume),V()).subscribe(this.info.volume$)).add(Nu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(mt(e.providerOutput.endedEvent$.pipe(Rg(!0)),e.providerOutput.seekedEvent$.pipe(Rg(!1))).pipe(V()).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(C(n=>({id:n?`No${n}`:"NoProviders",category:Cs.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(),C(n=>n??Ds()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(et(),C(()=>Ds()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(et(),C(()=>Ds()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new P(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new P(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(ee(({to:n})=>n==="playing"),et()).subscribe(()=>r.next(!1)));let a=0,s=mt(e.providerOutput.isBuffering$,t,r).pipe(C(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),V());this.subscription.add(s.subscribe(n=>{n?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})),this.subscription.add(mt(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(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(),c=e.providerOutput.element$.getValue(),u=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue(),l;d==="CONNECTED"?l="second_screen":c?u?n?l="pip":o?l="fullscreen":l="inline":l="invisible":l="none",this.info.surface$.getValue()!==l&&this.info.surface$.next(l)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(C(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new $g;this.subscription.add(t),this.subscription.add(e.current$.pipe(V((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ee(r=>r.length>0),et()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){let t,r=this.desiredState.videoTrack.getState()?.quality;r&&(t=e.find(({quality:a})=>a===r),t||this.setAutoQuality(!0)),t||(t=lt(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(C(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(C(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;Ms(this.providerContainer),Ms(e),im(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>rm(t)),this.providerContainer.current$.subscribe(({type:t})=>ii("provider",t)),e.duration$.subscribe(t=>ii("duration",t)),e.availableVideoTracks$.pipe(ee(t=>!!t.length),et()).subscribe(t=>ii("tracks",t)),this.events.fatalError$.subscribe(new X("fatalError")),this.events.managedError$.subscribe(new X("managedError")),e.position$.subscribe(new X("position")),e.currentVideoTrack$.pipe(C(t=>t?.quality)).subscribe(new X("quality")),this.info.currentBuffer$.subscribe(new X("buffer")),e.isBuffering$.subscribe(new X("isBuffering"))].forEach(t=>this.subscription.add(t)),ii("codecs",Mm())}initTracerSubscription(){let e=Cg(this.tracer.log.bind(this.tracer)),t=Cg(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(V()).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(ft({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(ee(({currentQuality:r,videoBitrate:a})=>!!r&&!!a),V((r,a)=>r.currentQuality===a.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(ee(r=>r>0),V()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(ee(r=>r>0),V()).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(ft({currentBuffer:this.info.currentBuffer$.pipe(ee(r=>r.end>0),V((r,a)=>r.end===a.end&&r.start===a.start)),position:this.info.position$.pipe(V())}).pipe(qu(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(V()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(V()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(V()).subscribe(e("canChangePlaybackSpeed"))).add(ft({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(ee(({liveTime:r,liveBufferTime:a})=>!!r&&!!a),qu(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(V(),ee(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(V(),ee(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(V()).subscribe(e("muted"))).add(this.info.volume$.pipe(V()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(V(),ee(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(ft({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(ee(({throughputEstimation:r,rtt:a})=>!!r&&!!a),qu(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(V(),ee(r=>r===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},r=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Cs.DOM,message:String(a)})})};this.subscription.add(mt(Fu(document,"visibilitychange"),Fu(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let a=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!e?.released;a&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(a=>a.quality===t);this.tracer.log("setVideoTrackIdByQuality",bt({quality:t,availableTracks:bt(e),track:bt(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as uj,Observable as cj,Subject as lj,ValueSubject as dj,VideoQuality as pj}from"@vkontakte/videoplayer-shared";var hj=`@vkontakte/videoplayer-core@${ju}`;export{la as ChromecastState,Hs as HttpConnectionType,cj as Observable,ie as PlaybackState,Bs as Player,hj as SDK_VERSION,lj as Subject,uj as Subscription,js as Surface,ju as VERSION,dj as ValueSubject,at as VideoFormat,pj as VideoQuality};
|