@vkontakte/videoplayer-core 2.0.108-dev.7ca5c32c.0 → 2.0.108-dev.9969cb23.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 +41 -20
- 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 +3 -3
- package/types/player/types.d.ts +5 -6
- package/types/providers/DashProvider/baseDashProvider.d.ts +3 -2
- package/types/providers/DashProvider/lib/LiveTextManager.d.ts +22 -0
- package/types/providers/DashProvider/lib/buffer.d.ts +3 -0
- package/types/providers/DashProvider/lib/player.d.ts +3 -1
- package/types/providers/DashProvider/lib/types.d.ts +6 -0
- package/types/providers/DashProvider/lib/utils.d.ts +3 -5
- package/types/utils/autoSelectTrack.d.ts +29 -0
- package/types/utils/tuningConfig.d.ts +6 -0
- 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.9969cb23.0
|
|
3
|
+
* Mon, 09 Sep 2024 08:50:20 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-108/doc/
|
|
5
5
|
*/
|
|
6
|
-
var DS=Object.create;var Fu=Object.defineProperty;var OS=Object.getOwnPropertyDescriptor;var BS=Object.getOwnPropertyNames;var VS=Object.getPrototypeOf,_S=Object.prototype.hasOwnProperty;var f=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var NS=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of BS(e))!_S.call(i,a)&&a!==t&&Fu(i,a,{get:()=>e[a],enumerable:!(r=OS(e,a))||r.enumerable});return i};var Ve=(i,e,t)=>(t=i!=null?DS(VS(i)):{},NS(e||!i||!i.__esModule?Fu(t,"default",{value:i,enumerable:!0}):t,i));var he=f((VR,Yu)=>{"use strict";Yu.exports=function(i){try{return!!i()}catch{return!0}}});var wr=f((_R,zu)=>{"use strict";var WS=he();zu.exports=!WS(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var ie=f((NR,Xu)=>{"use strict";var Ku=wr(),Ju=Function.prototype,Gs=Ju.call,YS=Ku&&Ju.bind.bind(Gs,Gs);Xu.exports=Ku?YS:function(i){return function(){return Gs.apply(i,arguments)}}});var Qt=f((FR,el)=>{"use strict";var Zu=ie(),zS=Zu({}.toString),KS=Zu("".slice);el.exports=function(i){return KS(zS(i),8,-1)}});var rl=f((qR,tl)=>{"use strict";var JS=ie(),XS=he(),ZS=Qt(),Qs=Object,eg=JS("".split);tl.exports=XS(function(){return!Qs("z").propertyIsEnumerable(0)})?function(i){return ZS(i)==="String"?eg(i,""):Qs(i)}:Qs});var Wt=f((UR,il)=>{"use strict";il.exports=function(i){return i==null}});var Rr=f((HR,al)=>{"use strict";var tg=Wt(),rg=TypeError;al.exports=function(i){if(tg(i))throw new rg("Can't call method on "+i);return i}});var Yt=f((jR,sl)=>{"use strict";var ig=rl(),ag=Rr();sl.exports=function(i){return ig(ag(i))}});var Ws=f((GR,nl)=>{"use strict";nl.exports=function(){}});var Tt=f((QR,ol)=>{"use strict";ol.exports={}});var H=f((Ys,ul)=>{"use strict";var Lr=function(i){return i&&i.Math===Math&&i};ul.exports=Lr(typeof globalThis=="object"&&globalThis)||Lr(typeof window=="object"&&window)||Lr(typeof self=="object"&&self)||Lr(typeof global=="object"&&global)||Lr(typeof Ys=="object"&&Ys)||function(){return this}()||Function("return this")()});var U=f((WR,ll)=>{"use strict";var zs=typeof document=="object"&&document.all;ll.exports=typeof zs>"u"&&zs!==void 0?function(i){return typeof i=="function"||i===zs}:function(i){return typeof i=="function"}});var pl=f((YR,dl)=>{"use strict";var sg=H(),ng=U(),cl=sg.WeakMap;dl.exports=ng(cl)&&/native code/.test(String(cl))});var ge=f((zR,hl)=>{"use strict";var og=U();hl.exports=function(i){return typeof i=="object"?i!==null:og(i)}});var ve=f((KR,fl)=>{"use strict";var ug=he();fl.exports=!ug(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var da=f((JR,bl)=>{"use strict";var lg=H(),ml=ge(),Ks=lg.document,cg=ml(Ks)&&ml(Ks.createElement);bl.exports=function(i){return cg?Ks.createElement(i):{}}});var Js=f((XR,Sl)=>{"use strict";var dg=ve(),pg=he(),hg=da();Sl.exports=!dg&&!pg(function(){return Object.defineProperty(hg("div"),"a",{get:function(){return 7}}).a!==7})});var Xs=f((ZR,gl)=>{"use strict";var fg=ve(),mg=he();gl.exports=fg&&mg(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var _e=f((eL,vl)=>{"use strict";var bg=ge(),Sg=String,gg=TypeError;vl.exports=function(i){if(bg(i))return i;throw new gg(Sg(i)+" is not an object")}});var fe=f((tL,yl)=>{"use strict";var vg=wr(),pa=Function.prototype.call;yl.exports=vg?pa.bind(pa):function(){return pa.apply(pa,arguments)}});var ha=f((rL,Tl)=>{"use strict";Tl.exports={}});var Ue=f((iL,El)=>{"use strict";var Zs=ha(),en=H(),yg=U(),Il=function(i){return yg(i)?i:void 0};El.exports=function(i,e){return arguments.length<2?Il(Zs[i])||Il(en[i]):Zs[i]&&Zs[i][e]||en[i]&&en[i][e]}});var $r=f((aL,xl)=>{"use strict";var Tg=ie();xl.exports=Tg({}.isPrototypeOf)});var zt=f((sL,Al)=>{"use strict";var Ig=H(),Pl=Ig.navigator,kl=Pl&&Pl.userAgent;Al.exports=kl?String(kl):""});var rn=f((nL,Cl)=>{"use strict";var Ml=H(),tn=zt(),wl=Ml.process,Rl=Ml.Deno,Ll=wl&&wl.versions||Rl&&Rl.version,$l=Ll&&Ll.v8,we,fa;$l&&(we=$l.split("."),fa=we[0]>0&&we[0]<4?1:+(we[0]+we[1]));!fa&&tn&&(we=tn.match(/Edge\/(\d+)/),(!we||we[1]>=74)&&(we=tn.match(/Chrome\/(\d+)/),we&&(fa=+we[1])));Cl.exports=fa});var an=f((oL,Ol)=>{"use strict";var Dl=rn(),Eg=he(),xg=H(),Pg=xg.String;Ol.exports=!!Object.getOwnPropertySymbols&&!Eg(function(){var i=Symbol("symbol detection");return!Pg(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&Dl&&Dl<41})});var sn=f((uL,Bl)=>{"use strict";var kg=an();Bl.exports=kg&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var nn=f((lL,Vl)=>{"use strict";var Ag=Ue(),wg=U(),Rg=$r(),Lg=sn(),$g=Object;Vl.exports=Lg?function(i){return typeof i=="symbol"}:function(i){var e=Ag("Symbol");return wg(e)&&Rg(e.prototype,$g(i))}});var Mr=f((cL,_l)=>{"use strict";var Mg=String;_l.exports=function(i){try{return Mg(i)}catch{return"Object"}}});var He=f((dL,Nl)=>{"use strict";var Cg=U(),Dg=Mr(),Og=TypeError;Nl.exports=function(i){if(Cg(i))return i;throw new Og(Dg(i)+" is not a function")}});var Cr=f((pL,Fl)=>{"use strict";var Bg=He(),Vg=Wt();Fl.exports=function(i,e){var t=i[e];return Vg(t)?void 0:Bg(t)}});var Ul=f((hL,ql)=>{"use strict";var on=fe(),un=U(),ln=ge(),_g=TypeError;ql.exports=function(i,e){var t,r;if(e==="string"&&un(t=i.toString)&&!ln(r=on(t,i))||un(t=i.valueOf)&&!ln(r=on(t,i))||e!=="string"&&un(t=i.toString)&&!ln(r=on(t,i)))return r;throw new _g("Can't convert object to primitive value")}});var Re=f((fL,Hl)=>{"use strict";Hl.exports=!0});var Ql=f((mL,Gl)=>{"use strict";var jl=H(),Ng=Object.defineProperty;Gl.exports=function(i,e){try{Ng(jl,i,{value:e,configurable:!0,writable:!0})}catch{jl[i]=e}return e}});var Dr=f((bL,zl)=>{"use strict";var Fg=Re(),qg=H(),Ug=Ql(),Wl="__core-js_shared__",Yl=zl.exports=qg[Wl]||Ug(Wl,{});(Yl.versions||(Yl.versions=[])).push({version:"3.38.0",mode:Fg?"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 cn=f((SL,Jl)=>{"use strict";var Kl=Dr();Jl.exports=function(i,e){return Kl[i]||(Kl[i]=e||{})}});var Or=f((gL,Xl)=>{"use strict";var Hg=Rr(),jg=Object;Xl.exports=function(i){return jg(Hg(i))}});var Le=f((vL,Zl)=>{"use strict";var Gg=ie(),Qg=Or(),Wg=Gg({}.hasOwnProperty);Zl.exports=Object.hasOwn||function(e,t){return Wg(Qg(e),t)}});var dn=f((yL,ec)=>{"use strict";var Yg=ie(),zg=0,Kg=Math.random(),Jg=Yg(1 .toString);ec.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+Jg(++zg+Kg,36)}});var J=f((TL,rc)=>{"use strict";var Xg=H(),Zg=cn(),tc=Le(),ev=dn(),tv=an(),rv=sn(),Kt=Xg.Symbol,pn=Zg("wks"),iv=rv?Kt.for||Kt:Kt&&Kt.withoutSetter||ev;rc.exports=function(i){return tc(pn,i)||(pn[i]=tv&&tc(Kt,i)?Kt[i]:iv("Symbol."+i)),pn[i]}});var nc=f((IL,sc)=>{"use strict";var av=fe(),ic=ge(),ac=nn(),sv=Cr(),nv=Ul(),ov=J(),uv=TypeError,lv=ov("toPrimitive");sc.exports=function(i,e){if(!ic(i)||ac(i))return i;var t=sv(i,lv),r;if(t){if(e===void 0&&(e="default"),r=av(t,i,e),!ic(r)||ac(r))return r;throw new uv("Can't convert object to primitive value")}return e===void 0&&(e="number"),nv(i,e)}});var hn=f((EL,oc)=>{"use strict";var cv=nc(),dv=nn();oc.exports=function(i){var e=cv(i,"string");return dv(e)?e:e+""}});var It=f(lc=>{"use strict";var pv=ve(),hv=Js(),fv=Xs(),ma=_e(),uc=hn(),mv=TypeError,fn=Object.defineProperty,bv=Object.getOwnPropertyDescriptor,mn="enumerable",bn="configurable",Sn="writable";lc.f=pv?fv?function(e,t,r){if(ma(e),t=uc(t),ma(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Sn in r&&!r[Sn]){var a=bv(e,t);a&&a[Sn]&&(e[t]=r.value,r={configurable:bn in r?r[bn]:a[bn],enumerable:mn in r?r[mn]:a[mn],writable:!1})}return fn(e,t,r)}:fn:function(e,t,r){if(ma(e),t=uc(t),ma(r),hv)try{return fn(e,t,r)}catch{}if("get"in r||"set"in r)throw new mv("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Br=f((PL,cc)=>{"use strict";cc.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var Jt=f((kL,dc)=>{"use strict";var Sv=ve(),gv=It(),vv=Br();dc.exports=Sv?function(i,e,t){return gv.f(i,e,vv(1,t))}:function(i,e,t){return i[e]=t,i}});var ba=f((AL,hc)=>{"use strict";var yv=cn(),Tv=dn(),pc=yv("keys");hc.exports=function(i){return pc[i]||(pc[i]=Tv(i))}});var Sa=f((wL,fc)=>{"use strict";fc.exports={}});var Tn=f((RL,Sc)=>{"use strict";var Iv=pl(),bc=H(),Ev=ge(),xv=Jt(),gn=Le(),vn=Dr(),Pv=ba(),kv=Sa(),mc="Object already initialized",yn=bc.TypeError,Av=bc.WeakMap,ga,Vr,va,wv=function(i){return va(i)?Vr(i):ga(i,{})},Rv=function(i){return function(e){var t;if(!Ev(e)||(t=Vr(e)).type!==i)throw new yn("Incompatible receiver, "+i+" required");return t}};Iv||vn.state?($e=vn.state||(vn.state=new Av),$e.get=$e.get,$e.has=$e.has,$e.set=$e.set,ga=function(i,e){if($e.has(i))throw new yn(mc);return e.facade=i,$e.set(i,e),e},Vr=function(i){return $e.get(i)||{}},va=function(i){return $e.has(i)}):(Et=Pv("state"),kv[Et]=!0,ga=function(i,e){if(gn(i,Et))throw new yn(mc);return e.facade=i,xv(i,Et,e),e},Vr=function(i){return gn(i,Et)?i[Et]:{}},va=function(i){return gn(i,Et)});var $e,Et;Sc.exports={set:ga,get:Vr,has:va,enforce:wv,getterFor:Rv}});var In=f((LL,Tc)=>{"use strict";var Lv=wr(),yc=Function.prototype,gc=yc.apply,vc=yc.call;Tc.exports=typeof Reflect=="object"&&Reflect.apply||(Lv?vc.bind(gc):function(){return vc.apply(gc,arguments)})});var En=f(($L,Ic)=>{"use strict";var $v=Qt(),Mv=ie();Ic.exports=function(i){if($v(i)==="Function")return Mv(i)}});var kc=f(Pc=>{"use strict";var Ec={}.propertyIsEnumerable,xc=Object.getOwnPropertyDescriptor,Cv=xc&&!Ec.call({1:2},1);Pc.f=Cv?function(e){var t=xc(this,e);return!!t&&t.enumerable}:Ec});var Rc=f(wc=>{"use strict";var Dv=ve(),Ov=fe(),Bv=kc(),Vv=Br(),_v=Yt(),Nv=hn(),Fv=Le(),qv=Js(),Ac=Object.getOwnPropertyDescriptor;wc.f=Dv?Ac:function(e,t){if(e=_v(e),t=Nv(t),qv)try{return Ac(e,t)}catch{}if(Fv(e,t))return Vv(!Ov(Bv.f,e,t),e[t])}});var xn=f((DL,Lc)=>{"use strict";var Uv=he(),Hv=U(),jv=/#|\.prototype\./,_r=function(i,e){var t=Qv[Gv(i)];return t===Yv?!0:t===Wv?!1:Hv(e)?Uv(e):!!e},Gv=_r.normalize=function(i){return String(i).replace(jv,".").toLowerCase()},Qv=_r.data={},Wv=_r.NATIVE="N",Yv=_r.POLYFILL="P";Lc.exports=_r});var Nr=f((OL,Mc)=>{"use strict";var $c=En(),zv=He(),Kv=wr(),Jv=$c($c.bind);Mc.exports=function(i,e){return zv(i),e===void 0?i:Kv?Jv(i,e):function(){return i.apply(e,arguments)}}});var ye=f((BL,Dc)=>{"use strict";var Fr=H(),Xv=In(),Zv=En(),ey=U(),ty=Rc().f,ry=xn(),Xt=ha(),iy=Nr(),Zt=Jt(),Cc=Le();Dr();var ay=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 Xv(i,this,arguments)};return e.prototype=i.prototype,e};Dc.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?Fr:a?Fr[t]:Fr[t]&&Fr[t].prototype,o=r?Xt:Xt[t]||Zt(Xt,t,{})[t],l=o.prototype,u,d,c,p,h,m,b,S,v;for(p in e)u=ry(r?p:t+(a?".":"#")+p,i.forced),d=!u&&n&&Cc(n,p),m=o[p],d&&(i.dontCallGetSet?(v=ty(n,p),b=v&&v.value):b=n[p]),h=d&&b?b:e[p],!(!u&&!s&&typeof m==typeof h)&&(i.bind&&d?S=iy(h,Fr):i.wrap&&d?S=ay(h):s&&ey(h)?S=Zv(h):S=h,(i.sham||h&&h.sham||m&&m.sham)&&Zt(S,"sham",!0),Zt(o,p,S),s&&(c=t+"Prototype",Cc(Xt,c)||Zt(Xt,c,{}),Zt(Xt[c],p,h),i.real&&l&&(u||!l[p])&&Zt(l,p,h)))}});var Vc=f((VL,Bc)=>{"use strict";var Pn=ve(),sy=Le(),Oc=Function.prototype,ny=Pn&&Object.getOwnPropertyDescriptor,kn=sy(Oc,"name"),oy=kn&&function(){}.name==="something",uy=kn&&(!Pn||Pn&&ny(Oc,"name").configurable);Bc.exports={EXISTS:kn,PROPER:oy,CONFIGURABLE:uy}});var Nc=f((_L,_c)=>{"use strict";var ly=Math.ceil,cy=Math.floor;_c.exports=Math.trunc||function(e){var t=+e;return(t>0?cy:ly)(t)}});var ya=f((NL,Fc)=>{"use strict";var dy=Nc();Fc.exports=function(i){var e=+i;return e!==e||e===0?0:dy(e)}});var Uc=f((FL,qc)=>{"use strict";var py=ya(),hy=Math.max,fy=Math.min;qc.exports=function(i,e){var t=py(i);return t<0?hy(t+e,0):fy(t,e)}});var jc=f((qL,Hc)=>{"use strict";var my=ya(),by=Math.min;Hc.exports=function(i){var e=my(i);return e>0?by(e,9007199254740991):0}});var Ta=f((UL,Gc)=>{"use strict";var Sy=jc();Gc.exports=function(i){return Sy(i.length)}});var Yc=f((HL,Wc)=>{"use strict";var gy=Yt(),vy=Uc(),yy=Ta(),Qc=function(i){return function(e,t,r){var a=gy(e),s=yy(a);if(s===0)return!i&&-1;var n=vy(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}};Wc.exports={includes:Qc(!0),indexOf:Qc(!1)}});var Jc=f((jL,Kc)=>{"use strict";var Ty=ie(),An=Le(),Iy=Yt(),Ey=Yc().indexOf,xy=Sa(),zc=Ty([].push);Kc.exports=function(i,e){var t=Iy(i),r=0,a=[],s;for(s in t)!An(xy,s)&&An(t,s)&&zc(a,s);for(;e.length>r;)An(t,s=e[r++])&&(~Ey(a,s)||zc(a,s));return a}});var wn=f((GL,Xc)=>{"use strict";Xc.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var ed=f((QL,Zc)=>{"use strict";var Py=Jc(),ky=wn();Zc.exports=Object.keys||function(e){return Py(e,ky)}});var rd=f(td=>{"use strict";var Ay=ve(),wy=Xs(),Ry=It(),Ly=_e(),$y=Yt(),My=ed();td.f=Ay&&!wy?Object.defineProperties:function(e,t){Ly(e);for(var r=$y(t),a=My(t),s=a.length,n=0,o;s>n;)Ry.f(e,o=a[n++],r[o]);return e}});var Rn=f((YL,id)=>{"use strict";var Cy=Ue();id.exports=Cy("document","documentElement")});var Cn=f((zL,cd)=>{"use strict";var Dy=_e(),Oy=rd(),ad=wn(),By=Sa(),Vy=Rn(),_y=da(),Ny=ba(),sd=">",nd="<",$n="prototype",Mn="script",ud=Ny("IE_PROTO"),Ln=function(){},ld=function(i){return nd+Mn+sd+i+nd+"/"+Mn+sd},od=function(i){i.write(ld("")),i.close();var e=i.parentWindow.Object;return i=null,e},Fy=function(){var i=_y("iframe"),e="java"+Mn+":",t;return i.style.display="none",Vy.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(ld("document.F=Object")),t.close(),t.F},Ia,Ea=function(){try{Ia=new ActiveXObject("htmlfile")}catch{}Ea=typeof document<"u"?document.domain&&Ia?od(Ia):Fy():od(Ia);for(var i=ad.length;i--;)delete Ea[$n][ad[i]];return Ea()};By[ud]=!0;cd.exports=Object.create||function(e,t){var r;return e!==null?(Ln[$n]=Dy(e),r=new Ln,Ln[$n]=null,r[ud]=e):r=Ea(),t===void 0?r:Oy.f(r,t)}});var pd=f((KL,dd)=>{"use strict";var qy=he();dd.exports=!qy(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var On=f((JL,fd)=>{"use strict";var Uy=Le(),Hy=U(),jy=Or(),Gy=ba(),Qy=pd(),hd=Gy("IE_PROTO"),Dn=Object,Wy=Dn.prototype;fd.exports=Qy?Dn.getPrototypeOf:function(i){var e=jy(i);if(Uy(e,hd))return e[hd];var t=e.constructor;return Hy(t)&&e instanceof t?t.prototype:e instanceof Dn?Wy:null}});var er=f((XL,md)=>{"use strict";var Yy=Jt();md.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:Yy(i,e,t),i}});var Nn=f((ZL,gd)=>{"use strict";var zy=he(),Ky=U(),Jy=ge(),Xy=Cn(),bd=On(),Zy=er(),eT=J(),tT=Re(),_n=eT("iterator"),Sd=!1,je,Bn,Vn;[].keys&&(Vn=[].keys(),"next"in Vn?(Bn=bd(bd(Vn)),Bn!==Object.prototype&&(je=Bn)):Sd=!0);var rT=!Jy(je)||zy(function(){var i={};return je[_n].call(i)!==i});rT?je={}:tT&&(je=Xy(je));Ky(je[_n])||Zy(je,_n,function(){return this});gd.exports={IteratorPrototype:je,BUGGY_SAFARI_ITERATORS:Sd}});var xa=f((e$,yd)=>{"use strict";var iT=J(),aT=iT("toStringTag"),vd={};vd[aT]="z";yd.exports=String(vd)==="[object z]"});var qr=f((t$,Td)=>{"use strict";var sT=xa(),nT=U(),Pa=Qt(),oT=J(),uT=oT("toStringTag"),lT=Object,cT=Pa(function(){return arguments}())==="Arguments",dT=function(i,e){try{return i[e]}catch{}};Td.exports=sT?Pa:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=dT(e=lT(i),uT))=="string"?t:cT?Pa(e):(r=Pa(e))==="Object"&&nT(e.callee)?"Arguments":r}});var Ed=f((r$,Id)=>{"use strict";var pT=xa(),hT=qr();Id.exports=pT?{}.toString:function(){return"[object "+hT(this)+"]"}});var Ur=f((i$,Pd)=>{"use strict";var fT=xa(),mT=It().f,bT=Jt(),ST=Le(),gT=Ed(),vT=J(),xd=vT("toStringTag");Pd.exports=function(i,e,t,r){var a=t?i:i&&i.prototype;a&&(ST(a,xd)||mT(a,xd,{configurable:!0,value:e}),r&&!fT&&bT(a,"toString",gT))}});var Ad=f((a$,kd)=>{"use strict";var yT=Nn().IteratorPrototype,TT=Cn(),IT=Br(),ET=Ur(),xT=Tt(),PT=function(){return this};kd.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=TT(yT,{next:IT(+!r,t)}),ET(i,a,!1,!0),xT[a]=PT,i}});var Rd=f((s$,wd)=>{"use strict";var kT=ie(),AT=He();wd.exports=function(i,e,t){try{return kT(AT(Object.getOwnPropertyDescriptor(i,e)[t]))}catch{}}});var $d=f((n$,Ld)=>{"use strict";var wT=ge();Ld.exports=function(i){return wT(i)||i===null}});var Cd=f((o$,Md)=>{"use strict";var RT=$d(),LT=String,$T=TypeError;Md.exports=function(i){if(RT(i))return i;throw new $T("Can't set "+LT(i)+" as a prototype")}});var Fn=f((u$,Dd)=>{"use strict";var MT=Rd(),CT=ge(),DT=Rr(),OT=Cd();Dd.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=MT(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch{}return function(a,s){return DT(a),OT(s),CT(a)&&(i?t(a,s):a.__proto__=s),a}}():void 0)});var Gd=f((l$,jd)=>{"use strict";var BT=ye(),VT=fe(),ka=Re(),Ud=Vc(),_T=U(),NT=Ad(),Od=On(),Bd=Fn(),FT=Ur(),qT=Jt(),qn=er(),UT=J(),Vd=Tt(),Hd=Nn(),HT=Ud.PROPER,jT=Ud.CONFIGURABLE,_d=Hd.IteratorPrototype,Aa=Hd.BUGGY_SAFARI_ITERATORS,Hr=UT("iterator"),Nd="keys",jr="values",Fd="entries",qd=function(){return this};jd.exports=function(i,e,t,r,a,s,n){NT(t,e,r);var o=function(v){if(v===a&&p)return p;if(!Aa&&v&&v in d)return d[v];switch(v){case Nd:return function(){return new t(this,v)};case jr:return function(){return new t(this,v)};case Fd:return function(){return new t(this,v)}}return function(){return new t(this)}},l=e+" Iterator",u=!1,d=i.prototype,c=d[Hr]||d["@@iterator"]||a&&d[a],p=!Aa&&c||o(a),h=e==="Array"&&d.entries||c,m,b,S;if(h&&(m=Od(h.call(new i)),m!==Object.prototype&&m.next&&(!ka&&Od(m)!==_d&&(Bd?Bd(m,_d):_T(m[Hr])||qn(m,Hr,qd)),FT(m,l,!0,!0),ka&&(Vd[l]=qd))),HT&&a===jr&&c&&c.name!==jr&&(!ka&&jT?qT(d,"name",jr):(u=!0,p=function(){return VT(c,this)})),a)if(b={values:o(jr),keys:s?p:o(Nd),entries:o(Fd)},n)for(S in b)(Aa||u||!(S in d))&&qn(d,S,b[S]);else BT({target:e,proto:!0,forced:Aa||u},b);return(!ka||n)&&d[Hr]!==p&&qn(d,Hr,p,{name:a}),Vd[e]=p,b}});var Wd=f((c$,Qd)=>{"use strict";Qd.exports=function(i,e){return{value:i,done:e}}});var Hn=f((d$,Xd)=>{"use strict";var GT=Yt(),Un=Ws(),Yd=Tt(),Kd=Tn(),QT=It().f,WT=Gd(),wa=Wd(),YT=Re(),zT=ve(),Jd="Array Iterator",KT=Kd.set,JT=Kd.getterFor(Jd);Xd.exports=WT(Array,"Array",function(i,e){KT(this,{type:Jd,target:GT(i),index:0,kind:e})},function(){var i=JT(this),e=i.target,t=i.index++;if(!e||t>=e.length)return i.target=void 0,wa(void 0,!0);switch(i.kind){case"keys":return wa(t,!1);case"values":return wa(e[t],!1)}return wa([t,e[t]],!1)},"values");var zd=Yd.Arguments=Yd.Array;Un("keys");Un("values");Un("entries");if(!YT&&zT&&zd.name!=="values")try{QT(zd,"name",{value:"values"})}catch{}});var ep=f((p$,Zd)=>{"use strict";var XT=J(),ZT=Tt(),eI=XT("iterator"),tI=Array.prototype;Zd.exports=function(i){return i!==void 0&&(ZT.Array===i||tI[eI]===i)}});var jn=f((h$,rp)=>{"use strict";var rI=qr(),tp=Cr(),iI=Wt(),aI=Tt(),sI=J(),nI=sI("iterator");rp.exports=function(i){if(!iI(i))return tp(i,nI)||tp(i,"@@iterator")||aI[rI(i)]}});var ap=f((f$,ip)=>{"use strict";var oI=fe(),uI=He(),lI=_e(),cI=Mr(),dI=jn(),pI=TypeError;ip.exports=function(i,e){var t=arguments.length<2?dI(i):e;if(uI(t))return lI(oI(t,i));throw new pI(cI(i)+" is not iterable")}});var op=f((m$,np)=>{"use strict";var hI=fe(),sp=_e(),fI=Cr();np.exports=function(i,e,t){var r,a;sp(i);try{if(r=fI(i,"return"),!r){if(e==="throw")throw t;return t}r=hI(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return sp(r),t}});var La=f((b$,dp)=>{"use strict";var mI=Nr(),bI=fe(),SI=_e(),gI=Mr(),vI=ep(),yI=Ta(),up=$r(),TI=ap(),II=jn(),lp=op(),EI=TypeError,Ra=function(i,e){this.stopped=i,this.result=e},cp=Ra.prototype;dp.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=mI(e,r),u,d,c,p,h,m,b,S=function(w){return u&&lp(u,"normal",w),new Ra(!0,w)},v=function(w){return a?(SI(w),o?l(w[0],w[1],S):l(w[0],w[1])):o?l(w,S):l(w)};if(s)u=i.iterator;else if(n)u=i;else{if(d=II(i),!d)throw new EI(gI(i)+" is not iterable");if(vI(d)){for(c=0,p=yI(i);p>c;c++)if(h=v(i[c]),h&&up(cp,h))return h;return new Ra(!1)}u=TI(i,d)}for(m=s?i.next:u.next;!(b=bI(m,u)).done;){try{h=v(b.value)}catch(w){lp(u,"throw",w)}if(typeof h=="object"&&h&&up(cp,h))return h}return new Ra(!1)}});var hp=f((S$,pp)=>{"use strict";var xI=ve(),PI=It(),kI=Br();pp.exports=function(i,e,t){xI?PI.f(i,e,kI(0,t)):i[e]=t}});var fp=f(()=>{"use strict";var AI=ye(),wI=La(),RI=hp();AI({target:"Object",stat:!0},{fromEntries:function(e){var t={};return wI(e,function(r,a){RI(t,r,a)},{AS_ENTRIES:!0}),t}})});var bp=f((y$,mp)=>{"use strict";Hn();fp();var LI=ha();mp.exports=LI.Object.fromEntries});var gp=f((T$,Sp)=>{"use strict";Sp.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 yp=f(()=>{"use strict";Hn();var $I=gp(),MI=H(),CI=Ur(),vp=Tt();for($a in $I)CI(MI[$a],$a),vp[$a]=vp.Array;var $a});var Ip=f((x$,Tp)=>{"use strict";var DI=bp();yp();Tp.exports=DI});var Gn=f((P$,Ep)=>{"use strict";var OI=Ip();Ep.exports=OI});var xp=f(()=>{"use strict"});var Qn=f((w$,Pp)=>{"use strict";var Gr=H(),BI=zt(),VI=Qt(),Ma=function(i){return BI.slice(0,i.length)===i};Pp.exports=function(){return Ma("Bun/")?"BUN":Ma("Cloudflare-Workers")?"CLOUDFLARE":Ma("Deno/")?"DENO":Ma("Node.js/")?"NODE":Gr.Bun&&typeof Bun.version=="string"?"BUN":Gr.Deno&&typeof Deno.version=="object"?"DENO":VI(Gr.process)==="process"?"NODE":Gr.window&&Gr.document?"BROWSER":"REST"}()});var Ca=f((R$,kp)=>{"use strict";var _I=Qn();kp.exports=_I==="NODE"});var wp=f((L$,Ap)=>{"use strict";var NI=It();Ap.exports=function(i,e,t){return NI.f(i,e,t)}});var $p=f(($$,Lp)=>{"use strict";var FI=Ue(),qI=wp(),UI=J(),HI=ve(),Rp=UI("species");Lp.exports=function(i){var e=FI(i);HI&&e&&!e[Rp]&&qI(e,Rp,{configurable:!0,get:function(){return this}})}});var Cp=f((M$,Mp)=>{"use strict";var jI=$r(),GI=TypeError;Mp.exports=function(i,e){if(jI(e,i))return i;throw new GI("Incorrect invocation")}});var Yn=f((C$,Dp)=>{"use strict";var QI=ie(),WI=U(),Wn=Dr(),YI=QI(Function.toString);WI(Wn.inspectSource)||(Wn.inspectSource=function(i){return YI(i)});Dp.exports=Wn.inspectSource});var Fp=f((D$,Np)=>{"use strict";var zI=ie(),KI=he(),Op=U(),JI=qr(),XI=Ue(),ZI=Yn(),Bp=function(){},Vp=XI("Reflect","construct"),zn=/^\s*(?:class|function)\b/,eE=zI(zn.exec),tE=!zn.test(Bp),Qr=function(e){if(!Op(e))return!1;try{return Vp(Bp,[],e),!0}catch{return!1}},_p=function(e){if(!Op(e))return!1;switch(JI(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return tE||!!eE(zn,ZI(e))}catch{return!0}};_p.sham=!0;Np.exports=!Vp||KI(function(){var i;return Qr(Qr.call)||!Qr(Object)||!Qr(function(){i=!0})||i})?_p:Qr});var Up=f((O$,qp)=>{"use strict";var rE=Fp(),iE=Mr(),aE=TypeError;qp.exports=function(i){if(rE(i))return i;throw new aE(iE(i)+" is not a constructor")}});var Kn=f((B$,jp)=>{"use strict";var Hp=_e(),sE=Up(),nE=Wt(),oE=J(),uE=oE("species");jp.exports=function(i,e){var t=Hp(i).constructor,r;return t===void 0||nE(r=Hp(t)[uE])?e:sE(r)}});var Qp=f((V$,Gp)=>{"use strict";var lE=ie();Gp.exports=lE([].slice)});var Yp=f((_$,Wp)=>{"use strict";var cE=TypeError;Wp.exports=function(i,e){if(i<e)throw new cE("Not enough arguments");return i}});var Jn=f((N$,zp)=>{"use strict";var dE=zt();zp.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(dE)});var no=f((F$,ah)=>{"use strict";var me=H(),pE=In(),hE=Nr(),Kp=U(),fE=Le(),ih=he(),Jp=Rn(),mE=Qp(),Xp=da(),bE=Yp(),SE=Jn(),gE=Ca(),io=me.setImmediate,ao=me.clearImmediate,vE=me.process,Xn=me.Dispatch,yE=me.Function,Zp=me.MessageChannel,TE=me.String,Zn=0,Wr={},eh="onreadystatechange",Yr,xt,eo,to;ih(function(){Yr=me.location});var so=function(i){if(fE(Wr,i)){var e=Wr[i];delete Wr[i],e()}},ro=function(i){return function(){so(i)}},th=function(i){so(i.data)},rh=function(i){me.postMessage(TE(i),Yr.protocol+"//"+Yr.host)};(!io||!ao)&&(io=function(e){bE(arguments.length,1);var t=Kp(e)?e:yE(e),r=mE(arguments,1);return Wr[++Zn]=function(){pE(t,void 0,r)},xt(Zn),Zn},ao=function(e){delete Wr[e]},gE?xt=function(i){vE.nextTick(ro(i))}:Xn&&Xn.now?xt=function(i){Xn.now(ro(i))}:Zp&&!SE?(eo=new Zp,to=eo.port2,eo.port1.onmessage=th,xt=hE(to.postMessage,to)):me.addEventListener&&Kp(me.postMessage)&&!me.importScripts&&Yr&&Yr.protocol!=="file:"&&!ih(rh)?(xt=rh,me.addEventListener("message",th,!1)):eh in Xp("script")?xt=function(i){Jp.appendChild(Xp("script"))[eh]=function(){Jp.removeChild(this),so(i)}}:xt=function(i){setTimeout(ro(i),0)});ah.exports={set:io,clear:ao}});var oh=f((q$,nh)=>{"use strict";var sh=H(),IE=ve(),EE=Object.getOwnPropertyDescriptor;nh.exports=function(i){if(!IE)return sh[i];var e=EE(sh,i);return e&&e.value}});var oo=f((U$,lh)=>{"use strict";var uh=function(){this.head=null,this.tail=null};uh.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}}};lh.exports=uh});var dh=f((H$,ch)=>{"use strict";var xE=zt();ch.exports=/ipad|iphone|ipod/i.test(xE)&&typeof Pebble<"u"});var hh=f((j$,ph)=>{"use strict";var PE=zt();ph.exports=/web0s(?!.*chrome)/i.test(PE)});var yh=f((G$,vh)=>{"use strict";var rr=H(),kE=oh(),fh=Nr(),uo=no().set,AE=oo(),wE=Jn(),RE=dh(),LE=hh(),lo=Ca(),mh=rr.MutationObserver||rr.WebKitMutationObserver,bh=rr.document,Sh=rr.process,Da=rr.Promise,ho=kE("queueMicrotask"),tr,co,po,Oa,gh;ho||(zr=new AE,Kr=function(){var i,e;for(lo&&(i=Sh.domain)&&i.exit();e=zr.get();)try{e()}catch(t){throw zr.head&&tr(),t}i&&i.enter()},!wE&&!lo&&!LE&&mh&&bh?(co=!0,po=bh.createTextNode(""),new mh(Kr).observe(po,{characterData:!0}),tr=function(){po.data=co=!co}):!RE&&Da&&Da.resolve?(Oa=Da.resolve(void 0),Oa.constructor=Da,gh=fh(Oa.then,Oa),tr=function(){gh(Kr)}):lo?tr=function(){Sh.nextTick(Kr)}:(uo=fh(uo,rr),tr=function(){uo(Kr)}),ho=function(i){zr.head||tr(),zr.add(i)});var zr,Kr;vh.exports=ho});var Ih=f((Q$,Th)=>{"use strict";Th.exports=function(i,e){try{arguments.length===1?console.error(i):console.error(i,e)}catch{}}});var Ba=f((W$,Eh)=>{"use strict";Eh.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var Pt=f((Y$,xh)=>{"use strict";var $E=H();xh.exports=$E.Promise});var ir=f((z$,wh)=>{"use strict";var ME=H(),Jr=Pt(),CE=U(),DE=xn(),OE=Yn(),BE=J(),Ph=Qn(),VE=Re(),fo=rn(),kh=Jr&&Jr.prototype,_E=BE("species"),mo=!1,Ah=CE(ME.PromiseRejectionEvent),NE=DE("Promise",function(){var i=OE(Jr),e=i!==String(Jr);if(!e&&fo===66||VE&&!(kh.catch&&kh.finally))return!0;if(!fo||fo<51||!/native code/.test(i)){var t=new Jr(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[_E]=r,mo=t.then(function(){})instanceof r,!mo)return!0}return!e&&(Ph==="BROWSER"||Ph==="DENO")&&!Ah});wh.exports={CONSTRUCTOR:NE,REJECTION_EVENT:Ah,SUBCLASSING:mo}});var ar=f((K$,Lh)=>{"use strict";var Rh=He(),FE=TypeError,qE=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw new FE("Bad Promise constructor");e=r,t=a}),this.resolve=Rh(e),this.reject=Rh(t)};Lh.exports.f=function(i){return new qE(i)}});var zh=f(()=>{"use strict";var UE=ye(),HE=Re(),Fa=Ca(),it=H(),ur=fe(),$h=er(),Mh=Fn(),jE=Ur(),GE=$p(),QE=He(),Na=U(),WE=ge(),YE=Cp(),zE=Kn(),Vh=no().set,yo=yh(),KE=Ih(),JE=Ba(),XE=oo(),_h=Tn(),qa=Pt(),To=ir(),Nh=ar(),Ua="Promise",Fh=To.CONSTRUCTOR,ZE=To.REJECTION_EVENT,ex=To.SUBCLASSING,bo=_h.getterFor(Ua),tx=_h.set,sr=qa&&qa.prototype,kt=qa,Va=sr,qh=it.TypeError,So=it.document,Io=it.process,go=Nh.f,rx=go,ix=!!(So&&So.createEvent&&it.dispatchEvent),Uh="unhandledrejection",ax="rejectionhandled",Ch=0,Hh=1,sx=2,Eo=1,jh=2,_a,Dh,nx,Oh,Gh=function(i){var e;return WE(i)&&Na(e=i.then)?e:!1},Qh=function(i,e){var t=e.value,r=e.state===Hh,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,l,u,d;try{a?(r||(e.rejection===jh&&ux(e),e.rejection=Eo),a===!0?l=t:(o&&o.enter(),l=a(t),o&&(o.exit(),d=!0)),l===i.promise?n(new qh("Promise-chain cycle")):(u=Gh(l))?ur(u,l,s,n):s(l)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},Wh=function(i,e){i.notified||(i.notified=!0,yo(function(){for(var t=i.reactions,r;r=t.get();)Qh(r,i);i.notified=!1,e&&!i.rejection&&ox(i)}))},Yh=function(i,e,t){var r,a;ix?(r=So.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),it.dispatchEvent(r)):r={promise:e,reason:t},!ZE&&(a=it["on"+i])?a(r):i===Uh&&KE("Unhandled promise rejection",t)},ox=function(i){ur(Vh,it,function(){var e=i.facade,t=i.value,r=Bh(i),a;if(r&&(a=JE(function(){Fa?Io.emit("unhandledRejection",t,e):Yh(Uh,e,t)}),i.rejection=Fa||Bh(i)?jh:Eo,a.error))throw a.value})},Bh=function(i){return i.rejection!==Eo&&!i.parent},ux=function(i){ur(Vh,it,function(){var e=i.facade;Fa?Io.emit("rejectionHandled",e):Yh(ax,e,i.value)})},nr=function(i,e,t){return function(r){i(e,r,t)}},or=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=sx,Wh(i,!0))},vo=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw new qh("Promise can't be resolved itself");var r=Gh(e);r?yo(function(){var a={done:!1};try{ur(r,e,nr(vo,a,i),nr(or,a,i))}catch(s){or(a,s,i)}}):(i.value=e,i.state=Hh,Wh(i,!1))}catch(a){or({done:!1},a,i)}}};if(Fh&&(kt=function(e){YE(this,Va),QE(e),ur(_a,this);var t=bo(this);try{e(nr(vo,t),nr(or,t))}catch(r){or(t,r)}},Va=kt.prototype,_a=function(e){tx(this,{type:Ua,done:!1,notified:!1,parent:!1,reactions:new XE,rejection:!1,state:Ch,value:void 0})},_a.prototype=$h(Va,"then",function(e,t){var r=bo(this),a=go(zE(this,kt));return r.parent=!0,a.ok=Na(e)?e:!0,a.fail=Na(t)&&t,a.domain=Fa?Io.domain:void 0,r.state===Ch?r.reactions.add(a):yo(function(){Qh(a,r)}),a.promise}),Dh=function(){var i=new _a,e=bo(i);this.promise=i,this.resolve=nr(vo,e),this.reject=nr(or,e)},Nh.f=go=function(i){return i===kt||i===nx?new Dh(i):rx(i)},!HE&&Na(qa)&&sr!==Object.prototype)){Oh=sr.then,ex||$h(sr,"then",function(e,t){var r=this;return new kt(function(a,s){ur(Oh,r,a,s)}).then(e,t)},{unsafe:!0});try{delete sr.constructor}catch{}Mh&&Mh(sr,Va)}UE({global:!0,constructor:!0,wrap:!0,forced:Fh},{Promise:kt});jE(kt,Ua,!1,!0);GE(Ua)});var ef=f((Z$,Zh)=>{"use strict";var lx=J(),Jh=lx("iterator"),Xh=!1;try{Kh=0,xo={next:function(){return{done:!!Kh++}},return:function(){Xh=!0}},xo[Jh]=function(){return this},Array.from(xo,function(){throw 2})}catch{}var Kh,xo;Zh.exports=function(i,e){try{if(!e&&!Xh)return!1}catch{return!1}var t=!1;try{var r={};r[Jh]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch{}return t}});var Po=f((eM,tf)=>{"use strict";var cx=Pt(),dx=ef(),px=ir().CONSTRUCTOR;tf.exports=px||!dx(function(i){cx.all(i).then(void 0,function(){})})});var rf=f(()=>{"use strict";var hx=ye(),fx=fe(),mx=He(),bx=ar(),Sx=Ba(),gx=La(),vx=Po();hx({target:"Promise",stat:!0,forced:vx},{all:function(e){var t=this,r=bx.f(t),a=r.resolve,s=r.reject,n=Sx(function(){var o=mx(t.resolve),l=[],u=0,d=1;gx(e,function(c){var p=u++,h=!1;d++,fx(o,t,c).then(function(m){h||(h=!0,l[p]=m,--d||a(l))},s)}),--d||a(l)});return n.error&&s(n.value),r.promise}})});var sf=f(()=>{"use strict";var yx=ye(),Tx=Re(),Ix=ir().CONSTRUCTOR,Ao=Pt(),Ex=Ue(),xx=U(),Px=er(),af=Ao&&Ao.prototype;yx({target:"Promise",proto:!0,forced:Ix,real:!0},{catch:function(i){return this.then(void 0,i)}});!Tx&&xx(Ao)&&(ko=Ex("Promise").prototype.catch,af.catch!==ko&&Px(af,"catch",ko,{unsafe:!0}));var ko});var nf=f(()=>{"use strict";var kx=ye(),Ax=fe(),wx=He(),Rx=ar(),Lx=Ba(),$x=La(),Mx=Po();kx({target:"Promise",stat:!0,forced:Mx},{race:function(e){var t=this,r=Rx.f(t),a=r.reject,s=Lx(function(){var n=wx(t.resolve);$x(e,function(o){Ax(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var of=f(()=>{"use strict";var Cx=ye(),Dx=ar(),Ox=ir().CONSTRUCTOR;Cx({target:"Promise",stat:!0,forced:Ox},{reject:function(e){var t=Dx.f(this),r=t.reject;return r(e),t.promise}})});var wo=f((lM,uf)=>{"use strict";var Bx=_e(),Vx=ge(),_x=ar();uf.exports=function(i,e){if(Bx(i),Vx(e)&&e.constructor===i)return e;var t=_x.f(i),r=t.resolve;return r(e),t.promise}});var df=f(()=>{"use strict";var Nx=ye(),Fx=Ue(),lf=Re(),qx=Pt(),cf=ir().CONSTRUCTOR,Ux=wo(),Hx=Fx("Promise"),jx=lf&&!cf;Nx({target:"Promise",stat:!0,forced:lf||cf},{resolve:function(e){return Ux(jx&&this===Hx?qx:this,e)}})});var pf=f(()=>{"use strict";zh();rf();sf();nf();of();df()});var bf=f(()=>{"use strict";var Gx=ye(),Qx=Re(),Ha=Pt(),Wx=he(),ff=Ue(),mf=U(),Yx=Kn(),hf=wo(),zx=er(),Lo=Ha&&Ha.prototype,Kx=!!Ha&&Wx(function(){Lo.finally.call({then:function(){}},function(){})});Gx({target:"Promise",proto:!0,real:!0,forced:Kx},{finally:function(i){var e=Yx(this,ff("Promise")),t=mf(i);return this.then(t?function(r){return hf(e,i()).then(function(){return r})}:i,t?function(r){return hf(e,i()).then(function(){throw r})}:i)}});!Qx&&mf(Ha)&&(Ro=ff("Promise").prototype.finally,Lo.finally!==Ro&&zx(Lo,"finally",Ro,{unsafe:!0}));var Ro});var ja=f((bM,Sf)=>{"use strict";var Jx=Ue();Sf.exports=Jx});var vf=f((SM,gf)=>{"use strict";xp();pf();bf();var Xx=ja();gf.exports=Xx("Promise","finally")});var Tf=f((gM,yf)=>{"use strict";var Zx=vf();yf.exports=Zx});var Ga=f((vM,If)=>{"use strict";var eP=Tf();If.exports=eP});var Wf=f(()=>{"use strict";var RP=ye(),LP=Or(),$P=Ta(),MP=ya(),CP=Ws();RP({target:"Array",proto:!0},{at:function(e){var t=LP(this),r=$P(t),a=MP(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});CP("at")});var zf=f((wC,Yf)=>{"use strict";Wf();var DP=ja();Yf.exports=DP("Array","at")});var Jf=f((RC,Kf)=>{"use strict";var OP=zf();Kf.exports=OP});var ti=f((LC,Xf)=>{"use strict";var BP=Jf();Xf.exports=BP});var Fm=f(()=>{"use strict"});var qm=f(()=>{"use strict"});var Hm=f((LB,Um)=>{"use strict";var Qk=ge(),Wk=Qt(),Yk=J(),zk=Yk("match");Um.exports=function(i){var e;return Qk(i)&&((e=i[zk])!==void 0?!!e:Wk(i)==="RegExp")}});var Gm=f(($B,jm)=>{"use strict";var Kk=qr(),Jk=String;jm.exports=function(i){if(Kk(i)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return Jk(i)}});var Wm=f((MB,Qm)=>{"use strict";var Xk=_e();Qm.exports=function(){var i=Xk(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 Km=f((CB,zm)=>{"use strict";var Zk=fe(),eA=Le(),tA=$r(),rA=Wm(),Ym=RegExp.prototype;zm.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in Ym)&&!eA(i,"flags")&&tA(Ym,i)?Zk(rA,i):e}});var Xm=f((DB,Jm)=>{"use strict";var nu=ie(),iA=Or(),aA=Math.floor,au=nu("".charAt),sA=nu("".replace),su=nu("".slice),nA=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,oA=/\$([$&'`]|\d{1,2})/g;Jm.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,l=oA;return a!==void 0&&(a=iA(a),l=nA),sA(s,l,function(u,d){var c;switch(au(d,0)){case"$":return"$";case"&":return i;case"`":return su(e,0,t);case"'":return su(e,n);case"<":c=a[su(d,1,-1)];break;default:var p=+d;if(p===0)return u;if(p>o){var h=aA(p/10);return h===0?u:h<=o?r[h-1]===void 0?au(d,1):r[h-1]+au(d,1):u}c=r[p-1]}return c===void 0?"":c})}});var tb=f(()=>{"use strict";var uA=ye(),lA=fe(),uu=ie(),Zm=Rr(),cA=U(),dA=Wt(),pA=Hm(),gr=Gm(),hA=Cr(),fA=Km(),mA=Xm(),bA=J(),SA=Re(),gA=bA("replace"),vA=TypeError,ou=uu("".indexOf),yA=uu("".replace),eb=uu("".slice),TA=Math.max;uA({target:"String",proto:!0},{replaceAll:function(e,t){var r=Zm(this),a,s,n,o,l,u,d,c,p,h,m=0,b="";if(!dA(e)){if(a=pA(e),a&&(s=gr(Zm(fA(e))),!~ou(s,"g")))throw new vA("`.replaceAll` does not allow non-global regexes");if(n=hA(e,gA),n)return lA(n,e,r,t);if(SA&&a)return yA(gr(r),e,t)}for(o=gr(r),l=gr(e),u=cA(t),u||(t=gr(t)),d=l.length,c=TA(1,d),p=ou(o,l);p!==-1;)h=u?gr(t(l,p,o)):mA(l,o,p,[],void 0,t),b+=eb(o,m,p)+h,m=p+d,p=p+c>o.length?-1:ou(o,l,p+c);return m<o.length&&(b+=eb(o,m)),b}})});var ib=f((VB,rb)=>{"use strict";Fm();qm();tb();var IA=ja();rb.exports=IA("String","replaceAll")});var sb=f((_B,ab)=>{"use strict";var EA=ib();ab.exports=EA});var ob=f((NB,nb)=>{"use strict";var xA=sb();nb.exports=xA});var qu="2.0.108-dev.7ca5c32c.0";var re=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(re||{}),rt=(T=>(T.MPEG="MPEG",T.DASH="DASH",T.DASH_SEP="DASH_SEP",T.DASH_SEP_VK="DASH_SEP",T.DASH_WEBM="DASH_WEBM",T.DASH_WEBM_AV1="DASH_WEBM_AV1",T.DASH_STREAMS="DASH_STREAMS",T.DASH_WEBM_VK="DASH_WEBM",T.DASH_ONDEMAND="DASH_ONDEMAND",T.DASH_ONDEMAND_VK="DASH_ONDEMAND",T.DASH_LIVE="DASH_LIVE",T.DASH_LIVE_CMAF="DASH_LIVE_CMAF",T.DASH_LIVE_WEBM="DASH_LIVE_WEBM",T.HLS="HLS",T.HLS_ONDEMAND="HLS_ONDEMAND",T.HLS_JS="HLS",T.HLS_LIVE="HLS_LIVE",T.HLS_LIVE_CMAF="HLS_LIVE_CMAF",T.WEB_RTC_LIVE="WEB_RTC_LIVE",T))(rt||{});var ua=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(ua||{}),qs=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(qs||{});var Us=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Us||{});import{assertNever as Wu,assertNonNullable as FS,isNonNullable as la,ValueSubject as Hs,Subject as qS,Subscription as US,merge as HS,observableFrom as jS,fromEvent as Hu,map as ju,tap as Gu,filterChanged as GS,isNullable as js,ErrorCategory as Qu}from"@vkontakte/videoplayer-shared";var Uu=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 ca=class{constructor(e){this.connection$=new Hs(void 0);this.castState$=new Hs("NOT_AVAILABLE");this.errorEvent$=new qS;this.realCastState$=new Hs("NOT_AVAILABLE");this.subscription=new US;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=la(window.chrome?.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},a||Uu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Qu.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(){la(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();js(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();js(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(Hu(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 Wu(a.sessionState)}})).add(HS(Hu(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Gu(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),ju(a=>a.castState)),jS([r.getCastState()])).pipe(GS(),ju(QS),Gu(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=la(this.connection$.getValue());if(s&&!n){let o=r.getCurrentSession();FS(o);let l=o.getCastDevice(),u=o.getMediaSession()?.media.contentId;(js(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"?la(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:Qu.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 Wu(i)}};var oS=Ve(Gn(),1);var Mf=Ve(Ga(),1);import{assertNever as Ef}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:Ef(t)}return i},$o=(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:Ef(e)}};var I=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};import{isNonNullable as tP,Subject as Qa,merge as xf}from"@vkontakte/videoplayer-shared";var $=class{constructor(e){this.transitionStarted$=new Qa;this.transitionEnded$=new Qa;this.transitionUpdated$=new Qa;this.forceChanged$=new Qa;this.stateChangeStarted$=xf(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=xf(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||tP(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 rP}from"@vkontakte/videoplayer-shared";var Pf=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 rP(i)}};import{assertNever as lr,assertNonNullable as At,debounce as kf,ErrorCategory as Af,fromEvent as wt,isNonNullable as wf,map as Rf,merge as Lf,observableFrom as iP,Subject as aP,Subscription as Mo,timeout as sP,getHighestQuality as nP}from"@vkontakte/videoplayer-shared";var oP=5,uP=5,lP=500,$f=7e3,Xr=class{constructor(e){this.subscription=new Mo;this.loadMediaTimeoutSubscription=new Mo;this.videoState=new $("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(Pf(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 Mo;this.subscription.add(e),this.subscription.add(Lf(this.videoState.stateChangeStarted$.pipe(Rf(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(Rf(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 aP;e.add(a.pipe(kf(lP)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(wt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>oP)&&a.next(o),s=o})),e.add(wt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(wt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(wt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(wt(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<uP&&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(wt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(wt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=Lf(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,iP(["init"])).pipe(kf(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];At(u);let d=nP(Object.keys(u));At(d);let c=u[d];At(c),r=c,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let u=t[e];At(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];At(u),r=u.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let u=t[e];At(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];At(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:Af.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:l}=this.params.meta;return wf(o)&&(n.metadata.title=o),wf(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(sP($f).subscribe(()=>s(`timeout(${$f})`)))});(0,Mf.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:Af.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as Df}from"@vkontakte/videoplayer-shared";import{clearVideoElement as cP}from"@vkontakte/videoplayer-shared";var Cf=i=>{try{i.pause(),i.playbackRate=0,cP(i),i.remove()}catch(e){console.error(e)}};import{fromEvent as dP,Subscription as pP}from"@vkontakte/videoplayer-shared";var Co=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)}},Do=window.WeakMap?new WeakMap:new Co,Oo=window.WeakMap?new WeakMap:new Map,hP=(i,e=20)=>{let t=0;return dP(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?Df(t):(t=document.createElement("video"),i.appendChild(t)),Do.set(t,r);let a=new pP;return a.add(hP(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},se=i=>{Oo.get(i)?.unsubscribe(),Oo.delete(i);let t=Do.get(i);Do.delete(i),t?Df(i):Cf(i)};import{assertNonNullable as Zr,isNonNullable as Fe,isNullable as bP,fromEvent as cr,merge as Of,observableFrom as Bf,filterChanged as Vf,map as ei,Subject as _f,Subscription as SP,ValueSubject as gP,ErrorCategory as vP}from"@vkontakte/videoplayer-shared";import{isNonNullable as Bo,isNullable as fP,Subscription as mP}from"@vkontakte/videoplayer-shared";var Wa=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),l=fP(a),u=new mP;return a&&u.add(a.subscribe(d=>{let c=i.getState();r(d,c)&&i.setState(d)},s)),r(o,n)||(t(n),l&&i.setState(n)),u.add(i.stateChangeStarted$.subscribe(d=>{t(d.to),l&&i.setState(d.to)},s)),u},Ne=(i,e,t)=>Wa(e,()=>i.loop,r=>{Bo(r)&&(i.loop=r)},{onError:t}),ne=(i,e,t,r)=>Wa(e,()=>({muted:i.muted,volume:i.volume}),a=>{Bo(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}),Te=(i,e,t,r)=>Wa(e,()=>i.playbackRate,a=>{Bo(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),at=Wa;var yP=i=>["__",i.language,i.label].join("|"),TP=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},Vo=class i{constructor(){this.available$=new _f;this.current$=new gP(void 0);this.error$=new _f;this.subscription=new SP;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:vP.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(at(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{Fe(s)&&this.setInternal(s)},{equal:(s,n)=>Fe(s)&&Fe(n)&&s.length===n.length&&s.every(({id:o},l)=>o===n[l].id),changed$:this.available$.pipe(ei(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(at(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{Fe(s)&&this.setExternal(s)},{equal:(s,n)=>Fe(s)&&Fe(n)&&s.length===n.length&&s.every(({id:o},l)=>o===n[l].id),changed$:this.available$.pipe(ei(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(at(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(at(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Zr(this.video);let{textTracks:e}=this.video;this.subscription.add(cr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(Of(cr(e,"addtrack"),cr(e,"removetrack"),Bf(["init"])).pipe(ei(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Vf((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add(Of(cr(e,"change"),Bf(["init"])).pipe(ei(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),ei(r=>r&&this.htmlTextTrackToITextTrack(r).id),Vf()).subscribe(this.current$));let t=r=>this.applyCueSettings(r.target?.activeCues??null);this.subscription.add(cr(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(cr(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;Fe(t.align)&&(a.align=t.align),Fe(t.position)&&(a.position=t.position),Fe(t.size)&&(a.size=t.size),Fe(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){Zr(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:yP(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){Zr(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(bP(e)||!TP(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){Zr(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){Zr(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)}},Ie=Vo;var Qe=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 Nf=i=>{let e=i;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},_o=i=>{let e=Nf(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},Ff=i=>{let e=Nf(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};import{fromEvent as Ee,map as st,merge as Uf,filterChanged as EP,isNonNullable as Hf,Subject as xP,filter as jf,mapTo as Gf,combine as PP,once as kP,ErrorCategory as AP,ValueSubject as Qf,clientChecker as wP}from"@vkontakte/videoplayer-shared";var IP=3,qf=(i,e,t=IP)=>{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=T=>Ee(i,T).pipe(Gf(void 0)),r=Uf(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(T=>Ee(i,T))).pipe(st(T=>T.type==="ended"?i.readyState<2:i.readyState<3),EP()),a=Uf(Ee(i,"progress"),Ee(i,"timeupdate")).pipe(st(()=>qf(i.buffered,i.currentTime))),s=wP.isSafari?PP({play:e("play").pipe(kP()),playing:e("playing")}).pipe(Gf(void 0)):e("playing"),n=Ee(i,"volumechange").pipe(st(()=>({muted:i.muted,volume:i.volume}))),o=Ee(i,"ratechange").pipe(st(()=>i.playbackRate)),l=Ee(i,"error").pipe(jf(()=>!!(i.error||i.played.length)),st(()=>{let T=i.error;return{id:T?`MediaError#${T.code}`:"HtmlVideoError",category:AP.VIDEO_PIPELINE,message:T?T.message:"Error event from HTML video element",thrown:i.error??void 0}})),u=Ee(i,"timeupdate").pipe(st(()=>i.currentTime)),d=new xP,c=.3,p;u.subscribe(T=>{i.loop&&Hf(p)&&Hf(T)&&p>=i.duration-c&&T<=c&&d.next(p),p=T});let h=e("pause").pipe(jf(()=>!i.error&&p!==i.duration)),m=Ee(i,"enterpictureinpicture"),b=Ee(i,"leavepictureinpicture"),S=new Qf(Ff(i));m.subscribe(()=>S.next(!0)),b.subscribe(()=>S.next(!1));let v=new Qf(_o(i));return Ee(i,"fullscreenchange").pipe(st(()=>_o(i))).subscribe(v),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:d,error$:l,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:u,durationChange$:Ee(i,"durationchange").pipe(st(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:v}};import{VideoQuality as nt}from"@vkontakte/videoplayer-shared";var ot=i=>{switch(i){case"mobile":return nt.Q_144P;case"lowest":return nt.Q_240P;case"low":return nt.Q_360P;case"sd":case"medium":return nt.Q_480P;case"hd":case"high":return nt.Q_720P;case"fullhd":case"full":return nt.Q_1080P;case"quadhd":case"quad":return nt.Q_1440P;case"ultrahd":case"ultra":return nt.Q_2160P}};var Ho=Ve(ti(),1);import{isNonNullable as ut,isNullable as Fo,now as am,isHigher as qo,isHigherOrEqual as rm,isInvariantQuality as im,isLower as Uo,isLowerOrEqual as VP,videoSizeToQuality as _P,assertNotEmptyArray as NP}from"@vkontakte/videoplayer-shared";var No=!1,We={},Zf=i=>{No=i},em=()=>{We={}},tm=i=>{i(We)},ri=(i,e)=>{No&&(We.meta=We.meta??{},We.meta[i]=e)},X=class{constructor(e){this.name=e}next(e){if(!No)return;We.series=We.series??{};let t=We.series[this.name]??[];t.push([Date.now(),e]),We.series[this.name]=t}};var FP=new X("best_bitrate"),qP=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t,Ya=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=am()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},UP='Assertion "ABR Tracks is empty array" failed',HP=(i,{container:e,throughput:t,tuning:r,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:l,history:u,droppedVideoMaxQualityLimit:d,abrLogger:c})=>{NP(i,UP);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},m=h&&_P(h),b=r.considerPlaybackRate&&ut(o)?o:1,S=i.filter(P=>!im(P.quality)).sort((P,A)=>qo(P.quality,A.quality)?-1:1),v=(0,Ho.default)(S,-1)?.quality,w=(0,Ho.default)(S,0)?.quality,T=Fo(a)||ut(a.min)&&ut(a.max)&&Uo(a.max,a.min)||ut(a.min)&&w&&qo(a.min,w)||ut(a.max)&&v&&Uo(a.max,v),g=b*qP(n??.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),y={},x=S.filter(P=>(m?Uo(P.quality,m):!0)?(ut(t)&&isFinite(t)&&ut(P.bitrate)?t-s>=P.bitrate*g:!0)?r.lazyQualitySwitch&&ut(r.minBufferToSwitchUp)&&l&&!im(l.quality)&&(n??0)<r.minBufferToSwitchUp&&qo(P.quality,l.quality)?(y[P.quality]="Buffer",!1):!!d&&rm(P.quality,d)?(y[P.quality]="DroppedFramesLimit",!1):T||(Fo(a.max)||VP(P.quality,a.max))&&(Fo(a.min)||rm(P.quality,a.min))?!0:(y[P.quality]="FitsQualityLimits",!1):(y[P.quality]="FitsThroughput",!1):(y[P.quality]="FitsContainer",!1))[0];x&&x.bitrate&&FP.next(x.bitrate);let D=x??S[Math.ceil((S.length-1)/2)]??i[0];D.quality!==u?.last?.quality&&c({message:`
|
|
7
|
-
[
|
|
8
|
-
|
|
6
|
+
var Hg=Object.create;var Ku=Object.defineProperty;var jg=Object.getOwnPropertyDescriptor;var Gg=Object.getOwnPropertyNames;var Wg=Object.getPrototypeOf,Yg=Object.prototype.hasOwnProperty;var f=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var Qg=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Gg(e))!Yg.call(i,a)&&a!==t&&Ku(i,a,{get:()=>e[a],enumerable:!(r=jg(e,a))||r.enumerable});return i};var We=(i,e,t)=>(t=i!=null?Hg(Wg(i)):{},Qg(e||!i||!i.__esModule?Ku(t,"default",{value:i,enumerable:!0}):t,i));var be=f((jR,ac)=>{"use strict";ac.exports=function(i){try{return!!i()}catch{return!0}}});var _r=f((GR,sc)=>{"use strict";var rS=be();sc.exports=!rS(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var ne=f((WR,uc)=>{"use strict";var nc=_r(),oc=Function.prototype,Zs=oc.call,iS=nc&&oc.bind.bind(Zs,Zs);uc.exports=nc?iS:function(i){return function(){return Zs.apply(i,arguments)}}});var rr=f((YR,lc)=>{"use strict";var cc=ne(),aS=cc({}.toString),sS=cc("".slice);lc.exports=function(i){return sS(aS(i),8,-1)}});var pc=f((QR,dc)=>{"use strict";var nS=ne(),oS=be(),uS=rr(),en=Object,cS=nS("".split);dc.exports=oS(function(){return!en("z").propertyIsEnumerable(0)})?function(i){return uS(i)==="String"?cS(i,""):en(i)}:en});var ir=f((zR,hc)=>{"use strict";hc.exports=function(i){return i==null}});var Nr=f((KR,fc)=>{"use strict";var lS=ir(),dS=TypeError;fc.exports=function(i){if(lS(i))throw new dS("Can't call method on "+i);return i}});var ar=f((JR,mc)=>{"use strict";var pS=pc(),hS=Nr();mc.exports=function(i){return pS(hS(i))}});var tn=f((XR,bc)=>{"use strict";bc.exports=function(){}});var Mt=f((ZR,gc)=>{"use strict";gc.exports={}});var H=f((rn,Sc)=>{"use strict";var Fr=function(i){return i&&i.Math===Math&&i};Sc.exports=Fr(typeof globalThis=="object"&&globalThis)||Fr(typeof window=="object"&&window)||Fr(typeof self=="object"&&self)||Fr(typeof global=="object"&&global)||Fr(typeof rn=="object"&&rn)||function(){return this}()||Function("return this")()});var U=f((e$,vc)=>{"use strict";var an=typeof document=="object"&&document.all;vc.exports=typeof an>"u"&&an!==void 0?function(i){return typeof i=="function"||i===an}:function(i){return typeof i=="function"}});var Ic=f((t$,Tc)=>{"use strict";var fS=H(),mS=U(),yc=fS.WeakMap;Tc.exports=mS(yc)&&/native code/.test(String(yc))});var Ee=f((r$,Ec)=>{"use strict";var bS=U();Ec.exports=function(i){return typeof i=="object"?i!==null:bS(i)}});var xe=f((i$,xc)=>{"use strict";var gS=be();xc.exports=!gS(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var xa=f((a$,Ac)=>{"use strict";var SS=H(),Pc=Ee(),sn=SS.document,vS=Pc(sn)&&Pc(sn.createElement);Ac.exports=function(i){return vS?sn.createElement(i):{}}});var nn=f((s$,kc)=>{"use strict";var yS=xe(),TS=be(),IS=xa();kc.exports=!yS&&!TS(function(){return Object.defineProperty(IS("div"),"a",{get:function(){return 7}}).a!==7})});var on=f((n$,wc)=>{"use strict";var ES=xe(),xS=be();wc.exports=ES&&xS(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Ye=f((o$,Rc)=>{"use strict";var PS=Ee(),AS=String,kS=TypeError;Rc.exports=function(i){if(PS(i))return i;throw new kS(AS(i)+" is not an object")}});var ge=f((u$,$c)=>{"use strict";var wS=_r(),Pa=Function.prototype.call;$c.exports=wS?Pa.bind(Pa):function(){return Pa.apply(Pa,arguments)}});var Aa=f((c$,Lc)=>{"use strict";Lc.exports={}});var Ze=f((l$,Cc)=>{"use strict";var un=Aa(),cn=H(),RS=U(),Mc=function(i){return RS(i)?i:void 0};Cc.exports=function(i,e){return arguments.length<2?Mc(un[i])||Mc(cn[i]):un[i]&&un[i][e]||cn[i]&&cn[i][e]}});var qr=f((d$,Dc)=>{"use strict";var $S=ne();Dc.exports=$S({}.isPrototypeOf)});var sr=f((p$,Oc)=>{"use strict";var LS=H(),Bc=LS.navigator,Vc=Bc&&Bc.userAgent;Oc.exports=Vc?String(Vc):""});var dn=f((h$,Hc)=>{"use strict";var Uc=H(),ln=sr(),_c=Uc.process,Nc=Uc.Deno,Fc=_c&&_c.versions||Nc&&Nc.version,qc=Fc&&Fc.v8,Ve,ka;qc&&(Ve=qc.split("."),ka=Ve[0]>0&&Ve[0]<4?1:+(Ve[0]+Ve[1]));!ka&&ln&&(Ve=ln.match(/Edge\/(\d+)/),(!Ve||Ve[1]>=74)&&(Ve=ln.match(/Chrome\/(\d+)/),Ve&&(ka=+Ve[1])));Hc.exports=ka});var pn=f((f$,Gc)=>{"use strict";var jc=dn(),MS=be(),CS=H(),DS=CS.String;Gc.exports=!!Object.getOwnPropertySymbols&&!MS(function(){var i=Symbol("symbol detection");return!DS(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&jc&&jc<41})});var hn=f((m$,Wc)=>{"use strict";var BS=pn();Wc.exports=BS&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var fn=f((b$,Yc)=>{"use strict";var VS=Ze(),OS=U(),_S=qr(),NS=hn(),FS=Object;Yc.exports=NS?function(i){return typeof i=="symbol"}:function(i){var e=VS("Symbol");return OS(e)&&_S(e.prototype,FS(i))}});var Ur=f((g$,Qc)=>{"use strict";var qS=String;Qc.exports=function(i){try{return qS(i)}catch{return"Object"}}});var et=f((S$,zc)=>{"use strict";var US=U(),HS=Ur(),jS=TypeError;zc.exports=function(i){if(US(i))return i;throw new jS(HS(i)+" is not a function")}});var Hr=f((v$,Kc)=>{"use strict";var GS=et(),WS=ir();Kc.exports=function(i,e){var t=i[e];return WS(t)?void 0:GS(t)}});var Xc=f((y$,Jc)=>{"use strict";var mn=ge(),bn=U(),gn=Ee(),YS=TypeError;Jc.exports=function(i,e){var t,r;if(e==="string"&&bn(t=i.toString)&&!gn(r=mn(t,i))||bn(t=i.valueOf)&&!gn(r=mn(t,i))||e!=="string"&&bn(t=i.toString)&&!gn(r=mn(t,i)))return r;throw new YS("Can't convert object to primitive value")}});var Oe=f((T$,Zc)=>{"use strict";Zc.exports=!0});var rl=f((I$,tl)=>{"use strict";var el=H(),QS=Object.defineProperty;tl.exports=function(i,e){try{QS(el,i,{value:e,configurable:!0,writable:!0})}catch{el[i]=e}return e}});var jr=f((E$,sl)=>{"use strict";var zS=Oe(),KS=H(),JS=rl(),il="__core-js_shared__",al=sl.exports=KS[il]||JS(il,{});(al.versions||(al.versions=[])).push({version:"3.38.0",mode:zS?"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 Sn=f((x$,ol)=>{"use strict";var nl=jr();ol.exports=function(i,e){return nl[i]||(nl[i]=e||{})}});var Gr=f((P$,ul)=>{"use strict";var XS=Nr(),ZS=Object;ul.exports=function(i){return ZS(XS(i))}});var _e=f((A$,cl)=>{"use strict";var ev=ne(),tv=Gr(),rv=ev({}.hasOwnProperty);cl.exports=Object.hasOwn||function(e,t){return rv(tv(e),t)}});var vn=f((k$,ll)=>{"use strict";var iv=ne(),av=0,sv=Math.random(),nv=iv(1 .toString);ll.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+nv(++av+sv,36)}});var te=f((w$,pl)=>{"use strict";var ov=H(),uv=Sn(),dl=_e(),cv=vn(),lv=pn(),dv=hn(),nr=ov.Symbol,yn=uv("wks"),pv=dv?nr.for||nr:nr&&nr.withoutSetter||cv;pl.exports=function(i){return dl(yn,i)||(yn[i]=lv&&dl(nr,i)?nr[i]:pv("Symbol."+i)),yn[i]}});var bl=f((R$,ml)=>{"use strict";var hv=ge(),hl=Ee(),fl=fn(),fv=Hr(),mv=Xc(),bv=te(),gv=TypeError,Sv=bv("toPrimitive");ml.exports=function(i,e){if(!hl(i)||fl(i))return i;var t=fv(i,Sv),r;if(t){if(e===void 0&&(e="default"),r=hv(t,i,e),!hl(r)||fl(r))return r;throw new gv("Can't convert object to primitive value")}return e===void 0&&(e="number"),mv(i,e)}});var Tn=f(($$,gl)=>{"use strict";var vv=bl(),yv=fn();gl.exports=function(i){var e=vv(i,"string");return yv(e)?e:e+""}});var Ct=f(vl=>{"use strict";var Tv=xe(),Iv=nn(),Ev=on(),wa=Ye(),Sl=Tn(),xv=TypeError,In=Object.defineProperty,Pv=Object.getOwnPropertyDescriptor,En="enumerable",xn="configurable",Pn="writable";vl.f=Tv?Ev?function(e,t,r){if(wa(e),t=Sl(t),wa(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Pn in r&&!r[Pn]){var a=Pv(e,t);a&&a[Pn]&&(e[t]=r.value,r={configurable:xn in r?r[xn]:a[xn],enumerable:En in r?r[En]:a[En],writable:!1})}return In(e,t,r)}:In:function(e,t,r){if(wa(e),t=Sl(t),wa(r),Iv)try{return In(e,t,r)}catch{}if("get"in r||"set"in r)throw new xv("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Wr=f((M$,yl)=>{"use strict";yl.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var or=f((C$,Tl)=>{"use strict";var Av=xe(),kv=Ct(),wv=Wr();Tl.exports=Av?function(i,e,t){return kv.f(i,e,wv(1,t))}:function(i,e,t){return i[e]=t,i}});var Ra=f((D$,El)=>{"use strict";var Rv=Sn(),$v=vn(),Il=Rv("keys");El.exports=function(i){return Il[i]||(Il[i]=$v(i))}});var $a=f((B$,xl)=>{"use strict";xl.exports={}});var Rn=f((V$,kl)=>{"use strict";var Lv=Ic(),Al=H(),Mv=Ee(),Cv=or(),An=_e(),kn=jr(),Dv=Ra(),Bv=$a(),Pl="Object already initialized",wn=Al.TypeError,Vv=Al.WeakMap,La,Yr,Ma,Ov=function(i){return Ma(i)?Yr(i):La(i,{})},_v=function(i){return function(e){var t;if(!Mv(e)||(t=Yr(e)).type!==i)throw new wn("Incompatible receiver, "+i+" required");return t}};Lv||kn.state?(Ne=kn.state||(kn.state=new Vv),Ne.get=Ne.get,Ne.has=Ne.has,Ne.set=Ne.set,La=function(i,e){if(Ne.has(i))throw new wn(Pl);return e.facade=i,Ne.set(i,e),e},Yr=function(i){return Ne.get(i)||{}},Ma=function(i){return Ne.has(i)}):(Dt=Dv("state"),Bv[Dt]=!0,La=function(i,e){if(An(i,Dt))throw new wn(Pl);return e.facade=i,Cv(i,Dt,e),e},Yr=function(i){return An(i,Dt)?i[Dt]:{}},Ma=function(i){return An(i,Dt)});var Ne,Dt;kl.exports={set:La,get:Yr,has:Ma,enforce:Ov,getterFor:_v}});var $n=f((O$,Ll)=>{"use strict";var Nv=_r(),$l=Function.prototype,wl=$l.apply,Rl=$l.call;Ll.exports=typeof Reflect=="object"&&Reflect.apply||(Nv?Rl.bind(wl):function(){return Rl.apply(wl,arguments)})});var Ln=f((_$,Ml)=>{"use strict";var Fv=rr(),qv=ne();Ml.exports=function(i){if(Fv(i)==="Function")return qv(i)}});var Vl=f(Bl=>{"use strict";var Cl={}.propertyIsEnumerable,Dl=Object.getOwnPropertyDescriptor,Uv=Dl&&!Cl.call({1:2},1);Bl.f=Uv?function(e){var t=Dl(this,e);return!!t&&t.enumerable}:Cl});var Nl=f(_l=>{"use strict";var Hv=xe(),jv=ge(),Gv=Vl(),Wv=Wr(),Yv=ar(),Qv=Tn(),zv=_e(),Kv=nn(),Ol=Object.getOwnPropertyDescriptor;_l.f=Hv?Ol:function(e,t){if(e=Yv(e),t=Qv(t),Kv)try{return Ol(e,t)}catch{}if(zv(e,t))return Wv(!jv(Gv.f,e,t),e[t])}});var Mn=f((q$,Fl)=>{"use strict";var Jv=be(),Xv=U(),Zv=/#|\.prototype\./,Qr=function(i,e){var t=ty[ey(i)];return t===iy?!0:t===ry?!1:Xv(e)?Jv(e):!!e},ey=Qr.normalize=function(i){return String(i).replace(Zv,".").toLowerCase()},ty=Qr.data={},ry=Qr.NATIVE="N",iy=Qr.POLYFILL="P";Fl.exports=Qr});var zr=f((U$,Ul)=>{"use strict";var ql=Ln(),ay=et(),sy=_r(),ny=ql(ql.bind);Ul.exports=function(i,e){return ay(i),e===void 0?i:sy?ny(i,e):function(){return i.apply(e,arguments)}}});var Pe=f((H$,jl)=>{"use strict";var Kr=H(),oy=$n(),uy=Ln(),cy=U(),ly=Nl().f,dy=Mn(),ur=Aa(),py=zr(),cr=or(),Hl=_e();jr();var hy=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 oy(i,this,arguments)};return e.prototype=i.prototype,e};jl.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?Kr:a?Kr[t]:Kr[t]&&Kr[t].prototype,o=r?ur:ur[t]||cr(ur,t,{})[t],c=o.prototype,u,d,l,p,h,m,b,g,v;for(p in e)u=dy(r?p:t+(a?".":"#")+p,i.forced),d=!u&&n&&Hl(n,p),m=o[p],d&&(i.dontCallGetSet?(v=ly(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=py(h,Kr):i.wrap&&d?g=hy(h):s&&cy(h)?g=uy(h):g=h,(i.sham||h&&h.sham||m&&m.sham)&&cr(g,"sham",!0),cr(o,p,g),s&&(l=t+"Prototype",Hl(ur,l)||cr(ur,l,{}),cr(ur[l],p,h),i.real&&c&&(u||!c[p])&&cr(c,p,h)))}});var Yl=f((j$,Wl)=>{"use strict";var Cn=xe(),fy=_e(),Gl=Function.prototype,my=Cn&&Object.getOwnPropertyDescriptor,Dn=fy(Gl,"name"),by=Dn&&function(){}.name==="something",gy=Dn&&(!Cn||Cn&&my(Gl,"name").configurable);Wl.exports={EXISTS:Dn,PROPER:by,CONFIGURABLE:gy}});var zl=f((G$,Ql)=>{"use strict";var Sy=Math.ceil,vy=Math.floor;Ql.exports=Math.trunc||function(e){var t=+e;return(t>0?vy:Sy)(t)}});var Ca=f((W$,Kl)=>{"use strict";var yy=zl();Kl.exports=function(i){var e=+i;return e!==e||e===0?0:yy(e)}});var Xl=f((Y$,Jl)=>{"use strict";var Ty=Ca(),Iy=Math.max,Ey=Math.min;Jl.exports=function(i,e){var t=Ty(i);return t<0?Iy(t+e,0):Ey(t,e)}});var ed=f((Q$,Zl)=>{"use strict";var xy=Ca(),Py=Math.min;Zl.exports=function(i){var e=xy(i);return e>0?Py(e,9007199254740991):0}});var Da=f((z$,td)=>{"use strict";var Ay=ed();td.exports=function(i){return Ay(i.length)}});var ad=f((K$,id)=>{"use strict";var ky=ar(),wy=Xl(),Ry=Da(),rd=function(i){return function(e,t,r){var a=ky(e),s=Ry(a);if(s===0)return!i&&-1;var n=wy(r,s),o;if(i&&t!==t){for(;s>n;)if(o=a[n++],o!==o)return!0}else for(;s>n;n++)if((i||n in a)&&a[n]===t)return i||n||0;return!i&&-1}};id.exports={includes:rd(!0),indexOf:rd(!1)}});var od=f((J$,nd)=>{"use strict";var $y=ne(),Bn=_e(),Ly=ar(),My=ad().indexOf,Cy=$a(),sd=$y([].push);nd.exports=function(i,e){var t=Ly(i),r=0,a=[],s;for(s in t)!Bn(Cy,s)&&Bn(t,s)&&sd(a,s);for(;e.length>r;)Bn(t,s=e[r++])&&(~My(a,s)||sd(a,s));return a}});var Vn=f((X$,ud)=>{"use strict";ud.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var ld=f((Z$,cd)=>{"use strict";var Dy=od(),By=Vn();cd.exports=Object.keys||function(e){return Dy(e,By)}});var pd=f(dd=>{"use strict";var Vy=xe(),Oy=on(),_y=Ct(),Ny=Ye(),Fy=ar(),qy=ld();dd.f=Vy&&!Oy?Object.defineProperties:function(e,t){Ny(e);for(var r=Fy(t),a=qy(t),s=a.length,n=0,o;s>n;)_y.f(e,o=a[n++],r[o]);return e}});var On=f((tL,hd)=>{"use strict";var Uy=Ze();hd.exports=Uy("document","documentElement")});var qn=f((rL,yd)=>{"use strict";var Hy=Ye(),jy=pd(),fd=Vn(),Gy=$a(),Wy=On(),Yy=xa(),Qy=Ra(),md=">",bd="<",Nn="prototype",Fn="script",Sd=Qy("IE_PROTO"),_n=function(){},vd=function(i){return bd+Fn+md+i+bd+"/"+Fn+md},gd=function(i){i.write(vd("")),i.close();var e=i.parentWindow.Object;return i=null,e},zy=function(){var i=Yy("iframe"),e="java"+Fn+":",t;return i.style.display="none",Wy.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(vd("document.F=Object")),t.close(),t.F},Ba,Va=function(){try{Ba=new ActiveXObject("htmlfile")}catch{}Va=typeof document<"u"?document.domain&&Ba?gd(Ba):zy():gd(Ba);for(var i=fd.length;i--;)delete Va[Nn][fd[i]];return Va()};Gy[Sd]=!0;yd.exports=Object.create||function(e,t){var r;return e!==null?(_n[Nn]=Hy(e),r=new _n,_n[Nn]=null,r[Sd]=e):r=Va(),t===void 0?r:jy.f(r,t)}});var Id=f((iL,Td)=>{"use strict";var Ky=be();Td.exports=!Ky(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var Hn=f((aL,xd)=>{"use strict";var Jy=_e(),Xy=U(),Zy=Gr(),eT=Ra(),tT=Id(),Ed=eT("IE_PROTO"),Un=Object,rT=Un.prototype;xd.exports=tT?Un.getPrototypeOf:function(i){var e=Zy(i);if(Jy(e,Ed))return e[Ed];var t=e.constructor;return Xy(t)&&e instanceof t?t.prototype:e instanceof Un?rT:null}});var lr=f((sL,Pd)=>{"use strict";var iT=or();Pd.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:iT(i,e,t),i}});var Yn=f((nL,wd)=>{"use strict";var aT=be(),sT=U(),nT=Ee(),oT=qn(),Ad=Hn(),uT=lr(),cT=te(),lT=Oe(),Wn=cT("iterator"),kd=!1,tt,jn,Gn;[].keys&&(Gn=[].keys(),"next"in Gn?(jn=Ad(Ad(Gn)),jn!==Object.prototype&&(tt=jn)):kd=!0);var dT=!nT(tt)||aT(function(){var i={};return tt[Wn].call(i)!==i});dT?tt={}:lT&&(tt=oT(tt));sT(tt[Wn])||uT(tt,Wn,function(){return this});wd.exports={IteratorPrototype:tt,BUGGY_SAFARI_ITERATORS:kd}});var Oa=f((oL,$d)=>{"use strict";var pT=te(),hT=pT("toStringTag"),Rd={};Rd[hT]="z";$d.exports=String(Rd)==="[object z]"});var Jr=f((uL,Ld)=>{"use strict";var fT=Oa(),mT=U(),_a=rr(),bT=te(),gT=bT("toStringTag"),ST=Object,vT=_a(function(){return arguments}())==="Arguments",yT=function(i,e){try{return i[e]}catch{}};Ld.exports=fT?_a:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=yT(e=ST(i),gT))=="string"?t:vT?_a(e):(r=_a(e))==="Object"&&mT(e.callee)?"Arguments":r}});var Cd=f((cL,Md)=>{"use strict";var TT=Oa(),IT=Jr();Md.exports=TT?{}.toString:function(){return"[object "+IT(this)+"]"}});var Xr=f((lL,Bd)=>{"use strict";var ET=Oa(),xT=Ct().f,PT=or(),AT=_e(),kT=Cd(),wT=te(),Dd=wT("toStringTag");Bd.exports=function(i,e,t,r){var a=t?i:i&&i.prototype;a&&(AT(a,Dd)||xT(a,Dd,{configurable:!0,value:e}),r&&!ET&&PT(a,"toString",kT))}});var Od=f((dL,Vd)=>{"use strict";var RT=Yn().IteratorPrototype,$T=qn(),LT=Wr(),MT=Xr(),CT=Mt(),DT=function(){return this};Vd.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=$T(RT,{next:LT(+!r,t)}),MT(i,a,!1,!0),CT[a]=DT,i}});var Nd=f((pL,_d)=>{"use strict";var BT=ne(),VT=et();_d.exports=function(i,e,t){try{return BT(VT(Object.getOwnPropertyDescriptor(i,e)[t]))}catch{}}});var qd=f((hL,Fd)=>{"use strict";var OT=Ee();Fd.exports=function(i){return OT(i)||i===null}});var Hd=f((fL,Ud)=>{"use strict";var _T=qd(),NT=String,FT=TypeError;Ud.exports=function(i){if(_T(i))return i;throw new FT("Can't set "+NT(i)+" as a prototype")}});var Qn=f((mL,jd)=>{"use strict";var qT=Nd(),UT=Ee(),HT=Nr(),jT=Hd();jd.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=qT(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch{}return function(a,s){return HT(a),jT(s),UT(a)&&(i?t(a,s):a.__proto__=s),a}}():void 0)});var tp=f((bL,ep)=>{"use strict";var GT=Pe(),WT=ge(),Na=Oe(),Xd=Yl(),YT=U(),QT=Od(),Gd=Hn(),Wd=Qn(),zT=Xr(),KT=or(),zn=lr(),JT=te(),Yd=Mt(),Zd=Yn(),XT=Xd.PROPER,ZT=Xd.CONFIGURABLE,Qd=Zd.IteratorPrototype,Fa=Zd.BUGGY_SAFARI_ITERATORS,Zr=JT("iterator"),zd="keys",ei="values",Kd="entries",Jd=function(){return this};ep.exports=function(i,e,t,r,a,s,n){QT(t,e,r);var o=function(v){if(v===a&&p)return p;if(!Fa&&v&&v in d)return d[v];switch(v){case zd:return function(){return new t(this,v)};case ei:return function(){return new t(this,v)};case Kd:return function(){return new t(this,v)}}return function(){return new t(this)}},c=e+" Iterator",u=!1,d=i.prototype,l=d[Zr]||d["@@iterator"]||a&&d[a],p=!Fa&&l||o(a),h=e==="Array"&&d.entries||l,m,b,g;if(h&&(m=Gd(h.call(new i)),m!==Object.prototype&&m.next&&(!Na&&Gd(m)!==Qd&&(Wd?Wd(m,Qd):YT(m[Zr])||zn(m,Zr,Jd)),zT(m,c,!0,!0),Na&&(Yd[c]=Jd))),XT&&a===ei&&l&&l.name!==ei&&(!Na&&ZT?KT(d,"name",ei):(u=!0,p=function(){return WT(l,this)})),a)if(b={values:o(ei),keys:s?p:o(zd),entries:o(Kd)},n)for(g in b)(Fa||u||!(g in d))&&zn(d,g,b[g]);else GT({target:e,proto:!0,forced:Fa||u},b);return(!Na||n)&&d[Zr]!==p&&zn(d,Zr,p,{name:a}),Yd[e]=p,b}});var ip=f((gL,rp)=>{"use strict";rp.exports=function(i,e){return{value:i,done:e}}});var Jn=f((SL,up)=>{"use strict";var eI=ar(),Kn=tn(),ap=Mt(),np=Rn(),tI=Ct().f,rI=tp(),qa=ip(),iI=Oe(),aI=xe(),op="Array Iterator",sI=np.set,nI=np.getterFor(op);up.exports=rI(Array,"Array",function(i,e){sI(this,{type:op,target:eI(i),index:0,kind:e})},function(){var i=nI(this),e=i.target,t=i.index++;if(!e||t>=e.length)return i.target=void 0,qa(void 0,!0);switch(i.kind){case"keys":return qa(t,!1);case"values":return qa(e[t],!1)}return qa([t,e[t]],!1)},"values");var sp=ap.Arguments=ap.Array;Kn("keys");Kn("values");Kn("entries");if(!iI&&aI&&sp.name!=="values")try{tI(sp,"name",{value:"values"})}catch{}});var lp=f((vL,cp)=>{"use strict";var oI=te(),uI=Mt(),cI=oI("iterator"),lI=Array.prototype;cp.exports=function(i){return i!==void 0&&(uI.Array===i||lI[cI]===i)}});var Xn=f((yL,pp)=>{"use strict";var dI=Jr(),dp=Hr(),pI=ir(),hI=Mt(),fI=te(),mI=fI("iterator");pp.exports=function(i){if(!pI(i))return dp(i,mI)||dp(i,"@@iterator")||hI[dI(i)]}});var fp=f((TL,hp)=>{"use strict";var bI=ge(),gI=et(),SI=Ye(),vI=Ur(),yI=Xn(),TI=TypeError;hp.exports=function(i,e){var t=arguments.length<2?yI(i):e;if(gI(t))return SI(bI(t,i));throw new TI(vI(i)+" is not iterable")}});var gp=f((IL,bp)=>{"use strict";var II=ge(),mp=Ye(),EI=Hr();bp.exports=function(i,e,t){var r,a;mp(i);try{if(r=EI(i,"return"),!r){if(e==="throw")throw t;return t}r=II(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return mp(r),t}});var Ha=f((EL,Tp)=>{"use strict";var xI=zr(),PI=ge(),AI=Ye(),kI=Ur(),wI=lp(),RI=Da(),Sp=qr(),$I=fp(),LI=Xn(),vp=gp(),MI=TypeError,Ua=function(i,e){this.stopped=i,this.result=e},yp=Ua.prototype;Tp.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=xI(e,r),u,d,l,p,h,m,b,g=function(k){return u&&vp(u,"normal",k),new Ua(!0,k)},v=function(k){return a?(AI(k),o?c(k[0],k[1],g):c(k[0],k[1])):o?c(k,g):c(k)};if(s)u=i.iterator;else if(n)u=i;else{if(d=LI(i),!d)throw new MI(kI(i)+" is not iterable");if(wI(d)){for(l=0,p=RI(i);p>l;l++)if(h=v(i[l]),h&&Sp(yp,h))return h;return new Ua(!1)}u=$I(i,d)}for(m=s?i.next:u.next;!(b=PI(m,u)).done;){try{h=v(b.value)}catch(k){vp(u,"throw",k)}if(typeof h=="object"&&h&&Sp(yp,h))return h}return new Ua(!1)}});var Ep=f((xL,Ip)=>{"use strict";var CI=xe(),DI=Ct(),BI=Wr();Ip.exports=function(i,e,t){CI?DI.f(i,e,BI(0,t)):i[e]=t}});var xp=f(()=>{"use strict";var VI=Pe(),OI=Ha(),_I=Ep();VI({target:"Object",stat:!0},{fromEntries:function(e){var t={};return OI(e,function(r,a){_I(t,r,a)},{AS_ENTRIES:!0}),t}})});var Ap=f((kL,Pp)=>{"use strict";Jn();xp();var NI=Aa();Pp.exports=NI.Object.fromEntries});var wp=f((wL,kp)=>{"use strict";kp.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 $p=f(()=>{"use strict";Jn();var FI=wp(),qI=H(),UI=Xr(),Rp=Mt();for(ja in FI)UI(qI[ja],ja),Rp[ja]=Rp.Array;var ja});var Mp=f((LL,Lp)=>{"use strict";var HI=Ap();$p();Lp.exports=HI});var Zn=f((ML,Cp)=>{"use strict";var jI=Mp();Cp.exports=jI});var Dp=f(()=>{"use strict"});var eo=f((BL,Bp)=>{"use strict";var ti=H(),GI=sr(),WI=rr(),Ga=function(i){return GI.slice(0,i.length)===i};Bp.exports=function(){return Ga("Bun/")?"BUN":Ga("Cloudflare-Workers")?"CLOUDFLARE":Ga("Deno/")?"DENO":Ga("Node.js/")?"NODE":ti.Bun&&typeof Bun.version=="string"?"BUN":ti.Deno&&typeof Deno.version=="object"?"DENO":WI(ti.process)==="process"?"NODE":ti.window&&ti.document?"BROWSER":"REST"}()});var Wa=f((VL,Vp)=>{"use strict";var YI=eo();Vp.exports=YI==="NODE"});var _p=f((OL,Op)=>{"use strict";var QI=Ct();Op.exports=function(i,e,t){return QI.f(i,e,t)}});var qp=f((_L,Fp)=>{"use strict";var zI=Ze(),KI=_p(),JI=te(),XI=xe(),Np=JI("species");Fp.exports=function(i){var e=zI(i);XI&&e&&!e[Np]&&KI(e,Np,{configurable:!0,get:function(){return this}})}});var Hp=f((NL,Up)=>{"use strict";var ZI=qr(),eE=TypeError;Up.exports=function(i,e){if(ZI(e,i))return i;throw new eE("Incorrect invocation")}});var ro=f((FL,jp)=>{"use strict";var tE=ne(),rE=U(),to=jr(),iE=tE(Function.toString);rE(to.inspectSource)||(to.inspectSource=function(i){return iE(i)});jp.exports=to.inspectSource});var Kp=f((qL,zp)=>{"use strict";var aE=ne(),sE=be(),Gp=U(),nE=Jr(),oE=Ze(),uE=ro(),Wp=function(){},Yp=oE("Reflect","construct"),io=/^\s*(?:class|function)\b/,cE=aE(io.exec),lE=!io.test(Wp),ri=function(e){if(!Gp(e))return!1;try{return Yp(Wp,[],e),!0}catch{return!1}},Qp=function(e){if(!Gp(e))return!1;switch(nE(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return lE||!!cE(io,uE(e))}catch{return!0}};Qp.sham=!0;zp.exports=!Yp||sE(function(){var i;return ri(ri.call)||!ri(Object)||!ri(function(){i=!0})||i})?Qp:ri});var Xp=f((UL,Jp)=>{"use strict";var dE=Kp(),pE=Ur(),hE=TypeError;Jp.exports=function(i){if(dE(i))return i;throw new hE(pE(i)+" is not a constructor")}});var ao=f((HL,eh)=>{"use strict";var Zp=Ye(),fE=Xp(),mE=ir(),bE=te(),gE=bE("species");eh.exports=function(i,e){var t=Zp(i).constructor,r;return t===void 0||mE(r=Zp(t)[gE])?e:fE(r)}});var rh=f((jL,th)=>{"use strict";var SE=ne();th.exports=SE([].slice)});var ah=f((GL,ih)=>{"use strict";var vE=TypeError;ih.exports=function(i,e){if(i<e)throw new vE("Not enough arguments");return i}});var so=f((WL,sh)=>{"use strict";var yE=sr();sh.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(yE)});var mo=f((YL,fh)=>{"use strict";var Se=H(),TE=$n(),IE=zr(),nh=U(),EE=_e(),hh=be(),oh=On(),xE=rh(),uh=xa(),PE=ah(),AE=so(),kE=Wa(),po=Se.setImmediate,ho=Se.clearImmediate,wE=Se.process,no=Se.Dispatch,RE=Se.Function,ch=Se.MessageChannel,$E=Se.String,oo=0,ii={},lh="onreadystatechange",ai,Bt,uo,co;hh(function(){ai=Se.location});var fo=function(i){if(EE(ii,i)){var e=ii[i];delete ii[i],e()}},lo=function(i){return function(){fo(i)}},dh=function(i){fo(i.data)},ph=function(i){Se.postMessage($E(i),ai.protocol+"//"+ai.host)};(!po||!ho)&&(po=function(e){PE(arguments.length,1);var t=nh(e)?e:RE(e),r=xE(arguments,1);return ii[++oo]=function(){TE(t,void 0,r)},Bt(oo),oo},ho=function(e){delete ii[e]},kE?Bt=function(i){wE.nextTick(lo(i))}:no&&no.now?Bt=function(i){no.now(lo(i))}:ch&&!AE?(uo=new ch,co=uo.port2,uo.port1.onmessage=dh,Bt=IE(co.postMessage,co)):Se.addEventListener&&nh(Se.postMessage)&&!Se.importScripts&&ai&&ai.protocol!=="file:"&&!hh(ph)?(Bt=ph,Se.addEventListener("message",dh,!1)):lh in uh("script")?Bt=function(i){oh.appendChild(uh("script"))[lh]=function(){oh.removeChild(this),fo(i)}}:Bt=function(i){setTimeout(lo(i),0)});fh.exports={set:po,clear:ho}});var gh=f((QL,bh)=>{"use strict";var mh=H(),LE=xe(),ME=Object.getOwnPropertyDescriptor;bh.exports=function(i){if(!LE)return mh[i];var e=ME(mh,i);return e&&e.value}});var bo=f((zL,vh)=>{"use strict";var Sh=function(){this.head=null,this.tail=null};Sh.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}}};vh.exports=Sh});var Th=f((KL,yh)=>{"use strict";var CE=sr();yh.exports=/ipad|iphone|ipod/i.test(CE)&&typeof Pebble<"u"});var Eh=f((JL,Ih)=>{"use strict";var DE=sr();Ih.exports=/web0s(?!.*chrome)/i.test(DE)});var $h=f((XL,Rh)=>{"use strict";var pr=H(),BE=gh(),xh=zr(),go=mo().set,VE=bo(),OE=so(),_E=Th(),NE=Eh(),So=Wa(),Ph=pr.MutationObserver||pr.WebKitMutationObserver,Ah=pr.document,kh=pr.process,Ya=pr.Promise,To=BE("queueMicrotask"),dr,vo,yo,Qa,wh;To||(si=new VE,ni=function(){var i,e;for(So&&(i=kh.domain)&&i.exit();e=si.get();)try{e()}catch(t){throw si.head&&dr(),t}i&&i.enter()},!OE&&!So&&!NE&&Ph&&Ah?(vo=!0,yo=Ah.createTextNode(""),new Ph(ni).observe(yo,{characterData:!0}),dr=function(){yo.data=vo=!vo}):!_E&&Ya&&Ya.resolve?(Qa=Ya.resolve(void 0),Qa.constructor=Ya,wh=xh(Qa.then,Qa),dr=function(){wh(ni)}):So?dr=function(){kh.nextTick(ni)}:(go=xh(go,pr),dr=function(){go(ni)}),To=function(i){si.head||dr(),si.add(i)});var si,ni;Rh.exports=To});var Mh=f((ZL,Lh)=>{"use strict";Lh.exports=function(i,e){try{arguments.length===1?console.error(i):console.error(i,e)}catch{}}});var za=f((eM,Ch)=>{"use strict";Ch.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var Vt=f((tM,Dh)=>{"use strict";var FE=H();Dh.exports=FE.Promise});var hr=f((rM,_h)=>{"use strict";var qE=H(),oi=Vt(),UE=U(),HE=Mn(),jE=ro(),GE=te(),Bh=eo(),WE=Oe(),Io=dn(),Vh=oi&&oi.prototype,YE=GE("species"),Eo=!1,Oh=UE(qE.PromiseRejectionEvent),QE=HE("Promise",function(){var i=jE(oi),e=i!==String(oi);if(!e&&Io===66||WE&&!(Vh.catch&&Vh.finally))return!0;if(!Io||Io<51||!/native code/.test(i)){var t=new oi(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[YE]=r,Eo=t.then(function(){})instanceof r,!Eo)return!0}return!e&&(Bh==="BROWSER"||Bh==="DENO")&&!Oh});_h.exports={CONSTRUCTOR:QE,REJECTION_EVENT:Oh,SUBCLASSING:Eo}});var fr=f((iM,Fh)=>{"use strict";var Nh=et(),zE=TypeError,KE=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw new zE("Bad Promise constructor");e=r,t=a}),this.resolve=Nh(e),this.reject=Nh(t)};Fh.exports.f=function(i){return new KE(i)}});var nf=f(()=>{"use strict";var JE=Pe(),XE=Oe(),Za=Wa(),mt=H(),Sr=ge(),qh=lr(),Uh=Qn(),ZE=Xr(),ex=qp(),tx=et(),Xa=U(),rx=Ee(),ix=Hp(),ax=ao(),Yh=mo().set,wo=$h(),sx=Mh(),nx=za(),ox=bo(),Qh=Rn(),es=Vt(),Ro=hr(),zh=fr(),ts="Promise",Kh=Ro.CONSTRUCTOR,ux=Ro.REJECTION_EVENT,cx=Ro.SUBCLASSING,xo=Qh.getterFor(ts),lx=Qh.set,mr=es&&es.prototype,Ot=es,Ka=mr,Jh=mt.TypeError,Po=mt.document,$o=mt.process,Ao=zh.f,dx=Ao,px=!!(Po&&Po.createEvent&&mt.dispatchEvent),Xh="unhandledrejection",hx="rejectionhandled",Hh=0,Zh=1,fx=2,Lo=1,ef=2,Ja,jh,mx,Gh,tf=function(i){var e;return rx(i)&&Xa(e=i.then)?e:!1},rf=function(i,e){var t=e.value,r=e.state===Zh,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,c,u,d;try{a?(r||(e.rejection===ef&&gx(e),e.rejection=Lo),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=tf(c))?Sr(u,c,s,n):s(c)):n(t)}catch(l){o&&!d&&o.exit(),n(l)}},af=function(i,e){i.notified||(i.notified=!0,wo(function(){for(var t=i.reactions,r;r=t.get();)rf(r,i);i.notified=!1,e&&!i.rejection&&bx(i)}))},sf=function(i,e,t){var r,a;px?(r=Po.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),mt.dispatchEvent(r)):r={promise:e,reason:t},!ux&&(a=mt["on"+i])?a(r):i===Xh&&sx("Unhandled promise rejection",t)},bx=function(i){Sr(Yh,mt,function(){var e=i.facade,t=i.value,r=Wh(i),a;if(r&&(a=nx(function(){Za?$o.emit("unhandledRejection",t,e):sf(Xh,e,t)}),i.rejection=Za||Wh(i)?ef:Lo,a.error))throw a.value})},Wh=function(i){return i.rejection!==Lo&&!i.parent},gx=function(i){Sr(Yh,mt,function(){var e=i.facade;Za?$o.emit("rejectionHandled",e):sf(hx,e,i.value)})},br=function(i,e,t){return function(r){i(e,r,t)}},gr=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=fx,af(i,!0))},ko=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=tf(e);r?wo(function(){var a={done:!1};try{Sr(r,e,br(ko,a,i),br(gr,a,i))}catch(s){gr(a,s,i)}}):(i.value=e,i.state=Zh,af(i,!1))}catch(a){gr({done:!1},a,i)}}};if(Kh&&(Ot=function(e){ix(this,Ka),tx(e),Sr(Ja,this);var t=xo(this);try{e(br(ko,t),br(gr,t))}catch(r){gr(t,r)}},Ka=Ot.prototype,Ja=function(e){lx(this,{type:ts,done:!1,notified:!1,parent:!1,reactions:new ox,rejection:!1,state:Hh,value:void 0})},Ja.prototype=qh(Ka,"then",function(e,t){var r=xo(this),a=Ao(ax(this,Ot));return r.parent=!0,a.ok=Xa(e)?e:!0,a.fail=Xa(t)&&t,a.domain=Za?$o.domain:void 0,r.state===Hh?r.reactions.add(a):wo(function(){rf(a,r)}),a.promise}),jh=function(){var i=new Ja,e=xo(i);this.promise=i,this.resolve=br(ko,e),this.reject=br(gr,e)},zh.f=Ao=function(i){return i===Ot||i===mx?new jh(i):dx(i)},!XE&&Xa(es)&&mr!==Object.prototype)){Gh=mr.then,cx||qh(mr,"then",function(e,t){var r=this;return new Ot(function(a,s){Sr(Gh,r,a,s)}).then(e,t)},{unsafe:!0});try{delete mr.constructor}catch{}Uh&&Uh(mr,Ka)}JE({global:!0,constructor:!0,wrap:!0,forced:Kh},{Promise:Ot});ZE(Ot,ts,!1,!0);ex(ts)});var df=f((nM,lf)=>{"use strict";var Sx=te(),uf=Sx("iterator"),cf=!1;try{of=0,Mo={next:function(){return{done:!!of++}},return:function(){cf=!0}},Mo[uf]=function(){return this},Array.from(Mo,function(){throw 2})}catch{}var of,Mo;lf.exports=function(i,e){try{if(!e&&!cf)return!1}catch{return!1}var t=!1;try{var r={};r[uf]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch{}return t}});var Co=f((oM,pf)=>{"use strict";var vx=Vt(),yx=df(),Tx=hr().CONSTRUCTOR;pf.exports=Tx||!yx(function(i){vx.all(i).then(void 0,function(){})})});var hf=f(()=>{"use strict";var Ix=Pe(),Ex=ge(),xx=et(),Px=fr(),Ax=za(),kx=Ha(),wx=Co();Ix({target:"Promise",stat:!0,forced:wx},{all:function(e){var t=this,r=Px.f(t),a=r.resolve,s=r.reject,n=Ax(function(){var o=xx(t.resolve),c=[],u=0,d=1;kx(e,function(l){var p=u++,h=!1;d++,Ex(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 mf=f(()=>{"use strict";var Rx=Pe(),$x=Oe(),Lx=hr().CONSTRUCTOR,Bo=Vt(),Mx=Ze(),Cx=U(),Dx=lr(),ff=Bo&&Bo.prototype;Rx({target:"Promise",proto:!0,forced:Lx,real:!0},{catch:function(i){return this.then(void 0,i)}});!$x&&Cx(Bo)&&(Do=Mx("Promise").prototype.catch,ff.catch!==Do&&Dx(ff,"catch",Do,{unsafe:!0}));var Do});var bf=f(()=>{"use strict";var Bx=Pe(),Vx=ge(),Ox=et(),_x=fr(),Nx=za(),Fx=Ha(),qx=Co();Bx({target:"Promise",stat:!0,forced:qx},{race:function(e){var t=this,r=_x.f(t),a=r.reject,s=Nx(function(){var n=Ox(t.resolve);Fx(e,function(o){Vx(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var gf=f(()=>{"use strict";var Ux=Pe(),Hx=fr(),jx=hr().CONSTRUCTOR;Ux({target:"Promise",stat:!0,forced:jx},{reject:function(e){var t=Hx.f(this),r=t.reject;return r(e),t.promise}})});var Vo=f((bM,Sf)=>{"use strict";var Gx=Ye(),Wx=Ee(),Yx=fr();Sf.exports=function(i,e){if(Gx(i),Wx(e)&&e.constructor===i)return e;var t=Yx.f(i),r=t.resolve;return r(e),t.promise}});var Tf=f(()=>{"use strict";var Qx=Pe(),zx=Ze(),vf=Oe(),Kx=Vt(),yf=hr().CONSTRUCTOR,Jx=Vo(),Xx=zx("Promise"),Zx=vf&&!yf;Qx({target:"Promise",stat:!0,forced:vf||yf},{resolve:function(e){return Jx(Zx&&this===Xx?Kx:this,e)}})});var If=f(()=>{"use strict";nf();hf();mf();bf();gf();Tf()});var Af=f(()=>{"use strict";var eP=Pe(),tP=Oe(),rs=Vt(),rP=be(),xf=Ze(),Pf=U(),iP=ao(),Ef=Vo(),aP=lr(),_o=rs&&rs.prototype,sP=!!rs&&rP(function(){_o.finally.call({then:function(){}},function(){})});eP({target:"Promise",proto:!0,real:!0,forced:sP},{finally:function(i){var e=iP(this,xf("Promise")),t=Pf(i);return this.then(t?function(r){return Ef(e,i()).then(function(){return r})}:i,t?function(r){return Ef(e,i()).then(function(){throw r})}:i)}});!tP&&Pf(rs)&&(Oo=xf("Promise").prototype.finally,_o.finally!==Oo&&aP(_o,"finally",Oo,{unsafe:!0}));var Oo});var is=f((EM,kf)=>{"use strict";var nP=Ze();kf.exports=nP});var Rf=f((xM,wf)=>{"use strict";Dp();If();Af();var oP=is();wf.exports=oP("Promise","finally")});var Lf=f((PM,$f)=>{"use strict";var uP=Rf();$f.exports=uP});var as=f((AM,Mf)=>{"use strict";var cP=Lf();Mf.exports=cP});var im=f(()=>{"use strict";var _P=Pe(),NP=Gr(),FP=Da(),qP=Ca(),UP=tn();_P({target:"Array",proto:!0},{at:function(e){var t=NP(this),r=FP(t),a=qP(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});UP("at")});var sm=f((BC,am)=>{"use strict";im();var HP=is();am.exports=HP("Array","at")});var om=f((VC,nm)=>{"use strict";var jP=sm();nm.exports=jP});var di=f((OC,um)=>{"use strict";var GP=om();um.exports=GP});var ib=f(()=>{"use strict"});var ab=f(()=>{"use strict"});var nb=f((OV,sb)=>{"use strict";var JA=Ee(),XA=rr(),ZA=te(),ek=ZA("match");sb.exports=function(i){var e;return JA(i)&&((e=i[ek])!==void 0?!!e:XA(i)==="RegExp")}});var ub=f((_V,ob)=>{"use strict";var tk=Jr(),rk=String;ob.exports=function(i){if(tk(i)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return rk(i)}});var lb=f((NV,cb)=>{"use strict";var ik=Ye();cb.exports=function(){var i=ik(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 hb=f((FV,pb)=>{"use strict";var ak=ge(),sk=_e(),nk=qr(),ok=lb(),db=RegExp.prototype;pb.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in db)&&!sk(i,"flags")&&nk(db,i)?ak(ok,i):e}});var mb=f((qV,fb)=>{"use strict";var fu=ne(),uk=Gr(),ck=Math.floor,pu=fu("".charAt),lk=fu("".replace),hu=fu("".slice),dk=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,pk=/\$([$&'`]|\d{1,2})/g;fb.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,c=pk;return a!==void 0&&(a=uk(a),c=dk),lk(s,c,function(u,d){var l;switch(pu(d,0)){case"$":return"$";case"&":return i;case"`":return hu(e,0,t);case"'":return hu(e,n);case"<":l=a[hu(d,1,-1)];break;default:var p=+d;if(p===0)return u;if(p>o){var h=ck(p/10);return h===0?u:h<=o?r[h-1]===void 0?pu(d,1):r[h-1]+pu(d,1):u}l=r[p-1]}return l===void 0?"":l})}});var Sb=f(()=>{"use strict";var hk=Pe(),fk=ge(),bu=ne(),bb=Nr(),mk=U(),bk=ir(),gk=nb(),wr=ub(),Sk=Hr(),vk=hb(),yk=mb(),Tk=te(),Ik=Oe(),Ek=Tk("replace"),xk=TypeError,mu=bu("".indexOf),Pk=bu("".replace),gb=bu("".slice),Ak=Math.max;hk({target:"String",proto:!0},{replaceAll:function(e,t){var r=bb(this),a,s,n,o,c,u,d,l,p,h,m=0,b="";if(!bk(e)){if(a=gk(e),a&&(s=wr(bb(vk(e))),!~mu(s,"g")))throw new xk("`.replaceAll` does not allow non-global regexes");if(n=Sk(e,Ek),n)return fk(n,e,r,t);if(Ik&&a)return Pk(wr(r),e,t)}for(o=wr(r),c=wr(e),u=mk(t),u||(t=wr(t)),d=c.length,l=Ak(1,d),p=mu(o,c);p!==-1;)h=u?wr(t(c,p,o)):yk(c,o,p,[],void 0,t),b+=gb(o,m,p)+h,m=p+d,p=p+l>o.length?-1:mu(o,c,p+l);return m<o.length&&(b+=gb(o,m)),b}})});var yb=f((jV,vb)=>{"use strict";ib();ab();Sb();var kk=is();vb.exports=kk("String","replaceAll")});var Ib=f((GV,Tb)=>{"use strict";var wk=yb();Tb.exports=wk});var xb=f((WV,Eb)=>{"use strict";var Rk=Ib();Eb.exports=Rk});var Ju="2.0.108-dev.9969cb23.0";var se=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(se||{}),ft=(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))(ft||{});var Ta=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(Ta||{}),zs=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(zs||{});var Ks=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Ks||{});import{assertNever as ic,assertNonNullable as zg,isNonNullable as Ia,ValueSubject as Js,Subject as Kg,Subscription as Jg,merge as Xg,observableFrom as Zg,fromEvent as Zu,map as ec,tap as tc,filterChanged as eS,isNullable as Xs,ErrorCategory as rc}from"@vkontakte/videoplayer-shared";var Xu=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 Ea=class{constructor(e){this.connection$=new Js(void 0);this.castState$=new Js("NOT_AVAILABLE");this.errorEvent$=new Kg;this.realCastState$=new Js("NOT_AVAILABLE");this.subscription=new Jg;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=Ia(window.chrome?.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},a||Xu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:rc.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(){Ia(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Xs(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Xs(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(Zu(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 ic(a.sessionState)}})).add(Xg(Zu(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(tc(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),ec(a=>a.castState)),Zg([r.getCastState()])).pipe(eS(),ec(tS),tc(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=Ia(this.connection$.getValue());if(s&&!n){let o=r.getCurrentSession();zg(o);let c=o.getCastDevice(),u=o.getMediaSession()?.media?.contentId;(Xs(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"?Ia(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:rc.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},tS=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 ic(i)}};var yg=We(Zn(),1);var Uf=We(as(),1);import{assertNever as Cf}from"@vkontakte/videoplayer-shared";var J=(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:Cf(t)}return i},No=(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:Cf(e)}};var I=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};import{isNonNullable as lP,Subject as ss,merge as Df}from"@vkontakte/videoplayer-shared";var L=class{constructor(e){this.transitionStarted$=new ss;this.transitionEnded$=new ss;this.transitionUpdated$=new ss;this.forceChanged$=new ss;this.stateChangeStarted$=Df(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Df(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||lP(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 dP}from"@vkontakte/videoplayer-shared";var Bf=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 dP(i)}};import{assertNever as vr,assertNonNullable as _t,debounce as Vf,ErrorCategory as Of,fromEvent as Nt,isNonNullable as _f,map as Nf,merge as Ff,observableFrom as pP,Subject as hP,Subscription as Fo,timeout as fP,getHighestQuality as mP}from"@vkontakte/videoplayer-shared";var bP=5,gP=5,SP=500,qf=7e3,ui=class{constructor(e){this.subscription=new Fo;this.loadMediaTimeoutSubscription=new Fo;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:vr(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:vr(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:vr(e)}break}default:vr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Bf(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 Fo;this.subscription.add(e),this.subscription.add(Ff(this.videoState.stateChangeStarted$.pipe(Nf(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(Nf(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 hP;e.add(a.pipe(Vf(SP)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Nt(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)>bP)&&a.next(o),s=o})),e.add(Nt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Nt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Nt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(Nt(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<gP&&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:vr(n)}}),t(Nt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(Nt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=Ff(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,pP(["init"])).pipe(Vf(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];_t(u);let d=mP(Object.keys(u));_t(d);let l=u[d];_t(l),r=l,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let u=t[e];_t(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];_t(u),r=u.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let u=t[e];_t(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];_t(u),r=J(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:Of.VIDEO_PIPELINE,message:u,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return vr(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 _f(o)&&(n.metadata.title=o),_f(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(fP(qf).subscribe(()=>s(`timeout(${qf})`)))});(0,Uf.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:Of.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as jf}from"@vkontakte/videoplayer-shared";import{clearVideoElement as vP}from"@vkontakte/videoplayer-shared";var Hf=i=>{try{i.pause(),i.playbackRate=0,vP(i),i.remove()}catch(e){console.error(e)}};import{fromEvent as yP,Subscription as TP}from"@vkontakte/videoplayer-shared";var qo=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)}},Uo=window.WeakMap?new WeakMap:new qo,Ho=window.WeakMap?new WeakMap:new Map,IP=(i,e=20)=>{let t=0;return yP(i,"ratechange").subscribe(r=>{t++,t>=e&&(i.currentTime=i.currentTime,t=0)})},oe=(i,{audioVideoSyncRate:e})=>{let t=i.querySelector("video"),r=!!t;t?jf(t):(t=document.createElement("video"),i.appendChild(t)),Uo.set(t,r);let a=new TP;return a.add(IP(t,e)),Ho.set(t,a),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},ue=i=>{Ho.get(i)?.unsubscribe(),Ho.delete(i);let t=Uo.get(i);Uo.delete(i),t?jf(i):Hf(i)};import{assertNonNullable as ci,isNonNullable as ze,isNullable as PP,fromEvent as yr,merge as Gf,observableFrom as Wf,filterChanged as Yf,map as li,Subject as Qf,Subscription as AP,ValueSubject as kP,ErrorCategory as wP}from"@vkontakte/videoplayer-shared";import{isNonNullable as jo,isNullable as EP,Subscription as xP}from"@vkontakte/videoplayer-shared";var ns=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),c=EP(a),u=new xP;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},Qe=(i,e,t)=>ns(e,()=>i.loop,r=>{jo(r)&&(i.loop=r)},{onError:t}),ce=(i,e,t,r)=>ns(e,()=>({muted:i.muted,volume:i.volume}),a=>{jo(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}),Ae=(i,e,t,r)=>ns(e,()=>i.playbackRate,a=>{jo(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),bt=ns;var RP=i=>["__",i.language,i.label].join("|"),$P=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},Go=class i{constructor(){this.available$=new Qf;this.current$=new kP(void 0);this.error$=new Qf;this.subscription=new AP;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:wP.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(bt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{ze(s)&&this.setInternal(s)},{equal:(s,n)=>ze(s)&&ze(n)&&s.length===n.length&&s.every(({id:o},c)=>o===n[c].id),changed$:this.available$.pipe(li(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(bt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{ze(s)&&this.setExternal(s)},{equal:(s,n)=>ze(s)&&ze(n)&&s.length===n.length&&s.every(({id:o},c)=>o===n[c].id),changed$:this.available$.pipe(li(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(bt(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(bt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){ci(this.video);let{textTracks:e}=this.video;this.subscription.add(yr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(Gf(yr(e,"addtrack"),yr(e,"removetrack"),Wf(["init"])).pipe(li(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Yf((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add(Gf(yr(e,"change"),Wf(["init"])).pipe(li(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),li(r=>r&&this.htmlTextTrackToITextTrack(r).id),Yf()).subscribe(this.current$));let t=r=>this.applyCueSettings(r.target?.activeCues??null);this.subscription.add(yr(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(yr(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;ze(t.align)&&(a.align=t.align),ze(t.position)&&(a.position=t.position),ze(t.size)&&(a.size=t.size),ze(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){ci(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:RP(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){ci(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(PP(e)||!$P(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){ci(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){ci(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)}},ke=Go;var it=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var zf=i=>{let e=i;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Wo=i=>{let e=zf(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},Kf=i=>{let e=zf(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};import{fromEvent as we,map as gt,merge as Xf,filterChanged as MP,isNonNullable as Zf,Subject as CP,filter as em,mapTo as tm,combine as DP,once as BP,ErrorCategory as VP,ValueSubject as rm,clientChecker as OP}from"@vkontakte/videoplayer-shared";var LP=3,Jf=(i,e,t=LP)=>{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 le=i=>{let e=y=>we(i,y).pipe(tm(void 0)),r=Xf(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(y=>we(i,y))).pipe(gt(y=>y.type==="ended"?i.readyState<2:i.readyState<3),MP()),a=Xf(we(i,"progress"),we(i,"timeupdate")).pipe(gt(()=>Jf(i.buffered,i.currentTime))),s=OP.isSafari?DP({play:e("play").pipe(BP()),playing:e("playing")}).pipe(tm(void 0)):e("playing"),n=we(i,"volumechange").pipe(gt(()=>({muted:i.muted,volume:i.volume}))),o=we(i,"ratechange").pipe(gt(()=>i.playbackRate)),c=we(i,"error").pipe(em(()=>!!(i.error||i.played.length)),gt(()=>{let y=i.error;return{id:y?`MediaError#${y.code}`:"HtmlVideoError",category:VP.VIDEO_PIPELINE,message:y?y.message:"Error event from HTML video element",thrown:i.error??void 0}})),u=we(i,"timeupdate").pipe(gt(()=>i.currentTime)),d=new CP,l=.3,p;u.subscribe(y=>{i.loop&&Zf(p)&&Zf(y)&&p>=i.duration-l&&y<=l&&d.next(p),p=y});let h=e("pause").pipe(em(()=>!i.error&&p!==i.duration)),m=we(i,"enterpictureinpicture"),b=we(i,"leavepictureinpicture"),g=new rm(Kf(i));m.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new rm(Wo(i));return we(i,"fullscreenchange").pipe(gt(()=>Wo(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$:we(i,"durationchange").pipe(gt(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v}};import{VideoQuality as St}from"@vkontakte/videoplayer-shared";var vt=i=>{switch(i){case"mobile":return St.Q_144P;case"lowest":return St.Q_240P;case"low":return St.Q_360P;case"sd":case"medium":return St.Q_480P;case"hd":case"high":return St.Q_720P;case"fullhd":case"full":return St.Q_1080P;case"quadhd":case"quad":return St.Q_1440P;case"ultrahd":case"ultra":return St.Q_2160P}};var Ft=We(di(),1);import{isNonNullable as de,isNullable as Qo,now as bm,isHigher as zo,isHigherOrEqual as pm,isInvariantQuality as hm,isLower as Ko,isLowerOrEqual as fm,videoSizeToQuality as WP,assertNotEmptyArray as gm,assertNonNullable as YP}from"@vkontakte/videoplayer-shared";var Yo=!1,at={},cm=i=>{Yo=i},lm=()=>{at={}},dm=i=>{i(at)},pi=(i,e)=>{Yo&&(at.meta=at.meta??{},at.meta[i]=e)},re=class{constructor(e){this.name=e}next(e){if(!Yo)return;at.series=at.series??{};let t=at.series[this.name]??[];t.push([Date.now(),e]),at.series[this.name]=t}};var QP=new re("best_bitrate"),Sm=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;var Jo=i=>(e,t)=>i*(Number(e.bitrate)-Number(t.bitrate)),hi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=bm()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},vm='Assertion "ABR Tracks is empty array" failed',os=(i,e,t,r)=>{let a=[...e].sort(Jo(1)),s=[...t].sort(Jo(1)),n=s.filter(c=>de(c.bitrate)&&de(i.bitrate)?i.bitrate/c.bitrate>r:!0),o=(0,Ft.default)(s,Math.round(s.length*a.indexOf(i)/(a.length+1)))??(0,Ft.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,Ft.default)(n,-1):(0,Ft.default)(s,0)},mm=i=>"quality"in i,ym=(i,e,t,r)=>{let a=t&&r&&r.history[t.id]&&bm()-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=mm(s)?"video":"audio",o=mm(s)?s.quality:s.bitrate;return e({message:`
|
|
7
|
+
[last ${n} selected] ${o}
|
|
8
|
+
`}),s}return r?.recordSwitch(t),t},yt=(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})=>{gm(i,vm);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&&WP(m),g=r.considerPlaybackRate&&de(o)?o:1,v=i.filter(w=>!hm(w.quality)).sort((w,R)=>zo(w.quality,R.quality)?-1:1),k=(0,Ft.default)(v,-1)?.quality,y=(0,Ft.default)(v,0)?.quality,S=Qo(a)||de(a.min)&&de(a.max)&&Ko(a.max,a.min)||de(a.min)&&y&&zo(a.min,y)||de(a.max)&&k&&Ko(a.max,k),T=g*Sm(n??.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),E={},O=v.filter(w=>{if(!(b?Ko(w.quality,b):!0))return E[w.quality]="FitsContainer",!1;if(!(de(t)&&isFinite(t)&&de(w.bitrate)?t-s>=w.bitrate*T:!0))return E[w.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&de(r.minBufferToSwitchUp)&&c&&!hm(c.quality)&&(n??0)<r.minBufferToSwitchUp&&zo(w.quality,c.quality))return E[w.quality]="Buffer",!1;if(!!l&&pm(w.quality,l))return E[w.quality]="DroppedFramesLimit",!1;let ae=S||(Qo(a.max)||fm(w.quality,a.max))&&(Qo(a.min)||pm(w.quality,a.min)),x=de(d)&&!d?fm(w.quality,r.backgroundVideoQualityLimit):!0;return!ae||!x?(E[w.quality]="FitsQualityLimits",!1):!0})[0];O&&O.bitrate&&QP.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(w=>`{ id: ${w.id}, quality: ${w.quality}, bitrate: ${w.bitrate} }`).join(`
|
|
9
12
|
`)}
|
|
10
13
|
|
|
11
14
|
[tuning]
|
|
12
|
-
${Object.entries(r??{}).map(([
|
|
15
|
+
${Object.entries(r??{}).map(([w,R])=>`${w}: ${R}`).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(([w,R])=>`${w}: ${R}`).join(`
|
|
31
34
|
`)||"All tracks are available"}
|
|
32
35
|
|
|
33
|
-
[best track] ${
|
|
34
|
-
[selected track] ${
|
|
35
|
-
`});let
|
|
36
|
-
[
|
|
37
|
-
`}),P}return u?.recordSwitch(D),D},lt=HP;var W=i=>new URL(i).hostname;import{assertNever as cm,assertNonNullable as dm,combine as lk,debounce as ck,ErrorCategory as pm,filter as hm,filterChanged as dk,isNonNullable as Yo,map as Za,merge as fm,observableFrom as pk,once as hk,Subscription as fk,ValueSubject as zo,videoQualityToHeight as mk,videoSizeToQuality as bk}from"@vkontakte/videoplayer-shared";var sm=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(!sm(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{await i.play()}catch(r){return sm(r)&&(i.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as Ka,isNullable as QP,assertNonNullable as si}from"@vkontakte/videoplayer-shared";import{isNonNullable as nm,assertNonNullable as za,now as jP}from"@vkontakte/videoplayer-shared";function Y(){return jP()}function jo(i){return Y()-i}function Go(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 om(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function dr(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,l=!1,u=0,d,c,p=!1,h="arraybuffer",m=7e3,b=2e3,S=()=>{if(l)return;za(d);let L=jo(d),q;if(L<b){q=b-L,setTimeout(S,q);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new a,C()},v=L=>(s=L,A),w=L=>(c=L,A),T=()=>(h="json",A),g=()=>{if(!l){if(--u>=0){S(),r&&r();return}l=!0,c&&c(),t&&t()}},y=L=>(p=L,A),C=()=>{d=Y(),n=new a,n.open("get",i);let L=0,q,Pe=0,de=()=>(za(d),Math.max(d,Math.max(q||0,Pe||0)));if(s&&n.addEventListener("progress",k=>{let R=Y();s.updateChunk&&k.loaded>L&&(s.updateChunk(de(),k.loaded-L),L=k.loaded,q=R)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>g())),n.addEventListener("load",()=>{if(l)return;za(n);let k=n.status;if(k>=200&&k<300){if(n.response.byteLength&&s){let R=n.response.byteLength-L;R&&s.updateChunk&&s.updateChunk(de(),R)}n.responseType==="json"&&!Object.values(n.response).length?g():(c&&c(),e(n.response))}else g()}),n.addEventListener("error",()=>{g()}),p){let k=()=>{za(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Pe=Y(),n.removeEventListener("readystatechange",k))};n.addEventListener("readystatechange",k)}return n.responseType=h,n.send(),A},A={withBitrateReporting:v,withParallel:y,withJSONResponse:T,withRetryCount:L=>(u=L,A),withRetryInterval:(L,q)=>(nm(L)&&(b=L),nm(q)&&(m=q),A),withTimeout:L=>(o=L,A),withFinally:w,send:C,abort:()=>{n&&(n.abort(),n=void 0),l=!0,c&&c()}};return A}var ii=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 ai=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=Y(),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=Y()-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=dr(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=Y()}_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=Y();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 Ja=1e4,Qo=3;var WP=6e4,YP=10,zP=1,KP=500,ni=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 ii(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Go(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=Go(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||Ka(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=()=>{om(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 ai(Qo,Ja,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,d=!1,c=()=>{let g=s&&(!d||d===this.rep);return g||t("Not running!"),g},p=(g,y,C)=>{l&&l.abort(),l=dr(this.urlResolver.resolve(g,!1),y,C,()=>this._retryCallback()).withTimeout(Ja).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Qo).withFinally(()=>{l=null}).send()},h=(g,y,C)=>{si(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(g,!1),y,C,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=g=>{let y=r.playbackRate;r.playbackRate!==g&&(t(`Playback rate switch: ${y}=>${g}`),r.playbackRate=g)},b=g=>{this.lowLatency=g,t(`lowLatency changed to ${g}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let g=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let C=Y()-1e4,x=0;for(let N=0;N<this.bufferStates.length;N++){let P=this.bufferStates[N];g=Math.min(g,P.buf),P.ts<C&&x++}this.bufferStates.splice(0,x),t(`update playback rate; minBuffer=${g} drop=${x} jitter=${this.sourceJitter}`);let D=g-zP;this.sourceJitter>=0?D-=this.sourceJitter/2:this.sourceJitter-=1,D>3?m(1.15):D>1?m(1.1):D>.3?m(1.05):m(1)}},v=g=>{let y,C=()=>y&&y.start?y.start.length:0,x=k=>y.start[k]/1e3,D=k=>y.dur[k]/1e3,N=k=>y.fragIndex+k,P=(k,R)=>({chunkIdx:N(k),startTS:x(k),dur:D(k),discontinuity:R}),A=()=>{let k=0;if(y&&y.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 pe=y.dur.length-1;for(;pe>=0&&(z-=y.dur[pe],!(z<=0));--pe);k=Math.min(pe,y.dur.length-1-G),k=Math.max(k,0)}return P(k,!0)},L=k=>{let R=C();if(!(R<=0)){if(Ka(k)){for(let G=0;G<R;G++)if(x(G)>k)return P(G)}return A()}},q=k=>{let R=C(),G=k?k.chunkIdx+1:0,z=G-y.fragIndex;if(!(R<=0)){if(!k||z<0||z-R>YP)return t(`Resync: offset=${z} bChunks=${R} chunk=`+JSON.stringify(k)),A();if(!(z>=R))return P(G-y.fragIndex,!1)}},Pe=(k,R,G)=>{u&&u.abort(),u=dr(this.urlResolver.resolve(k,!0,this.lowLatency),R,G,()=>this._retryCallback()).withTimeout(Ja).withRetryCount(Qo).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(k,R)=>{Pe(g,G=>{if(!c())return;y=G;let z=!!y.lowLatency;z!==this.lowLatency&&b(z);let pe=0;for(let Oe=0;Oe<y.dur.length;++Oe)pe+=y.dur[Oe];pe>0&&(si(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(pe/y.dur.length)),a({name:"index",zeroTime:y.zeroTime,shiftDuration:y.shiftDuration}),this.sourceJitter=y.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,y.jitter/1e3)):1,k(L(R))},()=>this._handleNetworkError())},nextChunk:q}},w=()=>{s=!1,o&&o.abort(),l&&l.abort(),u&&u.abort(),si(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:g=>{let{videoElement:y,logger:C}=this.params,x=v(e.jidxUrl),D,N,P,A,L=0,q,Pe,de,k=()=>{q&&(clearTimeout(q),q=void 0);let B=Math.max(KP,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Q=L+B,te=Y(),ke=Math.min(1e4,Q-te);L=te;let Ze=()=>{u||c()&&x.seek(()=>{c()&&(L=Y(),R(),k())})};ke>0?q=window.setTimeout(()=>{this.paused?k():Ze()},ke):Ze()},R=()=>{let B;for(;B=x.nextChunk(A);)A=B,qt(B);let Q=x.nextChunk(P);if(Q){if(P&&Q.discontinuity){C("Detected discontinuity; restarting playback"),this.paused?k():(w(),this._initPlayerWith(e));return}Oe(Q)}else k()},G=(B,Q)=>{if(!c()||!this.sourceBuffer)return;let te,ke,Ze,Ut=et=>{window.setTimeout(()=>{c()&&G(B,Q)},et)};if(this.sourceBuffer.updating)C("Source buffer is updating; delaying appendBuffer"),Ut(100);else{let et=Y(),Ht=y.currentTime;!this.paused&&y.buffered.length>1&&Pe===Ht&&et-de>500&&(C("Stall suspected; trying to fix"),this._fixupStall()),Pe!==Ht&&(Pe=Ht,de=et);let Pr=this._getBufferSizeSec();if(Pr>30)C(`Buffered ${Pr} seconds; delaying appendBuffer`),Ut(2e3);else try{this.sourceBuffer.appendBuffer(B),this.videoPlayStarted?(this.bufferStates.push({ts:et,buf:Pr}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Q&&Q()}catch(ia){if(ia.name==="QuotaExceededError")C("QuotaExceededError; delaying appendBuffer"),Ze=this.sourceBuffer.buffered.length,Ze!==0&&(te=this.sourceBuffer.buffered.start(0),ke=Ht,ke-te>4&&this.sourceBuffer.remove(te,ke-3)),Ut(1e3);else throw ia}}},z=()=>{N&&D&&(C([`Appending chunk, sz=${N.byteLength}:`,JSON.stringify(P)]),G(N,function(){N=null,R()}))},pe=B=>e.fragUrlTemplate.replace("%%id%%",B.chunkIdx),Oe=B=>{c()&&h(pe(B),(Q,te)=>{if(c()){if(te/=1e3,N=Q,P=B,n=B.startTS,te){let ke=Math.min(10,B.dur/te);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ke:ke}z()}},()=>this._handleNetworkError())},qt=B=>{c()&&(si(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(pe(B),!1)))},bt=B=>{c()&&(e.cachedHeader=B,G(B,()=>{D=!0,z()}))};s=!0,x.seek(B=>{if(c()){if(L=Y(),!B){k();return}A=B,!QP(g)||B.startTS>g?Oe(B):(P=B,R())}},g),e.cachedHeader?bt(e.cachedHeader):p(e.headerUrl,bt,()=>this._handleNetworkError())},stop:w,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),Ka(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,si(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Ka(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=c=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(h=this._getBufferSizeSec(),m=c/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(c)}`);return}p=this._selectQuality(c),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${c}`)},s={updateChunk:(p,h)=>{let m=Y();if(this.chunkRateEstimator.addInterval(p,m,h)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:S}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,l=!0,u=()=>{let c=s.get();if(c&&o&&this.autoQuality){if(l&&c>o&&jo(n)<3e4)return;r(c)}l=this.autoQuality};return{updateChunk:(c,p)=>{let h=s.updateChunk(c,p);return h&&u(),h},notifySwitch:c=>{let p=Y();c<o&&(n=p),o=c}}}_fetchManifest(e,t,r){this.manifestRequest=dr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Ja).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))},WP))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as JP,filter as um,fromEvent as XP,interval as ZP,isHigher as ek,isInvariantQuality as tk,isLower as rk,merge as ik,Subject as lm,Subscription as ak}from"@vkontakte/videoplayer-shared";var Wo=class{constructor(){this.onDroopedVideoFramesLimit$=new lm;this.subscription=new ak;this.playing=!1;this.tracks=[];this.forceChecker$=new lm;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&&!tk(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&&ek(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(XP(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=ZP(this.droppedFramesChecker.checkTime).pipe(um(()=>this.playing),um(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(JP(this.droppedFramesChecker.checkTime)),r=ik(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])=>rk(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}},Xa=Wo;import{map as sk,Observable as nk}from"@vkontakte/videoplayer-shared";import{fromEvent as ok}from"@vkontakte/videoplayer-shared";var oi=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var uk=(i,e)=>new nk(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(l=>t.next(l.isIntersecting||oi()))},{...r,...e});a.observe(i);let s=ok(document,"visibilitychange").pipe(sk(n=>!document.hidden||oi())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),xe=uk;var Sk=["paused","playing","ready"],gk=["paused","playing","ready"],ui=class{constructor(e){this.subscription=new fk;this.videoState=new $("stopped");this.representations$=new zo([]);this.textTracksManager=new Ie;this.droppedFramesManager=new Xa;this.maxSeekBackTime$=new zo(1/0);this.zeroTime$=new zo(void 0);this.liveOffset=new Qe;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:pm.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=ot(a.name)??bk(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),Yo(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(gk.includes(e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&Sk.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 cm(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:pm.WTF,message:"DashLiveProvider internal logic error",thrown:a})};fm(this.videoState.stateChangeStarted$.pipe(Za(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Za(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(Za(a=>a.map(({track:s})=>s)),hm(a=>!!a.length),hk()).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(dk(),Za(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(lk({zeroTime:this.zeroTime$.pipe(hm(Yo)),position:r.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(Ne(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(Te(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(xe(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&mk(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 cm(a.to)}},t)).add(fm(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,pk(["init"])).pipe(ck(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 ni({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&&Yo(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,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:d})=>d.id===s)?.representation;dm(u,"Representations missing"),this.dash.startPlay(u,r)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:r})=>r.id===e.id)?.representation;dm(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 mm=ui;var Ye=(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 UA,assertNonNullable as HA,debounce as jA,ErrorCategory as Iu,filter as Mb,filterChanged as Eu,fromEvent as GA,isLowerOrEqual as Cb,isNonNullable as QA,isInvariantQuality as WA,map as Db,merge as vs,observableFrom as YA,observeElementSize as zA,once as Ob,Subscription as KA,ValueSubject as JA}from"@vkontakte/videoplayer-shared";var es=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}},pr=class extends es{constructor(){super(),this.listeners||es.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)}},li=class{constructor(){Object.defineProperty(this,"signal",{value:new pr,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&&(li.prototype[Symbol.toStringTag]="AbortController",pr.prototype[Symbol.toStringTag]="AbortSignal");function ts(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 Ko(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!ts({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 c;d&&d.signal&&(c=d.signal,delete d.signal);let p=new t(u,d);return c&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),p},s.prototype=t.prototype);let n=e;return{fetch:(l,u)=>{let d=s&&s.prototype.isPrototypeOf(l)?l.signal:u?u.signal:void 0;if(d){let c;try{c=new DOMException("Aborted","AbortError")}catch{c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);let p=new Promise((h,m)=>{d.addEventListener("abort",()=>m(c),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([p,n(l,u)])}return n(l,u)},Request:s}}var ci=ts({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),bm=ci?Ko({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ze=ci?bm.fetch:window.fetch,XD=ci?bm.Request:window.Request,Ke=ci?li:window.AbortController,ZD=ci?pr:window.AbortSignal;var vm=Ve(ti(),1);var Je=()=>window.ManagedMediaSource||window.MediaSource,rs=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Sm=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),gm=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as ns,clientChecker as as}from"@vkontakte/videoplayer-shared";var ss=document.createElement("video"),Tk='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Ik='video/mp4; codecs="hev1.1.6.L93.B0"',ym='video/webm; codecs="vp09.00.10.08"',Tm='video/webm; codecs="av01.0.00M.08"',Ek='audio/mp4; codecs="mp4a.40.2"',xk='audio/webm; codecs="opus"',Rt={mms:rs(),mse:Sm(),hls:!!(ss.canPlayType?.("application/x-mpegurl")||ss.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},le={mp4:!!ss.canPlayType?.("video/mp4"),webm:!!ss.canPlayType?.("video/webm"),cmaf:!0},ce={h264:!!Je()?.isTypeSupported?.(Tk),h265:!!Je()?.isTypeSupported?.(Ik),vp9:!!Je()?.isTypeSupported?.(ym),av1:!!Je()?.isTypeSupported?.(Tm),aac:!!Je()?.isTypeSupported?.(Ek),opus:!!Je()?.isTypeSupported?.(xk)},hr=(ce.h264||ce.h265)&&ce.aac,Lt,Pk=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:Tm}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:ym}})]);Lt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{Pk()}catch(i){console.error(i)}var fr=Rt.hls&&le.mp4,Im=()=>Object.keys(ce).filter(i=>ce[i]),Em=(i,e=!1,t=!1)=>{let r=Rt.mse||Rt.mms&&t;return i.filter(a=>{switch(a){case"DASH_SEP":return r&&le.mp4&&hr;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&&hr||le.webm&&(ce.vp9||ce.av1)&&(ce.opus||ce.aac));case"DASH_LIVE":return Rt.mse&&le.mp4&&hr;case"DASH_LIVE_CMAF":return r&&le.mp4&&hr&&le.cmaf;case"DASH_ONDEMAND":return r&&le.mp4&&hr;case"HLS":case"HLS_ONDEMAND":return fr||e&&Rt.mse&&le.mp4&&hr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return fr;case"MPEG":return le.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Rt.webrtc&&Rt.ws&&ce.h264&&(le.mp4||le.webm);default:return ns(a)}})},is=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 Lt?Lt[t].smooth?[t,e]:Lt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Lt?Lt[t].powerEfficient?[t,e]:Lt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:ns(i)}return[e,t]},xm=({webmCodec:i,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...is(i),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],a=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(as.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",...is(i),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...is(i),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...is(i),...a,"HLS","HLS_ONDEMAND"];default:ns(e)}return fr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Pm=({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=as.isMac&&as.isSafari;if(as.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:ns(i)}else fr&&!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"]},Jo=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],km=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,vm.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return i.values().next().value.split(".").at(0)}};import{ErrorCategory as di}from"@vkontakte/videoplayer-shared";var Am=i=>{if(!i)return{id:"EmptyResponse",category:di.PARSER,message:"Empty response"};if(i.length<=2&&i.match(/^\d+$/))return{id:`UVError#${i}`,category:di.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:di.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:di.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:di.PARSER,message:"Response is valid XML, but parser failed"}};var pi=(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 vu,assertNonNullable as Nt,combine as hs,ErrorCategory as dt,filter as fs,filterChanged as Pb,fromEvent as Ir,interval as yu,isNonNullable as kb,map as Tu,merge as Er,Subject as Ab,Subscription as wb,tap as DA,throttle as OA,clientChecker as BA,ValueSubject as Z,flattenObject as qi,getTraceSubscriptionMethod as VA}from"@vkontakte/videoplayer-shared";var yr=Ve(ti(),1);var kk=(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)},Ak=i=>window.clearTimeout(i),wm=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Xo=wm?kk:window.requestIdleCallback,h0=wm?Ak:window.cancelIdleCallback;var gb=Ve(Ga(),1);import{assertNever as wk,ErrorCategory as Rm,clientChecker as Zo,Subject as Lm}from"@vkontakte/videoplayer-shared";var Rk=16,$m=!1;try{$m=Zo.isSafari&&!!Zo.macVersion&&Zo.macVersion<=Rk}catch(i){console.error(i)}var eu=class{constructor(e){this.bufferFull$=new Lm;this.error$=new Lm;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:Rm.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;$m&&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:Rm.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:wk(t)}}},Mm=eu;var tu=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 vr,assertNonNullable as qe,ErrorCategory as Bt,fromEvent as fu,getExponentialDelay as mu,isNonNullable as Sb,isNullable as Ce,once as kA,Subject as AA,Subscription as wA,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 mr=class extends _{};var hi=class extends _{};var fi=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 mi=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var bi=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Si=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 $t=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 l=a>>>28,u=a<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:l,SAPDeltaTime:u})}}};var gi=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var vi=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var yi=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 Ti=class extends j{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Ii=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 Ei=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var xi=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 Pi=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ki=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ai=class extends j{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var wi=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ri=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 Li=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 $i=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 $k={ftyp:fi,moov:mi,moof:bi,mdat:Si,sidx:$t,trak:gi,mdia:Ei,mfhd:Ai,tkhd:xi,traf:wi,tfhd:Ri,tfdt:Li,trun:$i,minf:Pi,sv3d:vi,st3d:yi,prhd:Ti,proj:ki,equi:Ii,uuid:hi,unknown:mr},Mt=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=$k[e];return r?new r(t,new i):new mr(t,new i)}};var br=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 Ck=new TextDecoder("ascii"),Dk=i=>Ck.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",Ok=i=>{let e=new $t(i,new Mt),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})},Bk=(i,e)=>{let r=new Mt().parse(i),a=new br(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,c=l.source.byteOffset-o.source.byteOffset+l.size;return new DataView(i.buffer,u,c)},Vk=(i,e)=>{let r=new Mt().parse(i),s=new br(r).findAll("traf"),n=s[s.length-1].children.find(c=>c.type==="tfhd"),o=s[s.length-1].children.find(c=>c.type==="tfdt"),l=s[s.length-1].children.find(c=>c.type==="trun"),u=0;return l.sampleDuration.length?u=l.sampleDuration.reduce((c,p)=>c+p,0):u=n.defaultSampleDuration*l.sampleCount,(Number(o.baseMediaDecodeTime)+u)/e*1e3},_k=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 Mt().parse(i),a=new br(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},Cm={validateData:Dk,parseInit:_k,getIndexRange:()=>{},parseSegments:Ok,parseFeedableSegmentChunk:Bk,getSegmentEndTime:Vk};import{assertNonNullable as iu,isNonNullable as Vm,isNullable as Fk}from"@vkontakte/videoplayer-shared";import{assertNever as Nk}from"@vkontakte/videoplayer-shared";var Dm={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"}},Om=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=Mi(i,t),a=r in Dm,s=a?Dm[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,d=Mi(l),c=u*2**((o-1)*8)+d,p=t+o,h;return p+c>i.byteLength?h=new DataView(i.buffer,i.byteOffset+p):h=new DataView(i.buffer,i.byteOffset+p,c),{tag:a?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+c,value:h,valueSize:c}},Mi=(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},Me=(i,e)=>{switch(e){case"int":return i.getInt8(0);case"uint":return Mi(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:Nk(e)}},Ct=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=Om(r);if(!e(a))return;a.type==="master"&&Ct(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},Bm=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=Om(i);return Ct(a.value,({tag:s,type:n,value:o})=>(s===17143?e=Me(o,n):s===17026?t=Me(o,n):s===17029&&(r=Me(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var _m=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],qk=[231,22612,22743,167,171,163,160,175],Uk=i=>{let e,t,r,a,s=!1,n=!1,o=!1,l,u,d=!1,c=0;return Ct(i,({tag:p,type:h,value:m,valueSize:b})=>{if(p===21419){let S=Me(m,h);u=Mi(S)}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=Me(m,h):p===17545?a=Me(m,h):p===21420&&u===475249515?l=Me(m,h):p===374648427?Ct(m,({tag:S,type:v,value:w})=>S===30321?(d=Me(w,v)===1,!1):!0):s&&n&&_m.includes(p)&&(o=!0),!o}),iu(e,"Failed to parse webm Segment start"),iu(t,"Failed to parse webm Segment end"),iu(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:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Hk=i=>{if(Fk(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},jk=(i,e)=>{let t=!1,r=!1,a=o=>Vm(o.time)&&Vm(o.position),s=[],n;return Ct(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=Me(u,l));break;case 183:break;case 241:n&&(n.position=Me(u,l));break;default:t&&_m.includes(o)&&(r=!0)}return!(t&&r)}),n&&a(n)&&s.push(n),s.map((o,l)=>{let{time:u,position:d}=o,c=s[l+1];return{status:"none",time:{from:u,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},Gk=i=>{let e=0,t=!1;try{Ct(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):qk.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},Nm={validateData:Bm,parseInit:Uk,getIndexRange:Hk,parseSegments:jk,parseFeedableSegmentChunk:Gk};var Sr=i=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(i);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return Nm;case"mp4":return Cm}}throw new ReferenceError(`Unsupported mime type ${i}`)};var cu=Ve(ob(),1);var lu=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 lb,isNullable as cb}from"@vkontakte/videoplayer-shared";var ub=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var db=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},Dt=(i,e)=>{let t=i;t=(0,cu.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,cu.default)(t,n,(o,l)=>cb(s)?o:cb(l)?s:s.padStart(parseInt(l,10),"0"))}return t},hb=(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",d=s.getAttribute("availabilityStartTime"),c=d?new Date(d).getTime():void 0,p,h=s.getAttribute("mediaPresentationDuration"),m=n.getAttribute("duration"),S=s.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=db(h);else if(m){let g=db(m);lb(g)&&(p=g)}else S&&(p=parseInt(S,10));let v=0,w=s.getAttribute("profiles")?.split(",")??[];for(let g of l){let y=g.getAttribute("id")??"id"+(v++).toString(10),C=g.getAttribute("mimeType")??"",x=g.getAttribute("codecs")??"",D=g.getAttribute("contentType")??C?.split("/")[0],N=g.getAttribute("profiles")?.split(",")??[],P=g.getAttribute("lang")??void 0,A=g.querySelector("Label")?.textContent?.trim()??void 0,L=g.querySelectorAll("Representation"),q=g.querySelector("SegmentTemplate"),Pe=g.querySelector("Role")?.getAttribute("value")??void 0,de=D,k={id:y,language:P,isDefault:Pe==="main",label:A,codecs:x,hdr:de==="video"&&lu(x),mime:C,representations:[]};for(let R of L){let G=R.getAttribute("lang")??void 0,z=R.getAttribute("label")??void 0,pe=R.querySelector("BaseURL")?.textContent?.trim()??"",Oe=new URL(pe||o,e).toString(),qt=R.getAttribute("mimeType")??C,bt=R.getAttribute("codecs")??x??"",B;if(D==="text"){let Q=R.getAttribute("id")||"",te=Q.includes("_auto");B={id:Q,isAuto:te,kind:"text",url:Oe}}else{let Q=R.getAttribute("contentType")??qt?.split("/")[0]??D,te=g.getAttribute("profiles")?.split(",")??[],ke=parseInt(R.getAttribute("width")??"",10),Ze=parseInt(R.getAttribute("height")??"",10),Ut=parseInt(R.getAttribute("bandwidth")??"",10)/1e3,et=R.getAttribute("frameRate")??"",Ht=R.getAttribute("quality")??void 0,Pr=et?ub(et):void 0,ia=R.getAttribute("id")??"id"+(v++).toString(10),kS=Q==="video"?`${Ze}p`:Q==="audio"?`${Ut}Kbps`:bt,AS=`${ia}@${kS}`,wS=[...w,...N,...te],Ds,RS=R.querySelector("SegmentBase"),St=R.querySelector("SegmentTemplate")??q;if(RS){let gt=R.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[vt,Bs]=gt.split("-").map(jt=>parseInt(jt,10)),tt={from:vt,to:Bs},kr=R.querySelector("SegmentBase")?.getAttribute("indexRange"),[Vs,aa]=kr?kr.split("-").map(jt=>parseInt(jt,10)):[],Ar=kr?{from:Vs,to:aa}:void 0;Ds={type:"byteRange",url:Oe,initRange:tt,indexRange:Ar}}else if(St){let gt={representationId:R.getAttribute("id")??void 0,bandwidth:R.getAttribute("bandwidth")??void 0},vt=parseInt(St.getAttribute("timescale")??"",10),Bs=St.getAttribute("initialization")??"",tt=St.getAttribute("media"),kr=parseInt(St.getAttribute("startNumber")??"",10)??1,Vs=Dt(Bs,gt);if(!tt)throw new ReferenceError("No media attribute in SegmentTemplate");let aa=St.querySelectorAll("SegmentTimeline S")??[],Ar=[],jt=0,_s="",Ns=0;if(aa.length){let sa=kr,Ae=0;for(let Gt of aa){let Be=parseInt(Gt.getAttribute("d")??"",10),yt=parseInt(Gt.getAttribute("r")??"",10)||0,na=parseInt(Gt.getAttribute("t")??"",10);Ae=Number.isFinite(na)?na:Ae;let Fs=Be/vt*1e3,$S=Ae/vt*1e3;for(let oa=0;oa<yt+1;oa++){let MS=Dt(tt,{...gt,segmentNumber:sa.toString(10),segmentTime:(Ae+oa*Be).toString(10)}),Nu=($S??0)+oa*Fs,CS=Nu+Fs;sa++,Ar.push({time:{from:Nu,to:CS},url:MS})}Ae+=(yt+1)*Be,jt+=(yt+1)*Fs}Ns=Ae/vt*1e3,_s=Dt(tt,{...gt,segmentNumber:sa.toString(10),segmentTime:Ae.toString(10)})}else if(lb(p)){let Ae=parseInt(St.getAttribute("duration")??"",10)/vt*1e3,Gt=Math.ceil(p/Ae),Be=0;for(let yt=1;yt<Gt;yt++){let na=Dt(tt,{...gt,segmentNumber:yt.toString(10),segmentTime:Be.toString(10)});Ar.push({time:{from:Be,to:Be+Ae},url:na}),Be+=Ae}Ns=Be,_s=Dt(tt,{...gt,segmentNumber:Gt.toString(10),segmentTime:Be.toString(10)})}let LS={time:{from:Ns,to:1/0},url:_s};Ds={type:"template",baseUrl:Oe,segmentTemplateUrl:tt,initUrl:Vs,totalSegmentsDurationMs:jt,segments:Ar,nextSegmentBeyondManifest:LS,timescale:vt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Q||!qt)continue;let Os={video:"video",audio:"audio",text:"text"}[Q];if(!Os)continue;de||=Os,B={id:AS,kind:Os,segmentReference:Ds,profiles:wS,duration:p,bitrate:Ut,mime:qt,codecs:bt,width:ke,height:Ze,fps:Pr,quality:Ht}}k.language||=G,k.label||=z,k.mime||=qt,k.codecs||=bt,k.hdr||=de==="video"&&lu(bt),k.representations.push(B)}de&&a[de].push(k)}return{dynamic:u,liveAvailabilityStartTime:c,duration:p,streams:a}};var Ci=Ve(ti(),1);import{videoSizeToQuality as PA}from"@vkontakte/videoplayer-shared";var fb=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s})=>{let n=(s?ot(s):void 0)??PA({width:e,height:t});return n&&{id:i,quality:n,bitrate:r,size:{width:e,height:t},fps:a}},mb=({id:i,bitrate:e})=>({id:i,bitrate:e}),os=(i,e,t)=>{let r=e.indexOf(i);return(0,Ci.default)(t,Math.round(t.length*r/e.length))??(0,Ci.default)(t,-1)},bb=({language:i,label:e},{id:t,url:r,isAuto:a})=>({id:t,url:r,isAuto:a,type:"internal",language:i,label:e}),pu=({id:i,language:e,label:t,codecs:r,isDefault:a})=>({id:i,language:e,label:t,codec:(0,Ci.default)(r.split("."),0),isDefault:a}),hu=({id:i,language:e,label:t,hdr:r,codecs:a})=>({id:i,language:e,hdr:r,label:t,codec:(0,Ci.default)(a.split("."),0)}),us=i=>"url"in i,Ot=i=>i.type==="template",Di=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var Bi=class{constructor(e,t,r,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:l=!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 AA;this.gaps=[];this.subscription=new wA;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Ke;this.destroyAbortController=new Ke;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=vr(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);qe(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Mm(this.sourceBuffer),this.subscription.add(fu(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,l=this.mediaSource.readyState;l!=="open"&&(o={id:`SegmentEjection_source_${l}`,category:Bt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:Bt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add(fu(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Bt.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,tu(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=l,this.tuning.useNewPruneBufferStrategy){let u=Ye(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);qe(r,"No init buffer for starting representation"),qe(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=vr(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);qe(r,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if(Ce(s)||Ce(a)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),qe(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();Sb(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=vr(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 d=this.representations.get(l);if(!d||!Ot(d.segmentReference))return;let c=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,c)}let r=this.switchingToRepresentationId??this.downloadingRepresentationId,a=this.representations.get(r);qe(a);let s=this.segments.get(r);qe(s,"No segments for starting representation");let n=this.initData.get(r);if(qe(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(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 Ke,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Ce(e)||Ce(this.downloadingRepresentationId)||Ce(this.playingRepresentationId)||Ce(this.sourceBuffer)||!Ce(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(qe(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=Ye(this.sourceBuffer.buffered,e),c=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=a.time.to-e+100&&(s=c)}if(isFinite(this.bufferLimit)&&tu(this.sourceBuffer.buffered)>=this.bufferLimit){let u=Ye(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,yr.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&&Ye(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,yr.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;Sb(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,yr.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;qe(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=Dt(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:c,time:{from:p,to:h}},m)=>{let b=p<=r&&h>=r,S=p>r||b||m===0&&r===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),w=this.preloadOnly&&p<=r+v||h<=r+v;return(c==="none"||c==="partially_ejected"&&S&&w&&this.sourceBuffer&&!pi(this.sourceBuffer.buffered,r))&&S&&w});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,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=a;c<s.length&&(n<=u||o<=d);c++){let p=s[c];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")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 vr(o,async function*(){let d=mu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:l,priority:r,isLowLatency:this.isActiveLowLatency()});if(!d)return;let c=new DataView(d);if(!isFinite(a.segment.time.to)){let p=t.segmentReference.timescale,h=Sr(t.mime);a.segment.time.to=h.getSegmentEndTime(c,p)}l&&a.feedingBytes&&u?await Promise.all(u):await this.sourceBufferTaskQueue.append(c,o),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Di(d)||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 vr(n,async function*(){let l=mu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(u,l),fu(window,"online").pipe(kA()).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),Di(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,yr.default)(e,0).byte.from,to:(0,yr.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:Bt.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,d)=>{if(!s.aborted)try{let c=this.onSomeTemplateDataLoaded({dataView:u,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:Bt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}: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),d=Sr(n.mime).parseFeedableSegmentChunk(u,this.isLive);d?.byteLength&&(l.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 l=o.segmentReference.type,u=e.byteLength;for(let d of this.activeSegments){let{segment:c}=d,p=l==="byteRange",h=p?c.byte.to-c.byte.from+1:u;if(d.representationId!==t||!(!p||c.byte.from>=r&&c.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let b=p?c.byte.from-r:0,S=p?c.byte.to-r:e.byteLength,v=b<a,w=S<=a;if(c.status==="downloading"&&v&&w){c.status="downloaded";let T=new DataView(e.buffer,e.byteOffset+b,h);this.sourceBufferTaskQueue.append(T,s).then(g=>g&&!s.aborted?this.onSegmentFullyAppended(d,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&v&&(d.loadedBytes=Math.min(h,a-b),d.loadedBytes>d.feedingBytes)){let T=new DataView(e.buffer,e.byteOffset+b+d.feedingBytes,d.loadedBytes-d.feedingBytes),g=d.loadedBytes===h?T:Sr(o.mime).parseFeedableSegmentChunk(T);g?.byteLength&&(c.status="partially_fed",d.feedingBytes+=g.byteLength,this.sourceBufferTaskQueue.append(g,s).then(y=>{if(s.aborted)n();else if(y)d.fedBytes+=g.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 l of this.activeSegments){let{segment:u}=l;if(l.representationId!==t)continue;if(s.aborted){n();continue}let d=u.byte.from-r,c=u.byte.to-r,p=c-d+1,h=d<a,m=c<=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(l,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(u.status==="downloading"||u.status==="partially_fed")&&(l.loadedBytes=Math.min(p,a-d),l.loadedBytes>l.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),S=l.loadedBytes===p?b:Sr(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",us(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=Xo(()=>(0,gb.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?vr(this.destroyAbortController.signal,async function*(){let o=mu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Sr(e.mime),a)).then(async o=>{if(!o)return;let{init:l,dataView:u,segments:d}=o,c=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,c);let p=d;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:Bt.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||Ce(e)||this.sourceBuffer.updating)return!1;let a=[],s=0,n=l=>{l.sort((d,c)=>d.from-c.from);let u=[l[0]];for(let d=1;d<l.length;d++){let{from:c,to:p}=l[d],h=u[u.length-1];h.to>=c?h.to=Math.max(h.to,p):u.push(l[d])}return u},o=l=>{if(s>=t)return a;a.push(l.time),a=n(a);let u=us(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 d=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||c)&&u.status==="fed"&&o(u)}for(let l=0;l<this.sourceBuffer.buffered.length;l++){let u=this.sourceBuffer.buffered.start(l)*1e3,d=this.sourceBuffer.buffered.end(l)*1e3,c=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)&&c++;if(c===this.segments.size){let p={time:{from:u,to:d},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 d of u)d.time.from>=e+l&&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||Ce(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 d=us(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"&&l(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"&&l(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,c=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(c)){s=d,n=c;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 c of d)c.time.from>e+u&&c.status==="fed"&&l(c)}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=Xo(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Bt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(Ce(this.sourceBuffer)||Ce(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(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);l||(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 Vi=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var vb=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 _i,assertNever as yb,fromEvent as Tb,merge as RA,now as Ni,Subscription as LA,ValueSubject as bu,flattenObject as Tr}from"@vkontakte/videoplayer-shared";var ls=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:a=!1}){this.lastConnectionType$=new bu(void 0);this.lastConnectionReused$=new bu(void 0);this.lastRequestFirstBytes$=new bu(void 0);this.abortAllController=new Ke;this.subscription=new LA;this.fetchManifest=_i(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Vi(r));let a=yield ze(r,{signal:this.abortAllController.signal}).catch(Fi);return a?(t.log("success",Tr({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(a.headers),a.text()):(t.error("error",Tr({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=_i(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,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let A=new URL(u,location.href);A.searchParams.append("bytes",`${r.from}-${r.to}`),u=A.toString();break}default:yb(t)}this.requestQuic&&(u=Vi(u));let p=this.abortAllController.signal,h;if(n){let A=new Ke;if(h=RA(Tb(this.abortAllController.signal,"abort"),Tb(n,"abort")).subscribe(()=>{try{A.abort()}catch(L){Fi(L)}}),this.abortAllController.signal.aborted||n.aborted)try{A.abort()}catch(L){Fi(L)}p=A.signal}let m=Ni();c.log("startRequest",Tr({url:u,priority:s,rangeMethod:t,range:r,isLowLatency:l,requestStartedAt:m}));let b=yield ze(u,{priority:s,headers:d,signal:p}).catch(Fi),S=Ni();if(!b)return c.error("error",{message:"No response in request"}),c.end(),h?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(S-m),!b.ok||!b.body){h?.unsubscribe();let A=`Fetch error ${b.status}: ${b.statusText}`;return c.error("error",{message:A}),c.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!a&&!o){h?.unsubscribe();let A=Ni(),L={requestStartedAt:m,requestEndedAt:A,duration:A-m};return c.log("endRequest",Tr(L)),c.end(),b.arrayBuffer()}let[v,w]=b.body.tee(),T=v.getReader();o&&this.throughputEstimator?.trackStream(w,l);let g=0,y=new Uint8Array(0),C=!1,x=A=>{h?.unsubscribe(),C=!0,Fi(A)},D=_i(p,async function*({done:A,value:L}){if(g===0&&this.lastRequestFirstBytes$.next(Ni()-m),p.aborted){h?.unsubscribe();return}if(!A&&L){let q=new Uint8Array(y.length+L.length);q.set(y),q.set(L,y.length),y=q,g+=L.byteLength,a?.(new DataView(y.buffer),g),yield T?.read().then(D,x)}}.bind(this));yield T?.read().then(D,x),h?.unsubscribe();let N=Ni(),P={failed:C,requestStartedAt:m,requestEndedAt:N,duration:N-m};return C?(c.error("endRequest",Tr(P)),c.end(),null):(c.log("endRequest",Tr(P)),c.end(),y.buffer)}.bind(this));this.fetchByteRangeRepresentation=_i(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,d;e.indexRange&&(u=e.indexRange.from,d=e.indexRange.to,l=s+1===u,l&&(n=Math.min(u,a),o=Math.max(d,s))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!c)return null;let p=new DataView(c,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(l)b=new DataView(c,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 S=t.parseSegments(b,h,m);return{init:h,dataView:new DataView(c),segments:S}}.bind(this));this.fetchTemplateRepresentation=_i(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}=vb(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:yb(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Fi=i=>{if(!Di(i))throw i};var Vt=(i,e,t)=>t*e+(1-t)*i,Su=(i,e)=>i.reduce((t,r)=>t+r,0)/e,Ib=(i,e,t,r)=>{let a=0,s=t,n=Su(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 $A,ValueSubject as Eb}from"@vkontakte/videoplayer-shared";var ct=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Eb(e.initial),this.debounced$=new Eb(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)&&($A(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 cs=class extends ct{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Vt(this.slow,e,this.params.emaAlphaSlow),this.fast=Vt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var ds=class extends ct{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Su(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Vt(this.emaSmoothed,e,this.params.emaAlpha);let r=Ib(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var ps=class extends ct{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?Vt(this.smoothed,t,this.params.emaAlpha):t}};var _t=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new cs({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new ds({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 ps({initial:e,label:"liveEdgeDelay",...t})}};var gu=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};var Rb=["timeupdate","progress","play","seeked","stalled","waiting"];var ms=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new wb;this.representationSubscription=new wb;this.state$=new $("none");this.currentVideoRepresentation$=new Z(void 0);this.currentVideoRepresentationInit$=new Z(void 0);this.currentAudioRepresentation$=new Z(void 0);this.currentVideoSegmentLength$=new Z(0);this.currentAudioSegmentLength$=new Z(0);this.error$=new Ab;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 Ab;this.gapWatchdogActive=!1;this.destroyController=new Ke;this.initManifest=vu(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:dt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=vu(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:dt.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t;try{t=hb(e??"",this.manifestUrlString)}catch(n){let o=Am(e)??{id:"ManifestParsing",category:dt.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(o)}if(!t)return null;let r=(n,o,l)=>!!(this.element?.canPlayType?.(o)&&Je()?.isTypeSupported?.(`${o}; codecs="${l}"`)||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 l=t.streams[n].filter(({mime:c,codecs:p})=>r(n,c,p)),u=new Set(l.map(({codecs:c})=>c)),d=km(u);if(d&&(a[n]=l.filter(({codecs:c})=>c.startsWith(d))),n==="video"){let c=this.tuning.preferHDR,p=a.video.some(m=>m.hdr),h=a.video.some(m=>!m.hdr);BA.isHDR&&c&&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",qi(s)),s}.bind(this));this.initRepresentations=vu(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initRepresentationsStart",qi({initialVideo:e,initialAudio:t,sourceHls:r})),Nt(this.manifest),Nt(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=c=>{this.representationSubscription.add(Ir(c,"error").pipe(fs(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:dt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=this.tuning.useManagedMediaSource?gm():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&rs())if(r){let c=document.createElement("source");a(c),c.type="application/x-mpegurl",c.src=r.url,this.element.appendChild(c)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.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((c,p)=>[...c,...p.representations],[]);if(this.videoBufferManager=new Bi("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],kb(t)){let c=this.manifest.streams.audio.reduce((p,h)=>[...p,...h.representations],[]);this.audioBufferManager=new Bi("audio",this.source,c,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(yu(1e3).subscribe(c=>{if(this.element?.paused){let p=$o(this.manifestUrlString,2);this.manifestUrlString=K(this.manifestUrlString,p+1e3,2)}})),this.representationSubscription.add(Er(...Rb.filter(c=>c!=="waiting").map(c=>Ir(this.element,c))).pipe(Tu(c=>this.element?Ye(this.element.buffered,this.element.currentTime*1e3):0),Pb(),fs(c=>!!c),DA(c=>{this.stallWatchdogSubscription?.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Pb()).subscribe(p=>gu(this.element,1))),this.representationSubscription.add(hs({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(fs(({bufferLength:p,isActiveLowLatency:h})=>h&&!!p)).subscribe(({bufferLength:p})=>this.liveEstimatedDelay.next(p))),this.representationSubscription.add(hs({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,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,v=p-m,w=1;Math.abs(v)>b&&(w=1+Math.sign(v)*S),gu(this.element,w)})),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(S=>S.getLiveSegmentsToLoadState(this.manifest)?.to??m))-m}this.liveLoadBufferLength$.getValue()!==h&&this.liveLoadBufferLength$.next(h)}));let c=0;this.representationSubscription.add(hs({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(OA(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:h})=>{if(Nt(this.element),this.isUpdatingLive)return;let m=this.element.playbackRate,b=$o(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*m),w=this.tuning.dashCmafLive.normalizedActualBufferOffset*m,T=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*m,g=isFinite(p)?p:h,y=this.isActiveLowLatency$.getValue(),C=S<=this.tuning.live.activeLiveDelay&&b===0;this.isActiveLowLatency$.next(y&&C);let x="none";if(y?x="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&C?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(D=>D.proceedLowLatencyLive()),x="active_low_latency"):b!==0&&g<v?x="live_forward_buffering":g<v+T&&(x="live_with_target_offset"),isFinite(p)&&(c=p>c?p:c),x==="live_forward_buffering"||x==="live_with_target_offset"){let D=c-(v+w),N=this.normolizeLiveOffset(Math.trunc(b+D/m)),P=Math.abs(N-b),A;!p||P<=this.tuning.dashCmafLive.offsetCalculationError?A=b:N>0&&P>this.tuning.dashCmafLive.offsetCalculationError?A=N:A=0,this.manifestUrlString=K(this.manifestUrlString,A,2)}x!=="none"&&x!=="active_low_latency"&&(c=0,this.updateLive())}))}let l=Er(...this.bufferManagers.map(c=>c.fullyBuffered$)).pipe(Tu(()=>this.bufferManagers.every(c=>c.fullyBuffered$.getValue()))),u=Er(...this.bufferManagers.map(c=>c.onLastSegment$)).pipe(Tu(()=>this.bufferManagers.some(c=>c.onLastSegment$.getValue())));this.representationSubscription.add(Er(this.forceEnded$,hs({allBuffersFull:l,someBufferEnded:u}).pipe(fs(({allBuffersFull:c,someBufferEnded:p})=>c&&p))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(c=>!c.updating))try{this.source?.endOfStream()}catch(c){this.error$.next({id:"EndOfStream",category:dt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:c})}})),this.representationSubscription.add(Er(...this.bufferManagers.map(c=>c.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(c=>this.source?.addEventListener("sourceopen",c)));let d=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(c=>c.representations).flatMap(c=>c.duration??0)];this.source.duration=Math.max(...d)/1e3,this.audioBufferManager&&kb(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=yu(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:dt.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 ls({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=_t.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator}),this.initTracerSubscription()}async seekLive(e){Nt(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(){Nt(this.element),this.state$.setState("running"),this.subscription.add(Er(...Rb.map(e=>Ir(this.element,e)),Ir(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:dt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Ir(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Ir(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&pi(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",qi(t))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=yu(1e3).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:dt.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){Nt(this.element),Nt(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),pi(this.element.buffered,r)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(r),this.audioBufferManager?.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",qi({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=VA(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",qi(t)))}}};var bs=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ss=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 Lb=`attribute vec2 a_vertex;
|
|
36
|
+
[best video track] ${O?.quality}
|
|
37
|
+
[selected video track] ${N?.quality}
|
|
38
|
+
`}),ym(r,p,N,u)},Tm=(i,e,t,{throughput:r,tuning:a,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:c})=>{gm(t,vm);let u=a.considerPlaybackRate&&de(s)?s:1,d=[...t].sort(Jo(-1)),l=i.bitrate;YP(l);let p=u*Sm(n??.5,a.bitrateAudioFactorAtEmptyBuffer,a.bitrateAudioFactorAtFullBuffer),h;return de(r)&&isFinite(r)&&(h=d.find(m=>de(m.bitrate)?r-l>=m.bitrate*p:!0)),h||(h=os(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&&ym(a,c,h,o)};var Q=i=>new URL(i).hostname;import{assertNever as km,assertNonNullable as wm,combine as fA,debounce as mA,ErrorCategory as Rm,filter as $m,filterChanged as bA,isNonNullable as ru,map as ps,merge as Lm,observableFrom as gA,once as SA,Subscription as vA,ValueSubject as iu,videoQualityToHeight as yA,videoSizeToQuality as TA}from"@vkontakte/videoplayer-shared";var Im=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"))},pe=async i=>{let e=i.muted;try{await i.play()}catch(t){if(!Im(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{await i.play()}catch(r){return Im(r)&&(i.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as cs,isNullable as JP,assertNonNullable as bi}from"@vkontakte/videoplayer-shared";import{isNonNullable as Em,assertNonNullable as us,now as zP}from"@vkontakte/videoplayer-shared";function z(){return zP()}function Xo(i){return z()-i}function Zo(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 xm(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function Tr(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;us(d);let $=Xo(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=$,R),k=$=>(l=$,R),y=()=>(h="json",R),S=()=>{if(!c){if(--u>=0){g(),r&&r();return}c=!0,l&&l(),t&&t()}},T=$=>(p=$,R),E=()=>{d=z(),n=new a,n.open("get",i);let $=0,q,Le=0,ae=()=>(us(d),Math.max(d,Math.max(q||0,Le||0)));if(s&&n.addEventListener("progress",x=>{let A=z();s.updateChunk&&x.loaded>$&&(s.updateChunk(ae(),x.loaded-$),$=x.loaded,q=A)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>S())),n.addEventListener("load",()=>{if(c)return;us(n);let x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&s){let A=n.response.byteLength-$;A&&s.updateChunk&&s.updateChunk(ae(),A)}n.responseType==="json"&&!Object.values(n.response).length?S():(l&&l(),e(n.response))}else S()}),n.addEventListener("error",()=>{S()}),p){let x=()=>{us(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Le=z(),n.removeEventListener("readystatechange",x))};n.addEventListener("readystatechange",x)}return n.responseType=h,n.send(),R},R={withBitrateReporting:v,withParallel:T,withJSONResponse:y,withRetryCount:$=>(u=$,R),withRetryInterval:($,q)=>(Em($)&&(b=$),Em(q)&&(m=q),R),withTimeout:$=>(o=$,R),withFinally:k,send:E,abort:()=>{n&&(n.abort(),n=void 0),c=!0,l&&l()}};return R}var fi=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 mi=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=z(),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=z()-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=Tr(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=z()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=z();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,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 ls=1e4,eu=3;var XP=6e4,ZP=10,eA=1,tA=500,gi=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 fi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Zo(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=Zo(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||cs(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=()=>{xm(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 mi(eu,ls,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:a}=this.params,s=!1,n=null,o=null,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=Tr(this.urlResolver.resolve(S,!1),T,E,()=>this._retryCallback()).withTimeout(ls).withBitrateReporting(this.bitrateSwitcher).withRetryCount(eu).withFinally(()=>{c=null}).send()},h=(S,T,E)=>{bi(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=z()-1e4,D=0;for(let N=0;N<this.bufferStates.length;N++){let w=this.bufferStates[N];S=Math.min(S,w.buf),w.ts<E&&D++}this.bufferStates.splice(0,D),t(`update playback rate; minBuffer=${S} drop=${D} jitter=${this.sourceJitter}`);let O=S-eA;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,w=(x,A)=>({chunkIdx:N(x),startTS:D(x),dur:O(x),discontinuity:A}),R=()=>{let x=0;if(T&&T.dur){let A=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,G=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,K=A;this.sourceJitter>1&&(K+=this.sourceJitter-1);let me=T.dur.length-1;for(;me>=0&&(K-=T.dur[me],!(K<=0));--me);x=Math.min(me,T.dur.length-1-G),x=Math.max(x,0)}return w(x,!0)},$=x=>{let A=E();if(!(A<=0)){if(cs(x)){for(let G=0;G<A;G++)if(D(G)>x)return w(G)}return R()}},q=x=>{let A=E(),G=x?x.chunkIdx+1:0,K=G-T.fragIndex;if(!(A<=0)){if(!x||K<0||K-A>ZP)return t(`Resync: offset=${K} bChunks=${A} chunk=`+JSON.stringify(x)),R();if(!(K>=A))return w(G-T.fragIndex,!1)}},Le=(x,A,G)=>{u&&u.abort(),u=Tr(this.urlResolver.resolve(x,!0,this.lowLatency),A,G,()=>this._retryCallback()).withTimeout(ls).withRetryCount(eu).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(x,A)=>{Le(S,G=>{if(!l())return;T=G;let K=!!T.lowLatency;K!==this.lowLatency&&b(K);let me=0;for(let Me=0;Me<T.dur.length;++Me)me+=T.dur[Me];me>0&&(bi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(me/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($(A))},()=>this._handleNetworkError())},nextChunk:q}},k=()=>{s=!1,o&&o.abort(),c&&c.abort(),u&&u.abort(),bi(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:S=>{let{videoElement:T,logger:E}=this.params,D=v(e.jidxUrl),O,N,w,R,$=0,q,Le,ae,x=()=>{q&&(clearTimeout(q),q=void 0);let B=Math.max(tA,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),W=$+B,Z=z(),Y=Math.min(1e4,W-Z);$=Z;let Te=()=>{u||l()&&D.seek(()=>{l()&&($=z(),A(),x())})};Y>0?q=window.setTimeout(()=>{this.paused?x():Te()},Y):Te()},A=()=>{let B;for(;B=D.nextChunk(R);)R=B,Jt(B);let W=D.nextChunk(w);if(W){if(w&&W.discontinuity){E("Detected discontinuity; restarting playback"),this.paused?x():(k(),this._initPlayerWith(e));return}Me(W)}else x()},G=(B,W)=>{if(!l()||!this.sourceBuffer)return;let Z,Y,Te,dt=He=>{window.setTimeout(()=>{l()&&G(B,W)},He)};if(this.sourceBuffer.updating)E("Source buffer is updating; delaying appendBuffer"),dt(100);else{let He=z(),Ce=T.currentTime;!this.paused&&T.buffered.length>1&&Le===Ce&&He-ae>500&&(E("Stall suspected; trying to fix"),this._fixupStall()),Le!==Ce&&(Le=Ce,ae=He);let wt=this._getBufferSizeSec();if(wt>30)E(`Buffered ${wt} seconds; delaying appendBuffer`),dt(2e3);else try{this.sourceBuffer.appendBuffer(B),this.videoPlayStarted?(this.bufferStates.push({ts:He,buf:wt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),W&&W()}catch(Je){if(Je.name==="QuotaExceededError")E("QuotaExceededError; delaying appendBuffer"),Te=this.sourceBuffer.buffered.length,Te!==0&&(Z=this.sourceBuffer.buffered.start(0),Y=Ce,Y-Z>4&&this.sourceBuffer.remove(Z,Y-3)),dt(1e3);else throw Je}}},K=()=>{N&&O&&(E([`Appending chunk, sz=${N.byteLength}:`,JSON.stringify(w)]),G(N,function(){N=null,A()}))},me=B=>e.fragUrlTemplate.replace("%%id%%",B.chunkIdx),Me=B=>{l()&&h(me(B),(W,Z)=>{if(l()){if(Z/=1e3,N=W,w=B,n=B.startTS,Z){let Y=Math.min(10,B.dur/Z);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Y:Y}K()}},()=>this._handleNetworkError())},Jt=B=>{l()&&(bi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(me(B),!1)))},kt=B=>{l()&&(e.cachedHeader=B,G(B,()=>{O=!0,K()}))};s=!0,D.seek(B=>{if(l()){if($=z(),!B){x();return}R=B,!JP(S)||B.startTS>S?Me(B):(w=B,A())}},S),e.cachedHeader?kt(e.cachedHeader):p(e.headerUrl,kt,()=>this._handleNetworkError())},stop:k,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),cs(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,bi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return cs(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=z();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&&Xo(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=z();l<o&&(n=p),o=l}}}_fetchManifest(e,t,r){this.manifestRequest=Tr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(ls).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;pe(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))},XP))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as rA,filter as Pm,fromEvent as iA,interval as aA,isHigher as sA,isInvariantQuality as nA,isLower as oA,merge as uA,Subject as Am,Subscription as cA}from"@vkontakte/videoplayer-shared";var tu=class{constructor(){this.onDroopedVideoFramesLimit$=new Am;this.subscription=new cA;this.playing=!1;this.tracks=[];this.forceChecker$=new Am;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&&!nA(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&&sA(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(iA(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=aA(this.droppedFramesChecker.checkTime).pipe(Pm(()=>this.playing),Pm(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(rA(this.droppedFramesChecker.checkTime)),r=uA(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])=>oA(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}},ds=tu;import{map as lA,Observable as dA}from"@vkontakte/videoplayer-shared";import{fromEvent as pA}from"@vkontakte/videoplayer-shared";var Si=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var hA=(i,e)=>new dA(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(c=>t.next(c.isIntersecting||Si()))},{...r,...e});a.observe(i);let s=pA(document,"visibilitychange").pipe(lA(n=>!document.hidden||Si())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),Re=hA;var IA=["paused","playing","ready"],EA=["paused","playing","ready"],vi=class{constructor(e){this.subscription=new vA;this.videoState=new L("stopped");this.representations$=new iu([]);this.textTracksManager=new ke;this.droppedFramesManager=new ds;this.maxSeekBackTime$=new iu(1/0);this.zeroTime$=new iu(void 0);this.liveOffset=new it;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:Rm.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=vt(a.name)??TA(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),ru(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(EA.includes(e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&IA.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(J(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(J(this.params.source.url,c))}return;default:return km(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:Rm.WTF,message:"DashLiveProvider internal logic error",thrown:a})};Lm(this.videoState.stateChangeStarted$.pipe(ps(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ps(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=oe(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(Q(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=le(this.video);this.subscription.add(this.representations$.pipe(ps(a=>a.map(({track:s})=>s)),$m(a=>!!a.length),SA()).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(bA(),ps(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(fA({zeroTime:this.zeroTime$.pipe($m(ru)),position:r.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(Qe(this.video,this.params.desiredState.isLooped,t)).add(ce(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Ae(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(Re(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&yA(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 km(a.to)}},t)).add(Lm(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,gA(["init"])).pipe(mA(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),ue(this.video)}createLiveDashPlayer(){let e=new gi({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&&ru(t)?t:yt(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;wm(u,"Representations missing"),this.dash.startPlay(u,r)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:r})=>r.id===e.id)?.representation;wm(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(J(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var Mm=vi;var st=(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 zk,assertNonNullable as Kk,debounce as Jk,ErrorCategory as Mu,filter as Wb,filterChanged as Cu,fromEvent as Xk,isNonNullable as Zk,map as Yb,merge as Cs,observableFrom as ew,observeElementSize as tw,once as Qb,Subscription as rw,ValueSubject as iw}from"@vkontakte/videoplayer-shared";var hs=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}},Ir=class extends hs{constructor(){super(),this.listeners||hs.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)}},yi=class{constructor(){Object.defineProperty(this,"signal",{value:new Ir,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&&(yi.prototype[Symbol.toStringTag]="AbortController",Ir.prototype[Symbol.toStringTag]="AbortSignal");function fs(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 au(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!fs({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 Ti=fs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Cm=Ti?au({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,nt=Ti?Cm.fetch:window.fetch,s0=Ti?Cm.Request:window.Request,ot=Ti?yi:window.AbortController,n0=Ti?Ir:window.AbortSignal;var Vm=We(di(),1);var ut=()=>window.ManagedMediaSource||window.MediaSource,ms=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Dm=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),Bm=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as vs,clientChecker as gs}from"@vkontakte/videoplayer-shared";var Ss=document.createElement("video"),AA='video/mp4; codecs="avc1.42000a,mp4a.40.2"',kA='video/mp4; codecs="hev1.1.6.L93.B0"',Om='video/webm; codecs="vp09.00.10.08"',_m='video/webm; codecs="av01.0.00M.08"',wA='audio/mp4; codecs="mp4a.40.2"',RA='audio/webm; codecs="opus"',qt={mms:ms(),mse:Dm(),hls:!!(Ss.canPlayType?.("application/x-mpegurl")||Ss.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},he={mp4:!!Ss.canPlayType?.("video/mp4"),webm:!!Ss.canPlayType?.("video/webm"),cmaf:!0},fe={h264:!!ut()?.isTypeSupported?.(AA),h265:!!ut()?.isTypeSupported?.(kA),vp9:!!ut()?.isTypeSupported?.(Om),av1:!!ut()?.isTypeSupported?.(_m),aac:!!ut()?.isTypeSupported?.(wA),opus:!!ut()?.isTypeSupported?.(RA)},Er=(fe.h264||fe.h265)&&fe.aac,Ut,$A=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:_m}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:Om}})]);Ut={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{$A()}catch(i){console.error(i)}var xr=qt.hls&&he.mp4,Nm=()=>Object.keys(fe).filter(i=>fe[i]),Fm=(i,e=!1,t=!1)=>{let r=qt.mse||qt.mms&&t;return i.filter(a=>{switch(a){case"DASH_SEP":return r&&he.mp4&&Er;case"DASH_WEBM":return r&&he.webm&&fe.vp9&&fe.opus;case"DASH_WEBM_AV1":return r&&he.webm&&fe.av1&&fe.opus;case"DASH_STREAMS":return r&&(he.mp4&&Er||he.webm&&(fe.vp9||fe.av1)&&(fe.opus||fe.aac));case"DASH_LIVE":return qt.mse&&he.mp4&&Er;case"DASH_LIVE_CMAF":return r&&he.mp4&&Er&&he.cmaf;case"DASH_ONDEMAND":return r&&he.mp4&&Er;case"HLS":case"HLS_ONDEMAND":return xr||e&&qt.mse&&he.mp4&&Er;case"HLS_LIVE":case"HLS_LIVE_CMAF":return xr;case"MPEG":return he.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return qt.webrtc&&qt.ws&&fe.h264&&(he.mp4||he.webm);default:return vs(a)}})},bs=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 Ut?Ut[t].smooth?[t,e]:Ut[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Ut?Ut[t].powerEfficient?[t,e]:Ut[e].powerEfficient?[e,t]:[t,e]:[e,t];default:vs(i)}return[e,t]},qm=({webmCodec:i,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...bs(i),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],a=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(gs.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",...bs(i),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...bs(i),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...bs(i),...a,"HLS","HLS_ONDEMAND"];default:vs(e)}return xr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Um=({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=gs.isMac&&gs.isSafari;if(gs.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:vs(i)}else xr&&!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"]},su=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Hm=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,Vm.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return i.values().next().value.split(".").at(0)}};import{ErrorCategory as Ii}from"@vkontakte/videoplayer-shared";var jm=i=>{if(!i)return{id:"EmptyResponse",category:Ii.PARSER,message:"Empty response"};if(i.length<=2&&i.match(/^\d+$/))return{id:`UVError#${i}`,category:Ii.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:Ii.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:Ii.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Ii.PARSER,message:"Response is valid XML, but parser failed"}};var Ei=(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 Ru,assertNonNullable as zt,combine as ks,ErrorCategory as It,filter as ws,filterChanged as Nb,fromEvent as Mr,interval as $u,isNonNullable as Fb,map as Lu,merge as Cr,Subject as qb,Subscription as Ub,tap as qk,throttle as Uk,clientChecker as Hk,ValueSubject as X,flattenObject as Zi,getTraceSubscriptionMethod as jk}from"@vkontakte/videoplayer-shared";var $r=We(di(),1);var LA=(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)},MA=i=>window.clearTimeout(i),Gm=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",nu=Gm?LA:window.requestIdleCallback,y0=Gm?MA:window.cancelIdleCallback;var Mb=We(as(),1);import{assertNever as CA,ErrorCategory as Wm,clientChecker as ou,Subject as Ym}from"@vkontakte/videoplayer-shared";var DA=16,Qm=!1;try{Qm=ou.isSafari&&!!ou.macVersion&&ou.macVersion<=DA}catch(i){console.error(i)}var uu=class{constructor(e){this.bufferFull$=new Ym;this.error$=new Ym;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:Wm.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:Wm.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:CA(t)}}},zm=uu;var cu=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 Rr,assertNonNullable as Ke,ErrorCategory as Wt,fromEvent as Eu,getExponentialDelay as xu,isNonNullable as Pu,isNullable as $e,once as Lk,Subject as Mk,Subscription as Ck,ValueSubject as Wi}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 Pr=class extends _{};var xi=class extends _{};var Pi=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 Ai=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ki=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var wi=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 Ht=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 Ri=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var $i=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Li=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 Mi=class extends j{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Ci=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 Di=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Bi=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 Vi=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Oi=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var _i=class extends j{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Ni=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Fi=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 qi=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 Ui=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 VA={ftyp:Pi,moov:Ai,moof:ki,mdat:wi,sidx:Ht,trak:Ri,mdia:Di,mfhd:_i,tkhd:Bi,traf:Ni,tfhd:Fi,tfdt:qi,trun:Ui,minf:Vi,sv3d:$i,st3d:Li,prhd:Mi,proj:Oi,equi:Ci,uuid:xi,unknown:Pr},jt=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=VA[e];return r?new r(t,new i):new Pr(t,new i)}};var Ar=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 _A=new TextDecoder("ascii"),NA=i=>_A.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",FA=i=>{let e=new Ht(i,new jt),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})},qA=(i,e)=>{let r=new jt().parse(i),a=new Ar(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)},UA=(i,e)=>{let r=new jt().parse(i),s=new Ar(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},HA=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 jt().parse(i),a=new Ar(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},Km={validateData:NA,parseInit:HA,getIndexRange:()=>{},parseSegments:FA,parseFeedableSegmentChunk:qA,getSegmentEndTime:UA};import{assertNonNullable as du,isNonNullable as eb,isNullable as GA}from"@vkontakte/videoplayer-shared";import{assertNever as jA}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"}},Xm=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=Hi(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=Hi(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}},Hi=(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},Fe=(i,e)=>{switch(e){case"int":return i.getInt8(0);case"uint":return Hi(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:jA(e)}},Gt=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=Xm(r);if(!e(a))return;a.type==="master"&&Gt(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},Zm=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=Xm(i);return Gt(a.value,({tag:s,type:n,value:o})=>(s===17143?e=Fe(o,n):s===17026?t=Fe(o,n):s===17029&&(r=Fe(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var tb=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],WA=[231,22612,22743,167,171,163,160,175],YA=i=>{let e,t,r,a,s=!1,n=!1,o=!1,c,u,d=!1,l=0;return Gt(i,({tag:p,type:h,value:m,valueSize:b})=>{if(p===21419){let g=Fe(m,h);u=Hi(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=Fe(m,h):p===17545?a=Fe(m,h):p===21420&&u===475249515?c=Fe(m,h):p===374648427?Gt(m,({tag:g,type:v,value:k})=>g===30321?(d=Fe(k,v)===1,!1):!0):s&&n&&tb.includes(p)&&(o=!0),!o}),du(e,"Failed to parse webm Segment start"),du(t,"Failed to parse webm Segment end"),du(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}}}},QA=i=>{if(GA(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},zA=(i,e)=>{let t=!1,r=!1,a=o=>eb(o.time)&&eb(o.position),s=[],n;return Gt(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=Fe(u,c));break;case 183:break;case 241:n&&(n.position=Fe(u,c));break;default:t&&tb.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}}})},KA=i=>{let e=0,t=!1;try{Gt(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):WA.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},rb={validateData:Zm,parseInit:YA,getIndexRange:QA,parseSegments:zA,parseFeedableSegmentChunk:KA};var kr=i=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(i);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return rb;case"mp4":return Km}}throw new ReferenceError(`Unsupported mime type ${i}`)};var Su=We(xb(),1);var gu=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 Ab,isNullable as kb}from"@vkontakte/videoplayer-shared";var Pb=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var wb=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},ct=(i,e)=>{let t=i;t=(0,Su.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,Su.default)(t,n,(o,c)=>kb(s)?o:kb(c)?s:s.padStart(parseInt(c,10),"0"))}return t},Rb=(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=wb(h);else if(m){let S=wb(m);Ab(S)&&(p=S)}else g&&(p=parseInt(g,10));let v=0,k=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(",")??[],w=S.getAttribute("lang")??void 0,R=S.querySelector("Label")?.textContent?.trim()??void 0,$=S.querySelectorAll("Representation"),q=S.querySelector("SegmentTemplate"),Le=S.querySelector("Role")?.getAttribute("value")??void 0,ae=O,x={id:T,language:w,isDefault:Le==="main",label:R,codecs:D,hdr:ae==="video"&&gu(D),mime:E,representations:[]};for(let A of $){let G=A.getAttribute("lang")??void 0,K=A.getAttribute("label")??void 0,me=A.querySelector("BaseURL")?.textContent?.trim()??"",Me=new URL(me||o,e).toString(),Jt=A.getAttribute("mimeType")??E,kt=A.getAttribute("codecs")??D??"",B;if(O==="text"){let W=A.getAttribute("id")||"",Z=W.includes("_auto"),Y=A.querySelector("SegmentTemplate");if(Y){let Te={representationId:A.getAttribute("id")??void 0,bandwidth:A.getAttribute("bandwidth")??void 0},dt=parseInt(A.getAttribute("bandwidth")??"",10)/1e3,He=parseInt(Y.getAttribute("startNumber")??"",10)??1,Ce=parseInt(Y.getAttribute("timescale")??"",10),wt=Y.querySelectorAll("SegmentTimeline S")??[],Je=Y.getAttribute("media");if(!Je)throw new ReferenceError("No media attribute in SegmentTemplate");let ma=[],ba=0,ga="",Xt=0,Br=He,ee=0;for(let De of wt){let Rt=parseInt(De.getAttribute("d")??"",10),Ie=parseInt(De.getAttribute("r")??"",10)||0,pt=parseInt(De.getAttribute("t")??"",10);ee=Number.isFinite(pt)?pt:ee;let $t=Rt/Ce*1e3,Zt=ee/Ce*1e3;for(let je=0;je<Ie+1;je++){let ht=ct(Je,{...Te,segmentNumber:Br.toString(10),segmentTime:(ee+je*Rt).toString(10)}),er=(Zt??0)+je*$t,Or=er+$t;Br++,ma.push({time:{from:er,to:Or},url:ht})}ee+=(Ie+1)*Rt,ba+=(Ie+1)*$t}Xt=ee/Ce*1e3,ga=ct(Je,{...Te,segmentNumber:Br.toString(10),segmentTime:ee.toString(10)});let Vr={time:{from:Xt,to:1/0},url:ga},Xe={type:"template",baseUrl:Me,segmentTemplateUrl:Je,initUrl:"",totalSegmentsDurationMs:ba,segments:ma,nextSegmentBeyondManifest:Vr,timescale:Ce};B={id:W,kind:"text",segmentReference:Xe,profiles:[],duration:p,bitrate:dt,mime:"",codecs:"",width:0,height:0,isAuto:Z}}else B={id:A.getAttribute("id")||"",isAuto:Z,kind:"text",url:Me}}else{let W=A.getAttribute("contentType")??Jt?.split("/")[0]??O,Z=S.getAttribute("profiles")?.split(",")??[],Y=parseInt(A.getAttribute("width")??"",10),Te=parseInt(A.getAttribute("height")??"",10),dt=parseInt(A.getAttribute("bandwidth")??"",10)/1e3,He=A.getAttribute("frameRate")??"",Ce=A.getAttribute("quality")??void 0,wt=He?Pb(He):void 0,Je=A.getAttribute("id")??"id"+(v++).toString(10),ma=W==="video"?`${Te}p`:W==="audio"?`${dt}Kbps`:kt,ba=`${Je}@${ma}`,ga=[...k,...N,...Z],Xt,Br=A.querySelector("SegmentBase"),ee=A.querySelector("SegmentTemplate")??q;if(Br){let Xe=A.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[De,Rt]=Xe.split("-").map(ht=>parseInt(ht,10)),Ie={from:De,to:Rt},pt=A.querySelector("SegmentBase")?.getAttribute("indexRange"),[$t,Zt]=pt?pt.split("-").map(ht=>parseInt(ht,10)):[],je=pt?{from:$t,to:Zt}:void 0;Xt={type:"byteRange",url:Me,initRange:Ie,indexRange:je}}else if(ee){let Xe={representationId:A.getAttribute("id")??void 0,bandwidth:A.getAttribute("bandwidth")??void 0},De=parseInt(ee.getAttribute("timescale")??"",10),Rt=ee.getAttribute("initialization")??"",Ie=ee.getAttribute("media"),pt=parseInt(ee.getAttribute("startNumber")??"",10)??1,$t=ct(Rt,Xe);if(!Ie)throw new ReferenceError("No media attribute in SegmentTemplate");let Zt=ee.querySelectorAll("SegmentTimeline S")??[],je=[],ht=0,er="",Or=0;if(Zt.length){let Sa=pt,Be=0;for(let tr of Zt){let Ge=parseInt(tr.getAttribute("d")??"",10),Lt=parseInt(tr.getAttribute("r")??"",10)||0,va=parseInt(tr.getAttribute("t")??"",10);Be=Number.isFinite(va)?va:Be;let Qs=Ge/De*1e3,Fg=Be/De*1e3;for(let ya=0;ya<Lt+1;ya++){let qg=ct(Ie,{...Xe,segmentNumber:Sa.toString(10),segmentTime:(Be+ya*Ge).toString(10)}),zu=(Fg??0)+ya*Qs,Ug=zu+Qs;Sa++,je.push({time:{from:zu,to:Ug},url:qg})}Be+=(Lt+1)*Ge,ht+=(Lt+1)*Qs}Or=Be/De*1e3,er=ct(Ie,{...Xe,segmentNumber:Sa.toString(10),segmentTime:Be.toString(10)})}else if(Ab(p)){let Be=parseInt(ee.getAttribute("duration")??"",10)/De*1e3,tr=Math.ceil(p/Be),Ge=0;for(let Lt=1;Lt<tr;Lt++){let va=ct(Ie,{...Xe,segmentNumber:Lt.toString(10),segmentTime:Ge.toString(10)});je.push({time:{from:Ge,to:Ge+Be},url:va}),Ge+=Be}Or=Ge,er=ct(Ie,{...Xe,segmentNumber:tr.toString(10),segmentTime:Ge.toString(10)})}let Ng={time:{from:Or,to:1/0},url:er};Xt={type:"template",baseUrl:Me,segmentTemplateUrl:Ie,initUrl:$t,totalSegmentsDurationMs:ht,segments:je,nextSegmentBeyondManifest:Ng,timescale:De}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!W||!Jt)continue;let Vr={video:"video",audio:"audio",text:"text"}[W];if(!Vr)continue;ae||=Vr,B={id:ba,kind:Vr,segmentReference:Xt,profiles:ga,duration:p,bitrate:dt,mime:Jt,codecs:kt,width:Y,height:Te,fps:wt,quality:Ce}}x.language||=G,x.label||=K,x.mime||=Jt,x.codecs||=kt,x.hdr||=ae==="video"&&gu(kt),x.representations.push(B)}ae&&a[ae].push(x)}return{dynamic:u,liveAvailabilityStartTime:l,duration:p,streams:a}};var ji=We(di(),1);import{videoSizeToQuality as $k}from"@vkontakte/videoplayer-shared";var $b=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s})=>{let n=(s?vt(s):void 0)??$k({width:e,height:t});return n&&{id:i,quality:n,bitrate:r,size:{width:e,height:t},fps:a}},Lb=({id:i,bitrate:e})=>({id:i,bitrate:e}),ys=(i,e,t)=>{let r=e.indexOf(i);return(0,ji.default)(t,Math.round(t.length*r/e.length))??(0,ji.default)(t,-1)},Ts=({language:i,label:e},{id:t,url:r,isAuto:a})=>({id:t,url:r,isAuto:a,type:"internal",language:i,label:e}),Tu=({id:i,language:e,label:t,codecs:r,isDefault:a})=>({id:i,language:e,label:t,codec:(0,ji.default)(r.split("."),0),isDefault:a}),Iu=({id:i,language:e,label:t,hdr:r,codecs:a})=>({id:i,language:e,hdr:r,label:t,codec:(0,ji.default)(a.split("."),0)}),Is=i=>"url"in i,qe=i=>i.type==="template",Gi=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var Yi=class{constructor(e,t,r,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:c=!1,manifest:u}){this.currentSegmentLength$=new Wi(0);this.onLastSegment$=new Wi(!1);this.fullyBuffered$=new Wi(!1);this.playingRepresentation$=new Wi(void 0);this.playingRepresentationInit$=new Wi(void 0);this.error$=new Mk;this.gaps=[];this.subscription=new Ck;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ot;this.destroyAbortController=new ot;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=Rr(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Ke(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new zm(this.sourceBuffer),this.subscription.add(Eu(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,c=this.mediaSource.readyState;c!=="open"&&(o={id:`SegmentEjection_source_${c}`,category:Wt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:Wt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add(Eu(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Wt.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,cu(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=c,this.tuning.useNewPruneBufferStrategy){let u=st(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);Ke(r,"No init buffer for starting representation"),Ke(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=Rr(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);Ke(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),Ke(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();Pu(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=Rr(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||!qe(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);Ke(a);let s=this.segments.get(r);Ke(s,"No segments for starting representation");let n=this.initData.get(r);if(Ke(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 ot,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(Ke(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=st(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)&&cu(this.sourceBuffer.buffered)>=this.bufferLimit){let u=st(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,$r.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&&st(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let c=(0,$r.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;Pu(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||!qe(r.segmentReference))return;let a=r.segmentReference.segments.map(c=>({...c,status:"none",size:void 0})),s=this.segments.get(r.id)??[],n=(0,$r.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;Ke(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(!qe(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=ct(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),k=this.preloadOnly&&p<=r+v||h<=r+v;return(l==="none"||l==="partially_ejected"&&g&&k&&this.sourceBuffer&&!Ei(this.sourceBuffer.buffered,r))&&g&&k});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 Rr(o,async function*(){let d=xu(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=kr(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]),Gi(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 Rr(n,async function*(){let c=xu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(u,c),Eu(window,"online").pipe(Lk()).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),Gi(c)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(qe(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,$r.default)(e,0).byte.from,to:(0,$r.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:Wt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}}}}prepareTemplateFetchSegmentParams(e,t){if(!qe(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:Wt.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=kr(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,k=g<=a;if(l.status==="downloading"&&v&&k){l.status="downloaded";let y=new DataView(e.buffer,e.byteOffset+b,h),S=this.getCurrentPosition();Pu(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||$e(S))&&(T({segmentView:y,segmentProgress:d}),this.resetAccumulateBufferAfterStall())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&v&&!k&&(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:kr(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:kr(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",Is(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=nu(()=>(0,Mb.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?Rr(this.destroyAbortController.signal,async function*(){let o=xu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,kr(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&&qe(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:Wt.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=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=Is(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||$e(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=Is(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=nu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Wt.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),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 Qi=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var Cb=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 zi,assertNever as Db,fromEvent as Bb,merge as Dk,now as Ki,Subscription as Bk,ValueSubject as Au,flattenObject as Lr}from"@vkontakte/videoplayer-shared";var Es=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:a=!1}){this.lastConnectionType$=new Au(void 0);this.lastConnectionReused$=new Au(void 0);this.lastRequestFirstBytes$=new Au(void 0);this.abortAllController=new ot;this.subscription=new Bk;this.fetchManifest=zi(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Qi(r));let a=yield nt(r,{signal:this.abortAllController.signal}).catch(Ji);return a?(t.log("success",Lr({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(a.headers),a.text()):(t.error("error",Lr({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=zi(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 R=new URL(u,location.href);R.searchParams.append("bytes",`${r.from}-${r.to}`),u=R.toString();break}default:Db(t)}this.requestQuic&&(u=Qi(u));let p=this.abortAllController.signal,h;if(n){let R=new ot;if(h=Dk(Bb(this.abortAllController.signal,"abort"),Bb(n,"abort")).subscribe(()=>{try{R.abort()}catch($){Ji($)}}),this.abortAllController.signal.aborted||n.aborted)try{R.abort()}catch($){Ji($)}p=R.signal}let m=Ki();l.log("startRequest",Lr({url:u,priority:s,rangeMethod:t,range:r,isLowLatency:c,requestStartedAt:m}));let b=yield nt(u,{priority:s,headers:d,signal:p}).catch(Ji),g=Ki();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 R=`Fetch error ${b.status}: ${b.statusText}`;return l.error("error",{message:R}),l.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!a&&!o){h?.unsubscribe();let R=Ki(),$={requestStartedAt:m,requestEndedAt:R,duration:R-m};return l.log("endRequest",Lr($)),l.end(),b.arrayBuffer()}let[v,k]=b.body.tee(),y=v.getReader();o&&this.throughputEstimator?.trackStream(k,c);let S=0,T=new Uint8Array(0),E=!1,D=R=>{h?.unsubscribe(),E=!0,Ji(R)},O=zi(p,async function*({done:R,value:$}){if(S===0&&this.lastRequestFirstBytes$.next(Ki()-m),p.aborted){h?.unsubscribe();return}if(!R&&$){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=Ki(),w={failed:E,requestStartedAt:m,requestEndedAt:N,duration:N-m};return E?(l.error("endRequest",Lr(w)),l.end(),null):(l.log("endRequest",Lr(w)),l.end(),T.buffer)}.bind(this));this.fetchByteRangeRepresentation=zi(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=zi(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}=Cb(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:Db(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Ji=i=>{if(!Gi(i))throw i};var Yt=(i,e,t)=>t*e+(1-t)*i,ku=(i,e)=>i.reduce((t,r)=>t+r,0)/e,Vb=(i,e,t,r)=>{let a=0,s=t,n=ku(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 Vk,ValueSubject as Ob}from"@vkontakte/videoplayer-shared";var Tt=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 Ob(e.initial),this.debounced$=new Ob(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new re(`raw_${t}`),this.smoothedSeries$=new re(`smoothed_${t}`),this.reportedSeries$=new re(`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)&&(Vk(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 xs=class extends Tt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Yt(this.slow,e,this.params.emaAlphaSlow),this.fast=Yt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Ps=class extends Tt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=ku(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Yt(this.emaSmoothed,e,this.params.emaAlpha);let r=Vb(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var As=class extends Tt{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?Yt(this.smoothed,t,this.params.emaAlpha):t}};var Qt=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new xs({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new Ps({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 As({initial:e,label:"liveEdgeDelay",...t})}};var wu=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};import{isNullable as Ok,ValueSubject as _k}from"@vkontakte/videoplayer-shared";var Xi=class i{constructor(e,t){this.currentRepresentation$=new _k(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(Ok(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&&qe(t.segmentReference))}};var Hb=["timeupdate","progress","play","seeked","stalled","waiting"];var Rs=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Ub;this.representationSubscription=new Ub;this.state$=new L("none");this.currentVideoRepresentation$=new X(void 0);this.currentVideoRepresentationInit$=new X(void 0);this.currentAudioRepresentation$=new X(void 0);this.currentVideoSegmentLength$=new X(0);this.currentAudioSegmentLength$=new X(0);this.error$=new qb;this.lastConnectionType$=new X(void 0);this.lastConnectionReused$=new X(void 0);this.lastRequestFirstBytes$=new X(void 0);this.currentLiveTextRepresentation$=new X(null);this.isLive$=new X(!1);this.liveDuration$=new X(0);this.liveAvailabilityStartTime$=new X(void 0);this.bufferLength$=new X(0);this.liveLoadBufferLength$=new X(0);this.livePositionFromPlayer$=new X(0);this.timeInWaiting=0;this.isActiveLowLatency$=new X(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new qb;this.gapWatchdogActive=!1;this.destroyController=new ot;this.initManifest=Ru(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=J(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:It.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Ru(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:It.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=Rb(e??"",this.manifestUrlString)}catch(n){let o=jm(e)??{id:"ManifestParsing",category:It.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)&&ut()?.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=Hm(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);Hk.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",Zi(s)),s}.bind(this));this.initRepresentations=Ru(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initRepresentationsStart",Zi({initialVideo:e,initialAudio:t,sourceHls:r})),zt(this.manifest),zt(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=l=>{this.representationSubscription.add(Mr(l,"error").pipe(ws(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:It.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=this.tuning.useManagedMediaSource?Bm():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&ms())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 Yi("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Fb(t)){let l=this.manifest.streams.audio.reduce((p,h)=>[...p,...h.representations],[]);this.audioBufferManager=new Yi("audio",this.source,l,n),this.bufferManagers.push(this.audioBufferManager)}if(Xi.isSupported(this.manifest.streams.text)&&!this.tuning.dashCmafLive.lowLatency.isActive&&(this.liveTextManager=new Xi(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($u(1e3).subscribe(l=>{if(this.element?.paused){let p=No(this.manifestUrlString,2);this.manifestUrlString=J(this.manifestUrlString,p+1e3,2)}})),this.representationSubscription.add(Cr(...Hb.filter(l=>l!=="waiting").map(l=>Mr(this.element,l))).pipe(Lu(l=>this.element?st(this.element.buffered,this.element.currentTime*1e3):0),Nb(),ws(l=>!!l),qk(l=>{this.stallWatchdogSubscription?.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Nb()).subscribe(p=>wu(this.element,1))),this.representationSubscription.add(ks({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(ws(({bufferLength:p,isActiveLowLatency:h})=>h&&!!p)).subscribe(({bufferLength:p})=>this.liveEstimatedDelay.next(p))),this.representationSubscription.add(ks({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,k=1;Math.abs(v)>b&&(k=1+Math.sign(v)*g),wu(this.element,k)})),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(ks({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Uk(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:h})=>{if(zt(this.element),this.isUpdatingLive)return;let m=this.element.playbackRate,b=No(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*m),k=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+k),N=this.normolizeLiveOffset(Math.trunc(b+O/m)),w=Math.abs(N-b),R;!p||w<=this.tuning.dashCmafLive.offsetCalculationError?R=b:N>0&&w>this.tuning.dashCmafLive.offsetCalculationError?R=N:R=0,this.manifestUrlString=J(this.manifestUrlString,R,2)}D!=="none"&&D!=="active_low_latency"&&(l=0,this.updateLive())}))}let c=Cr(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe(Lu(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),u=Cr(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe(Lu(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue())));this.representationSubscription.add(Cr(this.forceEnded$,ks({allBuffersFull:c,someBufferEnded:u}).pipe(ws(({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:It.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:l})}})),this.representationSubscription.add(Cr(...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.liveTextManager&&this.subscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),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),qe(l.segmentReference)&&l.segmentReference.totalSegmentsDurationMs&&p.push(l.segmentReference.totalSegmentsDurationMs),p})];this.source.duration=Math.max(...d)/1e3,this.audioBufferManager&&Fb(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=$u(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:It.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 Es({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=Qt.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator}),this.initTracerSubscription()}async seekLive(e){zt(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=J(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(){zt(this.element),this.state$.setState("running"),this.subscription.add(Cr(...Hb.map(e=>Mr(this.element,e)),Mr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:It.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Mr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Mr(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Ei(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",Zi(t))};this.videoBufferManager?.startAccumulateBuffer(),this.audioBufferManager?.startAccumulateBuffer(),this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=$u(1e3).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:It.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){zt(this.element),zt(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),Ei(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",Zi({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=jk(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.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,a=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?a.push(1/0):a.push(o.to));if(a.length){let n=Math.max(...a)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t={...t,gapEnds:a,jumpTo:n,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Zi(t)))}}};var $s=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ls=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 jb=`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 Gb=`#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 gs=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 bs(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ss(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(Lb,this.gl.VERTEX_SHADER),r=this.createShader($b,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,d=t+a,c=e-r,p=t+a;return[s,n,o,l,u,d,c,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var Ft=class{constructor(e){this.subscription=new KA;this.videoState=new $("stopped");this.elementSize$=new JA(void 0);this.textTracksManager=new Ie;this.droppedFramesManager=new Xa;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ya;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 UA(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new gs(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.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(W(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new ms({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=oe(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:Iu.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(Mb(u=>!!u.length),Ob()).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(Mb(QA),Ob()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(Db(u=>u.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(Ne(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(Te(this.video,t.playbackRate,r.playbackRateState$,a)),s(zA(this.video),this.elementSize$),s(xe(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(HA(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of d.audio){p.push(pu(h));let m=[];for(let b of h.representations){let S=mb(b);m.push(S),this.audioTracksMap.set(S,{stream:h,representation:b})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(p)}let c=[];for(let p of d.video){c.push(hu(p));let h=[];for(let m of p.representations){let b=fb(m);b&&(h.push(b),this.videoTracksMap.set(b,{stream:p,representation:m}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(c);for(let p of d.text)for(let h of p.representations){let m=bb(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:Iu.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(vs(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$,GA(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 c=this.selectVideoAudioRepresentations();if(!c)return;let[p,h]=c,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(Eu()).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[c,{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(c),e.currentVideoStream$.next(hu(p))},a)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Eu()).subscribe(u=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===u);if(!d){e.currentAudioStream$.next(void 0);return}let[c,{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(pu(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(Db(({to:u})=>u==="ready"),Eu());this.subscription.add(vs(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let u=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(vs(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=vs(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,YA(["init"])).pipe(jA(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),d=u&&this.videoStreamsMap.get(u);if(!d)return;let c=Ye(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(c/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:x})=>x===m?.id)??this.audioStreamsMap.keys().next().value,S=0;if(b){if(n&&!r){let x=os(n,d,this.audioStreamsMap.get(b)??[]);S=Math.max(S,x?.bitrate??-1/0)}if(o){let x=os(o,d,this.audioStreamsMap.get(b)??[]);S=Math.max(S,x?.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:S,forwardBufferHealth:h,current:o,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),{backgroundVideoQualityLimit:w}=this.params.tuning.autoTrackSelection;!this.params.output.elementVisible$.getValue()&&r&&(v=d.filter(x=>!WA(x.quality)).sort((x,D)=>(D.bitrate??0)-(x.bitrate??0)).filter(x=>Cb(x.quality,v.quality)&&Cb(x.quality,w))[0]??v);let T=r?v??n:n??v,g=b&&os(T,d,this.audioStreamsMap.get(b)??[]),y=this.videoTracksMap.get(T)?.representation,C=g&&this.audioTracksMap.get(g)?.representation;if(y&&C)return[y,C];if(y&&!C&&this.audioTracksMap.size===0)return[y,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:Iu.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),this.tracer.end()}};var Hi=class extends Ft{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 XA,map as ZA}from"@vkontakte/videoplayer-shared";var ji=class extends Ft{constructor(e){super(e),this.liveOffset=new Qe}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(Bb({interval:XA(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(ZA(({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 _b=Ve(Ga(),1);import{assertNever as Gi,assertNonNullable as Vb,debounce as ew,ErrorCategory as ys,filter as tw,isNonNullable as rw,isNullable as iw,map as Ts,merge as aw,Observable as sw,observableFrom as nw,Subscription as ow,videoSizeToQuality as uw}from"@vkontakte/videoplayer-shared";var De={};var xr=(i,e)=>new sw(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),Qi=class{constructor(e){this.subscription=new ow;this.videoState=new $("initializing");this.textTracksManager=new Ie;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:Gi(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Gi(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Gi(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:Gi(e)}break;default:Gi(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:ys.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,_b.default)(import("hls.js").then(a=>{e||(De.Hls=a.default,De.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){Vb(De.Hls,"hls.js not loaded"),this.hls=new De.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Vb(De.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=u=>{t.error$.next({id:"HlsJsProvider",category:ys.WTF,message:"HlsJsProvider internal logic error",thrown:u})},a=oe(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(Ne(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(Te(this.video,e.playbackRate,a.playbackRateState$,r)),s(xe(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(Ts(u=>u.to)),this.params.output.playbackState$),this.subscription.add(xr(this.hls,De.Events.ERROR).subscribe(u=>{u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:ys.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(xr(this.hls,De.Events.MANIFEST_PARSED).pipe(Ts(({levels:u})=>u.reduce((d,c)=>{let p=c.name||c.height.toString(10),{width:h,height:m}=c,b=ot(c.attrs.QUALITY??"")??uw({width:h,height:m});if(!b)return d;let S=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:b,bitrate:c.bitrate/1e3,size:{width:h,height:m},fps:S};return this.trackLevels.set(p,{track:v,level:c}),d.push(v),d},[]))),t.availableVideoTracks$),s(xr(this.hls,De.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){let d=[];for(let c of u.subtitleTracks){let p=c.name,h=c.attrs.URI||"",m=c.lang;d.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(d)}}),s(xr(this.hls,De.Events.LEVEL_LOADING).pipe(Ts(({url:u})=>W(u))),t.hostname$),s(xr(this.hls,De.Events.FRAG_CHANGED),u=>{let{video:d,audio:c}=u.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??0))*1e3)}),this.subscription.add(at(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=xr(this.hls,De.Events.LEVEL_SWITCHED).pipe(Ts(({level:u})=>n(this.hls.levels[u])));o.pipe(tw(rw)).subscribe(t.currentVideoTrack$,r),this.subscription.add(at(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),u=>{if(iw(u))return;let d=this.trackLevels.get(u.id)?.level;if(!d)return;let c=this.hls.levels.indexOf(d),p=this.hls.currentLevel,h=this.hls.levels[p];!h||d.bitrate>h.bitrate?this.hls.nextLevel=c:(this.hls.loadLevel=c,this.hls.loadLevel=c)},{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=aw(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,nw(["init"])).pipe(ew(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:ys.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 Nb="X-Playback-Duration",xu=async i=>{let e=await ze(i),t=await e.text(),r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return r?parseInt(r,10):e.headers.has(Nb)?parseInt(e.headers.get(Nb),10):void 0};import{assertNever as fw,combine as mw,debounce as bw,ErrorCategory as Es,filter as Sw,filterChanged as gw,isNonNullable as qb,isNullable as xs,map as Ub,merge as vw,observableFrom as yw,Subscription as Tw,ValueSubject as Au,VideoQuality as Iw}from"@vkontakte/videoplayer-shared";var ku=Ve(Gn(),1);import{videoSizeToQuality as lw,getExponentialDelay as cw}from"@vkontakte/videoplayer-shared";var dw=i=>{let e=null;if(i.QUALITY&&(e=ot(i.QUALITY)),!e&&i.RESOLUTION){let[t,r]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=lw({width:t,height:r})}return e??null},pw=(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,ku.default)(o[1].split(",").map(S=>S.split("="))),d=u.QUALITY??`stream-${u.BANDWIDTH}`,c=dw(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[S,v]=u.RESOLUTION.split("x").map(w=>parseInt(w,10));S&&v&&(m={width:S,height:v})}let b=new URL(t[++s],e).toString();c&&r.push({id:d,quality:c,url:b,bandwidth:p,size:m,fps:h})}if(l){let u=(0,ku.default)(l[1].split(",").map(h=>h.split("=")).map(([h,m])=>[h,m.replace(/^"|"$/g,"")])),d=u.URI?.replace(/playlist$/,"subtitles.vtt"),c=u.LANGUAGE,p=u.NAME;d&&c&&a.push({type:"internal",id:c,label:p,language:c,url:d,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:a}},hw=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),Pu=0,Fb=async(i,e=i,t)=>{let a=await(await ze(i)).text();Pu+=1;try{let{qualityManifests:s,textTracks:n}=pw(a,e);return{qualityManifests:s,textTracks:n}}catch{if(Pu<=t.manifestRetryMaxCount)return await hw(cw(Pu-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Fb(i,e,t)}return{qualityManifests:[],textTracks:[]}},Is=Fb;var Wi=class{constructor(e){this.subscription=new Tw;this.videoState=new $("stopped");this.textTracksManager=new Ie;this.manifests$=new Au([]);this.liveOffset=new Qe;this.manifestStartTime$=new Au(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 fw(t)}};this.params=e,this.video=ae(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Iw.INVARIANT,url:this.params.source.url},Is(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:Es.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Es.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 Au(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:Es.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(Te(this.video,t.playbackRate,a.playbackRateState$,r)),s(xe(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(gw(),Ub(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(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&qb(u.to)){let c=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let p=this.manifests$.getValue().find(h=>h.id===c);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(W(p.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.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(mw({startTime:this.manifestStartTime$.pipe(Sw(qb)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:l})=>this.params.output.liveTime$.next(o+l*1e3),r)),this.subscription.add(this.manifests$.pipe(Ub(o=>o.map(({id:l,quality:u,size:d,bandwidth:c,fps:p})=>({id:l,quality:u,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,r));let n=vw(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,yw(["init"])).pipe(bw(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(xs(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,d]of[[o,"mq"],[l,"lq"]]){let c=String(parseFloat(u||""));d&&u&&a.searchParams.set(d,c)}}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(),xu(n).then(o=>{if(!xs(o))this.maxSeekBackTime$.next(o);else{let l=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(xs(l)||!isFinite(l))try{ze(n).then(u=>u.text()).then(u=>{let d=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(u)?.[1];if(d){let c=new URL(d,n).toString();xu(c).then(p=>{xs(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:Es.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 Ew,debounce as xw,ErrorCategory as wu,fromEvent as Ru,isNonNullable as Pw,isNullable as kw,map as Hb,merge as jb,observableFrom as Gb,Subscription as Aw,ValueSubject as ww,VideoQuality as Rw,clientChecker as Lw}from"@vkontakte/videoplayer-shared";var Yi=class{constructor(e){this.subscription=new Aw;this.videoState=new $("stopped");this.textTracksManager=new Ie;this.manifests$=new ww([]);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:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*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 Ew(t)}};this.params=e,this.video=ae(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Rw.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),Is(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:wu.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:wu.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(Hb(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ne(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(Te(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(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&Pw(u.to)){let c=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let p=this.manifests$.getValue().find(h=>h.id===c);if(p){this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(W(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),l&&l.from==="changing_manifest"&&this.videoState.setState(l.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(Hb(o=>o.map(({id:l,quality:u,size:d,bandwidth:c,fps:p})=>({id:l,quality:u,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,r)),!Lw.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(jb(Ru(o,"addtrack"),Ru(o,"removetrack"),Ru(o,"change"),Gb(["init"])).subscribe(()=>{for(let l=0;l<o.length;l++)o[l].mode="hidden"},r))}let n=jb(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Gb(["init"])).pipe(xw(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(kw(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:wu.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as $w,assertNonNullable as Qb,debounce as Mw,ErrorCategory as Wb,isHigher as Cw,isHigherOrEqual as Dw,isInvariantQuality as Yb,isLowerOrEqual as Ow,isNonNullable as Bw,merge as Vw,observableFrom as _w,Subscription as Nw,map as Fw}from"@vkontakte/videoplayer-shared";var zi=class{constructor(e){this.subscription=new Nw;this.videoState=new $("stopped");this.trackUrls={};this.textTracksManager=new Ie;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 $w(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:Wb.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(Fw(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ne(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(Te(this.video,t.playbackRate,a.playbackRateState$,r)),s(xe(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&&Bw(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 d=this.params.output.element$.getValue();d&&(this.params.desiredState.playbackRate.setState(l),d.playbackRate=l)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=Vw(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,_w(["init"])).pipe(Mw(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;Qb(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Qb(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Vi(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:Wb.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=>!Yb(o.track.quality)&&Ow(o.track.quality,e))?.track,s=this.params.desiredState.videoTrack.getState()?.id,n=this.trackUrls[s??"0"]?.track;if(a&&n&&Dw(n.quality,a.quality)&&(t=a),!t){let o=Object.values(this.trackUrls).filter(u=>!Yb(u.track.quality)&&Cw(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=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 Kb,debounce as jw,merge as Jb,observableFrom as Gw,Subscription as Qw,map as Xb,ValueSubject as Ww,ErrorCategory as $u,VideoQuality as Yw}from"@vkontakte/videoplayer-shared";import{ErrorCategory as qw}from"@vkontakte/videoplayer-shared";var zb=["stun:videostun.mycdn.me:80"],Uw=1e3,Hw=3,Lu=()=>null,Ps=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=Lu;this.externalStopCallback=Lu;this.externalErrorCallback=Lu;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:zb}]};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:qw.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),Uw)}normalizeOptions(e={}){let t={stunServerList:zb,maxRetryNumber:Hw,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ki=class{constructor(e){this.videoState=new $("stopped");this.maxSeekBackTime$=new Ww(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 Kb(e)}};this.subscription=new Qw,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ae(e.container,e.tuning),this.liveStreamClient=new Ps(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:$u.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};Jb(this.videoState.stateChangeStarted$.pipe(Xb(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Xb(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(xe(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 Kb(n.to)}},r)).add(Jb(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Gw(["init"])).pipe(jw(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:Yw.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:$u.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:$u.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ji=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 ea,assertNonNullable as pt,ErrorCategory as As,filter as tR,isNonNullable as aS,isNullable as rR,map as iR,merge as aR,once as sR,Subject as be,Subscription as sS,ValueSubject as M,flattenObject as nS}from"@vkontakte/videoplayer-shared";import{Observable as zw,map as Zb,Subscription as Kw,Subject as Jw}from"@vkontakte/videoplayer-shared";var eS=i=>new zw(e=>{let t=new Kw,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(Zb(({from:u,to:d})=>`${u}-${d}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe(Zb(({type:u})=>u!==void 0)),n=new Jw,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 tS,Subscription as Xw,combine as Zw,filter as rS,once as iS}from"@vkontakte/videoplayer-shared";var Xi=null,ks=null;function Mu(){return Xi||(Xi=new(window.AudioContext||window.webkitAudioContext)),ks||(ks=new GainNode(Xi,{gain:1}),ks.connect(Xi.destination)),{audioCtx:Xi,gainNode:ks}}import{clientChecker as eR}from"@vkontakte/videoplayer-shared";var Zi=class i{constructor(e,t,r,a,s){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=a;this.subscriptions=new Xw;this.lastAudioContextResumeId=0;!s||!this.isSupported()||a===1||this.subscriptions.add(this.provider$.pipe(rS(n=>!!n.type),iS()).subscribe(({type:n})=>this.subscribe(n)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){eR.isSafari&&e!=="MPEG"||this.subscriptions.add(Zw({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(rS(({playbackState:t,video:r,volume:{muted:a,volume:s}})=>t==="playing"&&!!r&&!a&&!!s),iS()).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}=Mu(),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:tS.VIDEO_PIPELINE,message:n?.message??"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:n})}}).catch(n=>{this.volumeMultiplierError$.next({id:i.errorId,category:tS.VIDEO_PIPELINE,message:n?.message??"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){let{gainNode:e}=Mu();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};var nR={chunkDuration:5e3,maxParallelRequests:5},ta=class{constructor(e){this.current$=new M({type:void 0});this.providerError$=new be;this.noAvailableProvidersError$=new be;this.volumeMultiplierError$=new be;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 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 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 sS;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=Em([...Pm(this.params.tuning),...xm(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>aS(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",nS(s)),this.screenFormatsIterator=new Ji(s);let n=[...Jo(!0),...Jo(!1)];this.chromecastFormatsIterator=new Ji(n.filter(o=>aS(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new Zi(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(rR(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:As.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 ea(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 pt(o),new Hi({...n,source:o,sourceHls:l})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return pt(o),new ji({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return pt(o),fr||!this.params.tuning.useHlsJs?new Yi({...n,source:o}):new Qi({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return pt(o),new Wi({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return pt(o),new zi({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return pt(o),new mm({...n,source:o,config:{...nR,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return pt(o),new Ki({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 ea(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 pt(o),new Xr({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 ea(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return ea(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 ea(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 sS,t=!1,r=0;return e.add(aR(this.providerOutput.error$,eS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(iR(a=>({id:`ProviderHangup:${a}`,category:As.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(tR(({to:s})=>s==="playing"),sR()).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===As.NETWORK,l=a.category===As.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=r<this.params.tuning.providerErrorLimit&&!l,c=u&&!l&&(o&&t||!d);n={...n,isNetworkError:o,isFatalError:l,haveFailoverHost:u,tryFailover:c,canReinitProvider:d},c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(r++,this.reinitProvider()):this.switchToNextProvider(s??"SCREEN")}this.tracer.error("providerError",nS(n))})),e}};import{fromEvent as ws,once as oR,combine as uR,Subscription as uS,ValueSubject as Cu,map as lR,filter as cR,isNonNullable as Rs,now as Se,safeStorage as Du}from"@vkontakte/videoplayer-shared";var dR=5e3,lS="one_video_throughput",cS="one_video_rtt",ra=window.navigator.connection,dS=()=>{let i=ra?.downlink;if(Rs(i)&&i!==10)return i*1e3},pS=()=>{let i=ra?.rtt;if(Rs(i)&&i!==3e3)return i},hS=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},Ou=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)||dR,r=i.load(cS)??(e.useBrowserEstimation?pS():void 0)??0;if(this.throughput$=new Cu(t),this.rtt$=new Cu(r),this.rttAdjustedThroughput$=new Cu(hS(t,r,e.rttPenaltyRequestSize)),this.throughput=_t.getSmoothedValue(t,-1,e),this.rtt=_t.getSmoothedValue(r,1,e),e.useBrowserEstimation){let a=()=>{let n=dS();n&&this.throughput.next(n);let o=pS();Rs(o)&&this.rtt.next(o)};ra&&"onchange"in ra&&this.subscription.add(ws(ra,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{Du.set(lS,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{Du.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(uR({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(lR(({throughput:a,rtt:s})=>hS(a,s,e.rttPenaltyRequestSize)),cR(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(ws(e,"progress").pipe(oR()).subscribe(s=>{t=s.loaded,r=Se()}));break;case 1:case 0:a.add(ws(e,"loadstart").subscribe(()=>{t=0,r=Se()}));break}a.add(ws(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=d=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},u=async({done:d,value:c})=>{if(d)!t&&this.addRawSpeed(a,Se()-s,1),this.concurrentDownloads.delete(e);else if(c){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=c.byteLength,s=Se()}else n+=c.byteLength;o=Se()}else a+=c.byteLength,n+=c.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=Du.get(e);if(Rs(t))return parseInt(t,10)??void 0}},fS=Ou;import{fillWithDefault as pR,VideoQuality as mS}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:mS.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:mS.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=>({...pR(i,bS),configName:[...i.configName??[],...bS.configName]});import{assertNonNullable as Ls,combine as ht,ErrorCategory as $s,filter as ee,filterChanged as V,fromEvent as Vu,isNonNullable as vR,isNullable as yR,Logger as TR,map as O,mapTo as TS,merge as ft,now as Ms,once as Xe,Subject as F,Subscription as IS,tap as ES,ValueSubject as E,isHigher as IR,isInvariantQuality as xS,flattenObject as mt,throttle as _u,getTraceSubscriptionMethod as PS}from"@vkontakte/videoplayer-shared";import{merge as hR,map as fR,filter as gS,isNonNullable as mR}from"@vkontakte/videoplayer-shared";var Bu=({seekState:i,position$:e})=>hR(i.stateChangeEnded$.pipe(fR(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),gS(mR)),e.pipe(gS(()=>i.getState().state==="none")));import{assertNonNullable as bR}from"@vkontakte/videoplayer-shared";var vS=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return bR(e,`Wrong container or containerId {${i.container}}`),e};import{filter as SR,once as gR}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(SR(a=>a.length>0),gR()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t?.getValue().find(r))&&e.startTransitionTo(i)};var Cs=class{constructor(e={configName:[]},t){this.subscription=new IS;this.logger=new TR;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new E(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new $("stopped"),seekState:new $({state:"none"}),volume:new $({volume:1,muted:!1}),videoTrack:new $(void 0),videoStream:new $(void 0),audioStream:new $(void 0),autoVideoTrackSwitching:new $(!0),autoVideoTrackLimits:new $({}),isLooped:new $(!1),playbackRate:new $(1),externalTextTracks:new $([]),internalTextTracks:new $([]),currentTextTrack:new $(void 0),textTrackCuesSettings:new $({}),cameraOrientation:new $({x:0,y:0})};this.info={playbackState$:new E("stopped"),position$:new E(0),duration$:new E(1/0),muted$:new E(!1),volume$:new E(1),availableVideoStreams$:new E([]),currentVideoStream$:new E(void 0),availableQualities$:new E([]),availableQualitiesFps$:new E({}),currentQuality$:new E(void 0),isAutoQualityEnabled$:new E(!0),autoQualityLimitingAvailable$:new E(!1),autoQualityLimits$:new E({}),availableAudioStreams$:new E([]),currentAudioStream$:new E(void 0),availableAudioTracks$:new E([]),isAudioAvailable$:new E(!0),currentPlaybackRate$:new E(1),currentBuffer$:new E({start:0,end:0}),isBuffering$:new E(!0),isStalled$:new E(!1),isEnded$:new E(!1),isLooped$:new E(!1),isLive$:new E(void 0),canChangePlaybackSpeed$:new E(void 0),atLiveEdge$:new E(void 0),atLiveDurationEdge$:new E(void 0),liveTime$:new E(void 0),liveBufferTime$:new E(void 0),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 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 E(void 0),tuningConfigName$:new E([]),enableDebugTelemetry$:new E(!1),dumpTelemetry:tm};if(this.initLogs(),this.tuning=SS(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ca({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new fS(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(l){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)}`,c=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:$s.WTF,message:c,thrown:l}),l}}}})}initVideo(e){return this.config=e,this.tracer.log("initVideo",mt(e)),this.domContainer=vS(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new ta({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&&!oi()?(this.tracer.log("request play from hidden tab"),Vu(document,"visibilitychange").pipe(Xe()).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){Ls(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),Xe()).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",mt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){Ls(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",mt(e)),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.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(yR(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return vR(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(ft(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(O(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(O(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(O(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(O(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(O(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(ee(({from:e})=>e==="stopped"),Xe()).subscribe(()=>{this.initedAt=Ms(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",mt(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:$s.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",mt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(O(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(O(n=>n.destination),V()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(O(n=>n.map(({quality:o})=>o).sort((o,l)=>xS(o)?1:xS(l)?-1:IR(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$.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(O(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(ht({hasLiveOffsetByPaused:ft(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(O(n=>n.to),V(),O(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(ht({atLiveEdge:ht({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Bu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(O(({isLive:n,position:o,isLowLatency:l})=>{let u=this.getActiveLiveDelay(l);return n&&Math.abs(o)<u/1e3}),V(),ES(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(O(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(ht({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(O(({isLive:n,position:o,duration:l})=>n&&(Math.abs(l)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),V(),ES(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(O(n=>n.muted),V()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(O(n=>n.volume),V()).subscribe(this.info.volume$)).add(Bu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(ft(e.providerOutput.endedEvent$.pipe(TS(!0)),e.providerOutput.seekedEvent$.pipe(TS(!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(O(n=>({id:n?`No${n}`:"NoProviders",category:$s.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(Xe(),O(n=>n??Ms()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(Xe(),O(()=>Ms()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Xe(),O(()=>Ms()-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(ee(({to:n})=>n==="playing"),Xe()).subscribe(()=>r.next(!1)));let a=0,s=ft(e.providerOutput.isBuffering$,t,r).pipe(O(()=>{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(ft(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(ft(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(),d=this.chromecastInitializer.castState$.getValue(),c;d==="CONNECTED"?c="second_screen":l?u?n?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(O(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(V((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ee(r=>r.length>0),Xe()).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(ft(this.desiredState.videoTrack.stateChangeStarted$.pipe(O(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(O(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(O(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(O(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(O(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(O(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(O(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(O(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(O(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;Ls(this.providerContainer),Ls(e),em(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Zf(t)),this.providerContainer.current$.subscribe(({type:t})=>ri("provider",t)),e.duration$.subscribe(t=>ri("duration",t)),e.availableVideoTracks$.pipe(ee(t=>!!t.length),Xe()).subscribe(t=>ri("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(O(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)),ri("codecs",Im())}initTracerSubscription(){let e=PS(this.tracer.log.bind(this.tracer)),t=PS(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(ht({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(ht({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(_u(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(ht({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(ee(({liveTime:r,liveBufferTime:a})=>!!r&&!!a),_u(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(ht({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(ee(({throughputEstimation:r,rtt:a})=>!!r&&!!a),_u(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:$s.DOM,message:String(a)})})};this.subscription.add(ft(Vu(document,"visibilitychange"),Vu(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",mt({quality:t,availableTracks:mt(e),track:mt(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 aj,Observable as sj,Subject as nj,ValueSubject as oj,VideoQuality as uj}from"@vkontakte/videoplayer-shared";var lj=`@vkontakte/videoplayer-core@${qu}`;export{ua as ChromecastState,qs as HttpConnectionType,sj as Observable,re as PlaybackState,Cs as Player,lj as SDK_VERSION,nj as Subject,aj as Subscription,Us as Surface,qu as VERSION,oj as ValueSubject,rt as VideoFormat,uj as VideoQuality};
|
|
112
|
+
`;var Ms=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 $s(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ls(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(jb,this.gl.VERTEX_SHADER),r=this.createShader(Gb,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 Kt=class{constructor(e){this.subscription=new rw;this.videoState=new L("stopped");this.elementSize$=new iw(void 0);this.textTracksManager=new ke;this.droppedFramesManager=new ds;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new hi;this.audioTrackSwitchHistory=new hi;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 zk(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Ms(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=oe(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(Q(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Rs({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=le(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:Mu.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(Wb(u=>!!u.length),Qb()).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(Wb(Zk),Qb()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(Yb(u=>u.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(Qe(this.video,t.isLooped,a)),this.subscription.add(ce(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Ae(this.video,t.playbackRate,r.playbackRateState$,a)),s(tw(this.video),this.elementSize$),s(Re(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(Kk(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of d.audio){p.push(Tu(h));let m=[];for(let b of h.representations){let g=Lb(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(Iu(p));let h=[];for(let m of p.representations){let b=$b(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=Ts(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:Mu.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(Cs(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$,Xk(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(Cu()).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(Iu(p))},a)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Cu()).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(Tu(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(Yb(({to:u})=>u==="ready"),Cu());this.subscription.add(Cs(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(Cs(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let c=Cs(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ew(["init"])).pipe(Jk(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=st(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=os(n,d,this.audioStreamsMap.get(b)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,E?.bitrate??-1/0)}else{let E=ys(n,d,this.audioStreamsMap.get(b)??[]);g=Math.max(g,E?.bitrate??-1/0)}if(o)if(this.params.tuning.useSeparateAudioVideoABR){let E=os(o,d,this.audioStreamsMap.get(b)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,E?.bitrate??-1/0)}else{let E=ys(o,d,this.audioStreamsMap.get(b)??[]);g=Math.max(g,E?.bitrate??-1/0)}}let v=yt(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}),k=r?v??n:n??v,y;this.params.tuning.useSeparateAudioVideoABR?y=b&&Tm(k,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&&ys(k,d,this.audioStreamsMap.get(b)??[]);let S=this.videoTracksMap.get(k)?.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(){pe(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:Mu.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),ue(this.video),this.tracer.end()}};var ta=class extends Kt{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 zb,interval as aw,map as sw}from"@vkontakte/videoplayer-shared";var ra=class extends Kt{constructor(e){super(e),this.liveOffset=new it}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(zb({interval:aw(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(zb({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(sw(({liveBufferTime:a,liveAvailabilityStartTime:s})=>a&&s?a+s:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(a=>{if(a){let s=Ts(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 Jb=We(as(),1);import{assertNever as ia,assertNonNullable as Kb,debounce as nw,ErrorCategory as Ds,filter as ow,isNonNullable as uw,isNullable as cw,map as Bs,merge as lw,Observable as dw,observableFrom as pw,Subscription as hw,videoSizeToQuality as fw}from"@vkontakte/videoplayer-shared";var Ue={};var Dr=(i,e)=>new dw(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),aa=class{constructor(e){this.subscription=new hw;this.videoState=new L("initializing");this.textTracksManager=new ke;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:ia(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:ia(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:ia(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:ia(e)}break;default:ia(t)}};this.video=oe(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(Q(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),ue(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Ds.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Jb.default)(import("hls.js").then(a=>{e||(Ue.Hls=a.default,Ue.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){Kb(Ue.Hls,"hls.js not loaded"),this.hls=new Ue.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Kb(Ue.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=u=>{t.error$.next({id:"HlsJsProvider",category:Ds.WTF,message:"HlsJsProvider internal logic error",thrown:u})},a=le(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(Qe(this.video,e.isLooped,r)),this.subscription.add(ce(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ae(this.video,e.playbackRate,a.playbackRateState$,r)),s(Re(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(Bs(u=>u.to)),this.params.output.playbackState$),this.subscription.add(Dr(this.hls,Ue.Events.ERROR).subscribe(u=>{u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:Ds.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(Dr(this.hls,Ue.Events.MANIFEST_PARSED).pipe(Bs(({levels:u})=>u.reduce((d,l)=>{let p=l.name||l.height.toString(10),{width:h,height:m}=l,b=vt(l.attrs.QUALITY??"")??fw({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(Dr(this.hls,Ue.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(Dr(this.hls,Ue.Events.LEVEL_LOADING).pipe(Bs(({url:u})=>Q(u))),t.hostname$),s(Dr(this.hls,Ue.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(bt(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=Dr(this.hls,Ue.Events.LEVEL_SWITCHED).pipe(Bs(({level:u})=>n(this.hls.levels[u])));o.pipe(ow(uw)).subscribe(t.currentVideoTrack$,r),this.subscription.add(bt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),u=>{if(cw(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=lw(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,pw(["init"])).pipe(nw(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 pe(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ds.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 Xb="X-Playback-Duration",Du=async i=>{let e=await nt(i),t=await e.text(),r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return r?parseInt(r,10):e.headers.has(Xb)?parseInt(e.headers.get(Xb),10):void 0};import{assertNever as yw,combine as Tw,debounce as Iw,ErrorCategory as Os,filter as Ew,filterChanged as xw,isNonNullable as eg,isNullable as _s,map as tg,merge as Pw,observableFrom as Aw,Subscription as kw,ValueSubject as Ou,VideoQuality as ww}from"@vkontakte/videoplayer-shared";var Vu=We(Zn(),1);import{videoSizeToQuality as mw,getExponentialDelay as bw}from"@vkontakte/videoplayer-shared";var gw=i=>{let e=null;if(i.QUALITY&&(e=vt(i.QUALITY)),!e&&i.RESOLUTION){let[t,r]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=mw({width:t,height:r})}return e??null},Sw=(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,Vu.default)(o[1].split(",").map(g=>g.split("="))),d=u.QUALITY??`stream-${u.BANDWIDTH}`,l=gw(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(k=>parseInt(k,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,Vu.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}},vw=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),Bu=0,Zb=async(i,e=i,t)=>{let a=await(await nt(i)).text();Bu+=1;try{let{qualityManifests:s,textTracks:n}=Sw(a,e);return{qualityManifests:s,textTracks:n}}catch{if(Bu<=t.manifestRetryMaxCount)return await vw(bw(Bu-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Zb(i,e,t)}return{qualityManifests:[],textTracks:[]}},Vs=Zb;var sa=class{constructor(e){this.subscription=new kw;this.videoState=new L("stopped");this.textTracksManager=new ke;this.manifests$=new Ou([]);this.liveOffset=new it;this.manifestStartTime$=new Ou(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 yw(t)}};this.params=e,this.video=oe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ww.INVARIANT,url:this.params.source.url},Vs(J(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:Os.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Os.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(Q(this.params.source.url)),this.maxSeekBackTime$=new Ou(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:Os.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=le(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(ce(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ae(this.video,t.playbackRate,a.playbackRateState$,r)),s(Re(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(xw(),tg(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&&eg(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(Q(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(Tw({startTime:this.manifestStartTime$.pipe(Ew(eg)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:c})=>this.params.output.liveTime$.next(o+c*1e3),r)),this.subscription.add(this.manifests$.pipe(tg(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=Pw(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Aw(["init"])).pipe(Iw(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ue(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: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=J(a.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),Du(n).then(o=>{if(!_s(o))this.maxSeekBackTime$.next(o);else{let c=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(_s(c)||!isFinite(c))try{nt(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();Du(l).then(p=>{_s(p)||this.maxSeekBackTime$.next(p)})}})}catch{}}})}playIfAllowed(){pe(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:Os.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 Rw,debounce as $w,ErrorCategory as _u,fromEvent as Nu,isNonNullable as Lw,isNullable as Mw,map as rg,merge as ig,observableFrom as ag,Subscription as Cw,ValueSubject as Dw,VideoQuality as Bw,clientChecker as Vw}from"@vkontakte/videoplayer-shared";var na=class{constructor(e){this.subscription=new Cw;this.videoState=new L("stopped");this.textTracksManager=new ke;this.manifests$=new Dw([]);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 Rw(t)}};this.params=e,this.video=oe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Bw.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(Q(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Vs(J(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:_u.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:_u.WTF,message:"HlsProvider internal logic error",thrown:o})},a=le(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(rg(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Qe(this.video,t.isLooped,r)),this.subscription.add(ce(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ae(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&&Lw(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(Q(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(rg(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)),!Vw.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(ig(Nu(o,"addtrack"),Nu(o,"removetrack"),Nu(o,"change"),ag(["init"])).subscribe(()=>{for(let c=0;c<o.length;c++)o[c].mode="hidden"},r))}let n=ig(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,ag(["init"])).pipe($w(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ue(this.video)}prepare(){let e=this.selectManifest();if(Mw(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(){pe(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:_u.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as Ow,assertNonNullable as sg,debounce as _w,ErrorCategory as ng,isHigher as Nw,isHigherOrEqual as Fw,isInvariantQuality as og,isLowerOrEqual as qw,isNonNullable as Uw,merge as Hw,observableFrom as jw,Subscription as Gw,map as Ww}from"@vkontakte/videoplayer-shared";var oa=class{constructor(e){this.subscription=new Gw;this.videoState=new L("stopped");this.trackUrls={};this.textTracksManager=new ke;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 Ow(e)}};this.params=e,this.video=oe(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:ng.WTF,message:"MpegProvider internal logic error",thrown:o})},a=le(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(Ww(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Qe(this.video,t.isLooped,r)),this.subscription.add(ce(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ae(this.video,t.playbackRate,a.playbackRateState$,r)),s(Re(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&&Uw(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=Hw(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,jw(["init"])).pipe(_w(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),ue(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;sg(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];sg(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Qi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Q(t))}playIfAllowed(){pe(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:ng.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=>!og(o.track.quality)&&qw(o.track.quality,e))?.track,s=this.params.desiredState.videoTrack.getState()?.id,n=this.trackUrls[s??"0"]?.track;if(a&&n&&Fw(n.quality,a.quality)&&(t=a),!t){let o=Object.values(this.trackUrls).filter(u=>!og(u.track.quality)&&Nw(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=yt(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 cg,debounce as Kw,merge as lg,observableFrom as Jw,Subscription as Xw,map as dg,ValueSubject as Zw,ErrorCategory as qu,VideoQuality as eR}from"@vkontakte/videoplayer-shared";import{ErrorCategory as Yw}from"@vkontakte/videoplayer-shared";var ug=["stun:videostun.mycdn.me:80"],Qw=1e3,zw=3,Fu=()=>null,Ns=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=Fu;this.externalStopCallback=Fu;this.externalErrorCallback=Fu;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:ug}]};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:Yw.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),Qw)}normalizeOptions(e={}){let t={stunServerList:ug,maxRetryNumber:zw,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var ua=class{constructor(e){this.videoState=new L("stopped");this.maxSeekBackTime$=new Zw(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 cg(e)}};this.subscription=new Xw,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=oe(e.container,e.tuning),this.liveStreamClient=new Ns(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),ue(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:qu.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};lg(this.videoState.stateChangeStarted$.pipe(dg(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(dg(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=le(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(Re(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(ce(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 cg(n.to)}},r)).add(lg(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Jw(["init"])).pipe(Kw(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(Q(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:eR.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:qu.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){pe(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:qu.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var ca=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 pa,assertNonNullable as Et,ErrorCategory as qs,filter as oR,isNonNullable as gg,isNullable as uR,map as cR,merge as lR,once as dR,Subject as ve,Subscription as Sg,ValueSubject as M,flattenObject as vg}from"@vkontakte/videoplayer-shared";import{Observable as tR,map as pg,Subscription as rR,Subject as iR}from"@vkontakte/videoplayer-shared";var hg=i=>new tR(e=>{let t=new rR,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(pg(({from:u,to:d})=>`${u}-${d}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe(pg(({type:u})=>u!==void 0)),n=new iR,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 fg,Subscription as aR,combine as sR,filter as mg,once as bg}from"@vkontakte/videoplayer-shared";var la=null,Fs=null;function Uu(){return la||(la=new(window.AudioContext||window.webkitAudioContext)),Fs||(Fs=new GainNode(la,{gain:1}),Fs.connect(la.destination)),{audioCtx:la,gainNode:Fs}}import{clientChecker as nR}from"@vkontakte/videoplayer-shared";var da=class i{constructor(e,t,r,a,s){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=a;this.subscriptions=new aR;this.lastAudioContextResumeId=0;!s||!this.isSupported()||a===1||this.subscriptions.add(this.provider$.pipe(mg(n=>!!n.type),bg()).subscribe(({type:n})=>this.subscribe(n)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){nR.isSafari&&e!=="MPEG"||this.subscriptions.add(sR({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(mg(({playbackState:t,video:r,volume:{muted:a,volume:s}})=>t==="playing"&&!!r&&!a&&!!s),bg()).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}=Uu(),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:fg.VIDEO_PIPELINE,message:n?.message??"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:n})}}).catch(n=>{this.volumeMultiplierError$.next({id:i.errorId,category:fg.VIDEO_PIPELINE,message:n?.message??"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){let{gainNode:e}=Uu();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};var pR={chunkDuration:5e3,maxParallelRequests:5},ha=class{constructor(e){this.current$=new M({type:void 0});this.providerError$=new ve;this.noAvailableProvidersError$=new ve;this.volumeMultiplierError$=new ve;this.providerOutput={position$:new M(0),duration$:new M(1/0),volume$:new M({muted:!1,volume:1}),availableVideoStreams$:new M([]),currentVideoStream$:new M(void 0),availableVideoTracks$:new M([]),currentVideoTrack$:new M(void 0),availableAudioStreams$:new M([]),currentAudioStream$:new M(void 0),availableAudioTracks$:new M([]),currentVideoSegmentLength$:new M(0),currentAudioSegmentLength$:new M(0),isAudioAvailable$:new M(!0),autoVideoTrackLimitingAvailable$:new M(!1),autoVideoTrackLimits$:new M(void 0),currentBuffer$:new M(void 0),isBuffering$:new M(!0),error$:new ve,warning$:new ve,willSeekEvent$:new ve,seekedEvent$:new ve,loopedEvent$:new ve,endedEvent$:new ve,firstBytesEvent$:new ve,loadedMetadataEvent$:new ve,firstFrameEvent$:new ve,canplay$:new ve,isLive$:new M(void 0),isLowLatency$:new M(!1),canChangePlaybackSpeed$:new M(!0),liveTime$:new M(void 0),liveBufferTime$:new M(void 0),availableTextTracks$:new M([]),currentTextTrack$:new M(void 0),hostname$:new M(void 0),httpConnectionType$:new M(void 0),httpConnectionReused$:new M(void 0),inPiP$:new M(!1),inFullscreen$:new M(!1),element$:new M(void 0),elementVisible$:new M(!0),availableSources$:new M(void 0),is3DVideo$:new M(!1),playbackState$:new M("")};this.subscription=new Sg;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=Fm([...Um(this.params.tuning),...qm(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>gg(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",vg(s)),this.screenFormatsIterator=new ca(s);let n=[...su(!0),...su(!1)];this.chromecastFormatsIterator=new ca(n.filter(o=>gg(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new da(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(uR(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:qs.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 pa(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 Et(o),new ta({...n,source:o,sourceHls:c})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Et(o),new ra({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Et(o),xr||!this.params.tuning.useHlsJs?new na({...n,source:o}):new aa({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Et(o),new sa({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Et(o),new oa({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Et(o),new Mm({...n,source:o,config:{...pR,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Et(o),new ua({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 pa(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 Et(o),new ui({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 pa(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return pa(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 pa(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,yg.default)(Object.entries(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new Sg,t=!1,r=0;return e.add(lR(this.providerOutput.error$,hg({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(cR(a=>({id:`ProviderHangup:${a}`,category:qs.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(oR(({to:s})=>s==="playing"),dR()).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===qs.NETWORK,c=a.category===qs.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",vg(n))})),e}};import{fromEvent as Us,once as hR,combine as fR,Subscription as Tg,ValueSubject as Hu,map as mR,filter as bR,isNonNullable as Hs,now as ye,safeStorage as ju}from"@vkontakte/videoplayer-shared";var gR=5e3,Ig="one_video_throughput",Eg="one_video_rtt",fa=window.navigator.connection,xg=()=>{let i=fa?.downlink;if(Hs(i)&&i!==10)return i*1e3},Pg=()=>{let i=fa?.rtt;if(Hs(i)&&i!==3e3)return i},Ag=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},Gu=class i{constructor(e){this.subscription=new Tg;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=i.load(Ig)||(e.useBrowserEstimation?xg():void 0)||gR,r=i.load(Eg)??(e.useBrowserEstimation?Pg():void 0)??0;if(this.throughput$=new Hu(t),this.rtt$=new Hu(r),this.rttAdjustedThroughput$=new Hu(Ag(t,r,e.rttPenaltyRequestSize)),this.throughput=Qt.getSmoothedValue(t,-1,e),this.rtt=Qt.getSmoothedValue(r,1,e),e.useBrowserEstimation){let a=()=>{let n=xg();n&&this.throughput.next(n);let o=Pg();Hs(o)&&this.rtt.next(o)};fa&&"onchange"in fa&&this.subscription.add(Us(fa,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{ju.set(Ig,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{ju.set(Eg,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(fR({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(mR(({throughput:a,rtt:s})=>Ag(a,s,e.rttPenaltyRequestSize)),bR(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=ye(),a=new Tg;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(Us(e,"progress").pipe(hR()).subscribe(s=>{t=s.loaded,r=ye()}));break;case 1:case 0:a.add(Us(e,"loadstart").subscribe(()=>{t=0,r=ye()}));break}a.add(Us(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=ye(),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=ye(),n=0,o=ye(),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,ye()-s,1),this.concurrentDownloads.delete(e);else if(l){if(t){let p=ye();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=ye()}else n+=l.byteLength;o=ye()}else a+=l.byteLength,n+=l.byteLength,n>=this.tuningConfig.streamMinSampleSize&&ye()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,ye()-o,this.concurrentDownloads.size),n=0,o=ye());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=ju.get(e);if(Hs(t))return parseInt(t,10)??void 0}},kg=Gu;import{fillWithDefault as SR,VideoQuality as wg}from"@vkontakte/videoplayer-shared";var Rg={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:wg.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:wg.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},$g=i=>({...SR(i,Rg),configName:[...i.configName??[],...Rg.configName]});import{assertNonNullable as js,combine as xt,ErrorCategory as Gs,filter as ie,filterChanged as V,fromEvent as Yu,isNonNullable as PR,isNullable as AR,Logger as kR,map as C,mapTo as Dg,merge as Pt,now as Ws,once as lt,Subject as F,Subscription as Bg,tap as Vg,ValueSubject as P,isHigher as wR,isInvariantQuality as Og,flattenObject as At,throttle as Qu,getTraceSubscriptionMethod as _g,Tracer as RR}from"@vkontakte/videoplayer-shared";import{merge as vR,map as yR,filter as Lg,isNonNullable as TR}from"@vkontakte/videoplayer-shared";var Wu=({seekState:i,position$:e})=>vR(i.stateChangeEnded$.pipe(yR(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),Lg(TR)),e.pipe(Lg(()=>i.getState().state==="none")));import{assertNonNullable as IR}from"@vkontakte/videoplayer-shared";var Mg=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return IR(e,`Wrong container or containerId {${i.container}}`),e};import{filter as ER,once as xR}from"@vkontakte/videoplayer-shared";var Cg=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(ER(a=>a.length>0),xR()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t?.getValue().find(r))&&e.startTransitionTo(i)};var Ys=class{constructor(e={configName:[]},t=RR.createRootTracer(!1)){this.subscription=new Bg;this.logger=new kR;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:dm};if(this.initLogs(),this.tuning=$g(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ea({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new kg(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:Gs.WTF,message:l,thrown:c}),c}}}})}initVideo(e){this.config=e;let{container:t,...r}=e;return this.tracer.log("initVideo",At(r)),this.domContainer=Mg(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new ha({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&&!Si()?(this.tracer.log("request play from hidden tab"),Yu(document,"visibilitychange").pipe(lt()).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){js(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(ie(r=>r.length>0),lt()).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",At(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){js(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",At(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return Cg(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(AR(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return PR(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(Pt(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(ie(({from:e})=>e==="stopped"),lt()).subscribe(()=>{this.initedAt=Ws(),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",At(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Gs.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",At(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)=>Og(o)?1:Og(c)?-1:wR(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(xt({hasLiveOffsetByPaused:Pt(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(xt({atLiveEdge:xt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Wu({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(),Vg(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(C(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(xt({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(),Vg(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(Wu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Pt(e.providerOutput.endedEvent$.pipe(Dg(!0)),e.providerOutput.seekedEvent$.pipe(Dg(!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:Gs.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(lt(),C(n=>n??Ws()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(lt(),C(()=>Ws()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(lt(),C(()=>Ws()-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(ie(({to:n})=>n==="playing"),lt()).subscribe(()=>r.next(!1)));let a=0,s=Pt(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(Pt(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(Pt(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 Bg;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(ie(r=>r.length>0),lt()).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=yt(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(Pt(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;js(this.providerContainer),js(e),lm(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>cm(t)),this.providerContainer.current$.subscribe(({type:t})=>pi("provider",t)),e.duration$.subscribe(t=>pi("duration",t)),e.availableVideoTracks$.pipe(ie(t=>!!t.length),lt()).subscribe(t=>pi("tracks",t)),this.events.fatalError$.subscribe(new re("fatalError")),this.events.managedError$.subscribe(new re("managedError")),e.position$.subscribe(new re("position")),e.currentVideoTrack$.pipe(C(t=>t?.quality)).subscribe(new re("quality")),this.info.currentBuffer$.subscribe(new re("buffer")),e.isBuffering$.subscribe(new re("isBuffering"))].forEach(t=>this.subscription.add(t)),pi("codecs",Nm())}initTracerSubscription(){let e=_g(this.tracer.log.bind(this.tracer)),t=_g(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(xt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(ie(({currentQuality:r,videoBitrate:a})=>!!r&&!!a),V((r,a)=>r.currentQuality===a.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(ie(r=>r>0),V()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(ie(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(xt({currentBuffer:this.info.currentBuffer$.pipe(ie(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(xt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(ie(({liveTime:r,liveBufferTime:a})=>!!r&&!!a),Qu(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(V(),ie(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(V(),ie(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(),ie(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(xt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(ie(({throughputEstimation:r,rtt:a})=>!!r&&!!a),Qu(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(V(),ie(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:Gs.DOM,message:String(a)})})};this.subscription.add(Pt(Yu(document,"visibilitychange"),Yu(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",At({quality:t,availableTracks:At(e),track:At(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 wj,Observable as Rj,Subject as $j,ValueSubject as Lj,VideoQuality as Mj}from"@vkontakte/videoplayer-shared";var Cj=`@vkontakte/videoplayer-core@${Ju}`;export{Ta as ChromecastState,zs as HttpConnectionType,Rj as Observable,se as PlaybackState,Ys as Player,Cj as SDK_VERSION,$j as Subject,wj as Subscription,Ks as Surface,Ju as VERSION,Lj as ValueSubject,ft as VideoFormat,Mj as VideoQuality};
|