@vkontakte/videoplayer-core 2.0.108-dev.3b4522e2.0 → 2.0.108-dev.3ff897f5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esnext.esm.js CHANGED
@@ -1,40 +1,61 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.108-dev.3b4522e2.0
3
- * Tue, 03 Sep 2024 10:04:28 GMT
2
+ * @vkontakte/videoplayer-core v2.0.108-dev.3ff897f5.0
3
+ * Wed, 04 Sep 2024 18:33:52 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-108/doc/
5
5
  */
6
- var kS=Object.create;var Vu=Object.defineProperty;var RS=Object.getOwnPropertyDescriptor;var LS=Object.getOwnPropertyNames;var $S=Object.getPrototypeOf,MS=Object.prototype.hasOwnProperty;var f=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var CS=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of LS(e))!MS.call(i,a)&&a!==t&&Vu(i,a,{get:()=>e[a],enumerable:!(r=RS(e,a))||r.enumerable});return i};var Oe=(i,e,t)=>(t=i!=null?kS($S(i)):{},CS(e||!i||!i.__esModule?Vu(t,"default",{value:i,enumerable:!0}):t,i));var de=f((LR,Gu)=>{"use strict";Gu.exports=function(i){try{return!!i()}catch{return!0}}});var xr=f(($R,Yu)=>{"use strict";var qS=de();Yu.exports=!qS(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var te=f((MR,zu)=>{"use strict";var Wu=xr(),Qu=Function.prototype,qs=Qu.call,US=Wu&&Qu.bind.bind(qs,qs);zu.exports=Wu?US:function(i){return function(){return qs.apply(i,arguments)}}});var Ht=f((CR,Ju)=>{"use strict";var Ku=te(),HS=Ku({}.toString),jS=Ku("".slice);Ju.exports=function(i){return jS(HS(i),8,-1)}});var Zu=f((DR,Xu)=>{"use strict";var GS=te(),YS=de(),WS=Ht(),Us=Object,QS=GS("".split);Xu.exports=YS(function(){return!Us("z").propertyIsEnumerable(0)})?function(i){return WS(i)==="String"?QS(i,""):Us(i)}:Us});var jt=f((BR,el)=>{"use strict";el.exports=function(i){return i==null}});var Pr=f((OR,tl)=>{"use strict";var zS=jt(),KS=TypeError;tl.exports=function(i){if(zS(i))throw new KS("Can't call method on "+i);return i}});var Gt=f((VR,rl)=>{"use strict";var JS=Zu(),XS=Pr();rl.exports=function(i){return JS(XS(i))}});var Hs=f((_R,il)=>{"use strict";il.exports=function(){}});var gt=f((NR,al)=>{"use strict";al.exports={}});var q=f((js,sl)=>{"use strict";var Ar=function(i){return i&&i.Math===Math&&i};sl.exports=Ar(typeof globalThis=="object"&&globalThis)||Ar(typeof window=="object"&&window)||Ar(typeof self=="object"&&self)||Ar(typeof global=="object"&&global)||Ar(typeof js=="object"&&js)||function(){return this}()||Function("return this")()});var F=f((FR,nl)=>{"use strict";var Gs=typeof document=="object"&&document.all;nl.exports=typeof Gs>"u"&&Gs!==void 0?function(i){return typeof i=="function"||i===Gs}:function(i){return typeof i=="function"}});var ll=f((qR,ul)=>{"use strict";var ZS=q(),eg=F(),ol=ZS.WeakMap;ul.exports=eg(ol)&&/native code/.test(String(ol))});var be=f((UR,cl)=>{"use strict";var tg=F();cl.exports=function(i){return typeof i=="object"?i!==null:tg(i)}});var Se=f((HR,dl)=>{"use strict";var rg=de();dl.exports=!rg(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var na=f((jR,hl)=>{"use strict";var ig=q(),pl=be(),Ys=ig.document,ag=pl(Ys)&&pl(Ys.createElement);hl.exports=function(i){return ag?Ys.createElement(i):{}}});var Ws=f((GR,fl)=>{"use strict";var sg=Se(),ng=de(),og=na();fl.exports=!sg&&!ng(function(){return Object.defineProperty(og("div"),"a",{get:function(){return 7}}).a!==7})});var Qs=f((YR,ml)=>{"use strict";var ug=Se(),lg=de();ml.exports=ug&&lg(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Ve=f((WR,bl)=>{"use strict";var cg=be(),dg=String,pg=TypeError;bl.exports=function(i){if(cg(i))return i;throw new pg(dg(i)+" is not an object")}});var pe=f((QR,Sl)=>{"use strict";var hg=xr(),oa=Function.prototype.call;Sl.exports=hg?oa.bind(oa):function(){return oa.apply(oa,arguments)}});var ua=f((zR,gl)=>{"use strict";gl.exports={}});var qe=f((KR,yl)=>{"use strict";var zs=ua(),Ks=q(),fg=F(),vl=function(i){return fg(i)?i:void 0};yl.exports=function(i,e){return arguments.length<2?vl(zs[i])||vl(Ks[i]):zs[i]&&zs[i][e]||Ks[i]&&Ks[i][e]}});var wr=f((JR,Tl)=>{"use strict";var mg=te();Tl.exports=mg({}.isPrototypeOf)});var Yt=f((XR,xl)=>{"use strict";var bg=q(),Il=bg.navigator,El=Il&&Il.userAgent;xl.exports=El?String(El):""});var Xs=f((ZR,Ll)=>{"use strict";var Rl=q(),Js=Yt(),Pl=Rl.process,Al=Rl.Deno,wl=Pl&&Pl.versions||Al&&Al.version,kl=wl&&wl.v8,ke,la;kl&&(ke=kl.split("."),la=ke[0]>0&&ke[0]<4?1:+(ke[0]+ke[1]));!la&&Js&&(ke=Js.match(/Edge\/(\d+)/),(!ke||ke[1]>=74)&&(ke=Js.match(/Chrome\/(\d+)/),ke&&(la=+ke[1])));Ll.exports=la});var Zs=f((eL,Ml)=>{"use strict";var $l=Xs(),Sg=de(),gg=q(),vg=gg.String;Ml.exports=!!Object.getOwnPropertySymbols&&!Sg(function(){var i=Symbol("symbol detection");return!vg(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&$l&&$l<41})});var en=f((tL,Cl)=>{"use strict";var yg=Zs();Cl.exports=yg&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var tn=f((rL,Dl)=>{"use strict";var Tg=qe(),Ig=F(),Eg=wr(),xg=en(),Pg=Object;Dl.exports=xg?function(i){return typeof i=="symbol"}:function(i){var e=Tg("Symbol");return Ig(e)&&Eg(e.prototype,Pg(i))}});var kr=f((iL,Bl)=>{"use strict";var Ag=String;Bl.exports=function(i){try{return Ag(i)}catch{return"Object"}}});var Ue=f((aL,Ol)=>{"use strict";var wg=F(),kg=kr(),Rg=TypeError;Ol.exports=function(i){if(wg(i))return i;throw new Rg(kg(i)+" is not a function")}});var Rr=f((sL,Vl)=>{"use strict";var Lg=Ue(),$g=jt();Vl.exports=function(i,e){var t=i[e];return $g(t)?void 0:Lg(t)}});var Nl=f((nL,_l)=>{"use strict";var rn=pe(),an=F(),sn=be(),Mg=TypeError;_l.exports=function(i,e){var t,r;if(e==="string"&&an(t=i.toString)&&!sn(r=rn(t,i))||an(t=i.valueOf)&&!sn(r=rn(t,i))||e!=="string"&&an(t=i.toString)&&!sn(r=rn(t,i)))return r;throw new Mg("Can't convert object to primitive value")}});var Re=f((oL,Fl)=>{"use strict";Fl.exports=!0});var Hl=f((uL,Ul)=>{"use strict";var ql=q(),Cg=Object.defineProperty;Ul.exports=function(i,e){try{Cg(ql,i,{value:e,configurable:!0,writable:!0})}catch{ql[i]=e}return e}});var Lr=f((lL,Yl)=>{"use strict";var Dg=Re(),Bg=q(),Og=Hl(),jl="__core-js_shared__",Gl=Yl.exports=Bg[jl]||Og(jl,{});(Gl.versions||(Gl.versions=[])).push({version:"3.38.0",mode:Dg?"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 nn=f((cL,Ql)=>{"use strict";var Wl=Lr();Ql.exports=function(i,e){return Wl[i]||(Wl[i]=e||{})}});var $r=f((dL,zl)=>{"use strict";var Vg=Pr(),_g=Object;zl.exports=function(i){return _g(Vg(i))}});var Le=f((pL,Kl)=>{"use strict";var Ng=te(),Fg=$r(),qg=Ng({}.hasOwnProperty);Kl.exports=Object.hasOwn||function(e,t){return qg(Fg(e),t)}});var on=f((hL,Jl)=>{"use strict";var Ug=te(),Hg=0,jg=Math.random(),Gg=Ug(1 .toString);Jl.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+Gg(++Hg+jg,36)}});var K=f((fL,Zl)=>{"use strict";var Yg=q(),Wg=nn(),Xl=Le(),Qg=on(),zg=Zs(),Kg=en(),Wt=Yg.Symbol,un=Wg("wks"),Jg=Kg?Wt.for||Wt:Wt&&Wt.withoutSetter||Qg;Zl.exports=function(i){return Xl(un,i)||(un[i]=zg&&Xl(Wt,i)?Wt[i]:Jg("Symbol."+i)),un[i]}});var ic=f((mL,rc)=>{"use strict";var Xg=pe(),ec=be(),tc=tn(),Zg=Rr(),ev=Nl(),tv=K(),rv=TypeError,iv=tv("toPrimitive");rc.exports=function(i,e){if(!ec(i)||tc(i))return i;var t=Zg(i,iv),r;if(t){if(e===void 0&&(e="default"),r=Xg(t,i,e),!ec(r)||tc(r))return r;throw new rv("Can't convert object to primitive value")}return e===void 0&&(e="number"),ev(i,e)}});var ln=f((bL,ac)=>{"use strict";var av=ic(),sv=tn();ac.exports=function(i){var e=av(i,"string");return sv(e)?e:e+""}});var vt=f(nc=>{"use strict";var nv=Se(),ov=Ws(),uv=Qs(),ca=Ve(),sc=ln(),lv=TypeError,cn=Object.defineProperty,cv=Object.getOwnPropertyDescriptor,dn="enumerable",pn="configurable",hn="writable";nc.f=nv?uv?function(e,t,r){if(ca(e),t=sc(t),ca(r),typeof e=="function"&&t==="prototype"&&"value"in r&&hn in r&&!r[hn]){var a=cv(e,t);a&&a[hn]&&(e[t]=r.value,r={configurable:pn in r?r[pn]:a[pn],enumerable:dn in r?r[dn]:a[dn],writable:!1})}return cn(e,t,r)}:cn:function(e,t,r){if(ca(e),t=sc(t),ca(r),ov)try{return cn(e,t,r)}catch{}if("get"in r||"set"in r)throw new lv("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Mr=f((gL,oc)=>{"use strict";oc.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var Qt=f((vL,uc)=>{"use strict";var dv=Se(),pv=vt(),hv=Mr();uc.exports=dv?function(i,e,t){return pv.f(i,e,hv(1,t))}:function(i,e,t){return i[e]=t,i}});var da=f((yL,cc)=>{"use strict";var fv=nn(),mv=on(),lc=fv("keys");cc.exports=function(i){return lc[i]||(lc[i]=mv(i))}});var pa=f((TL,dc)=>{"use strict";dc.exports={}});var Sn=f((IL,fc)=>{"use strict";var bv=ll(),hc=q(),Sv=be(),gv=Qt(),fn=Le(),mn=Lr(),vv=da(),yv=pa(),pc="Object already initialized",bn=hc.TypeError,Tv=hc.WeakMap,ha,Cr,fa,Iv=function(i){return fa(i)?Cr(i):ha(i,{})},Ev=function(i){return function(e){var t;if(!Sv(e)||(t=Cr(e)).type!==i)throw new bn("Incompatible receiver, "+i+" required");return t}};bv||mn.state?($e=mn.state||(mn.state=new Tv),$e.get=$e.get,$e.has=$e.has,$e.set=$e.set,ha=function(i,e){if($e.has(i))throw new bn(pc);return e.facade=i,$e.set(i,e),e},Cr=function(i){return $e.get(i)||{}},fa=function(i){return $e.has(i)}):(yt=vv("state"),yv[yt]=!0,ha=function(i,e){if(fn(i,yt))throw new bn(pc);return e.facade=i,gv(i,yt,e),e},Cr=function(i){return fn(i,yt)?i[yt]:{}},fa=function(i){return fn(i,yt)});var $e,yt;fc.exports={set:ha,get:Cr,has:fa,enforce:Iv,getterFor:Ev}});var gn=f((EL,gc)=>{"use strict";var xv=xr(),Sc=Function.prototype,mc=Sc.apply,bc=Sc.call;gc.exports=typeof Reflect=="object"&&Reflect.apply||(xv?bc.bind(mc):function(){return bc.apply(mc,arguments)})});var vn=f((xL,vc)=>{"use strict";var Pv=Ht(),Av=te();vc.exports=function(i){if(Pv(i)==="Function")return Av(i)}});var Ec=f(Ic=>{"use strict";var yc={}.propertyIsEnumerable,Tc=Object.getOwnPropertyDescriptor,wv=Tc&&!yc.call({1:2},1);Ic.f=wv?function(e){var t=Tc(this,e);return!!t&&t.enumerable}:yc});var Ac=f(Pc=>{"use strict";var kv=Se(),Rv=pe(),Lv=Ec(),$v=Mr(),Mv=Gt(),Cv=ln(),Dv=Le(),Bv=Ws(),xc=Object.getOwnPropertyDescriptor;Pc.f=kv?xc:function(e,t){if(e=Mv(e),t=Cv(t),Bv)try{return xc(e,t)}catch{}if(Dv(e,t))return $v(!Rv(Lv.f,e,t),e[t])}});var yn=f((wL,wc)=>{"use strict";var Ov=de(),Vv=F(),_v=/#|\.prototype\./,Dr=function(i,e){var t=Fv[Nv(i)];return t===Uv?!0:t===qv?!1:Vv(e)?Ov(e):!!e},Nv=Dr.normalize=function(i){return String(i).replace(_v,".").toLowerCase()},Fv=Dr.data={},qv=Dr.NATIVE="N",Uv=Dr.POLYFILL="P";wc.exports=Dr});var Br=f((kL,Rc)=>{"use strict";var kc=vn(),Hv=Ue(),jv=xr(),Gv=kc(kc.bind);Rc.exports=function(i,e){return Hv(i),e===void 0?i:jv?Gv(i,e):function(){return i.apply(e,arguments)}}});var ge=f((RL,$c)=>{"use strict";var Or=q(),Yv=gn(),Wv=vn(),Qv=F(),zv=Ac().f,Kv=yn(),zt=ua(),Jv=Br(),Kt=Qt(),Lc=Le();Lr();var Xv=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 Yv(i,this,arguments)};return e.prototype=i.prototype,e};$c.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?Or:a?Or[t]:Or[t]&&Or[t].prototype,o=r?zt:zt[t]||Kt(zt,t,{})[t],l=o.prototype,u,c,d,p,h,m,b,S,v;for(p in e)u=Kv(r?p:t+(a?".":"#")+p,i.forced),c=!u&&n&&Lc(n,p),m=o[p],c&&(i.dontCallGetSet?(v=zv(n,p),b=v&&v.value):b=n[p]),h=c&&b?b:e[p],!(!u&&!s&&typeof m==typeof h)&&(i.bind&&c?S=Jv(h,Or):i.wrap&&c?S=Xv(h):s&&Qv(h)?S=Wv(h):S=h,(i.sham||h&&h.sham||m&&m.sham)&&Kt(S,"sham",!0),Kt(o,p,S),s&&(d=t+"Prototype",Lc(zt,d)||Kt(zt,d,{}),Kt(zt[d],p,h),i.real&&l&&(u||!l[p])&&Kt(l,p,h)))}});var Dc=f((LL,Cc)=>{"use strict";var Tn=Se(),Zv=Le(),Mc=Function.prototype,ey=Tn&&Object.getOwnPropertyDescriptor,In=Zv(Mc,"name"),ty=In&&function(){}.name==="something",ry=In&&(!Tn||Tn&&ey(Mc,"name").configurable);Cc.exports={EXISTS:In,PROPER:ty,CONFIGURABLE:ry}});var Oc=f(($L,Bc)=>{"use strict";var iy=Math.ceil,ay=Math.floor;Bc.exports=Math.trunc||function(e){var t=+e;return(t>0?ay:iy)(t)}});var ma=f((ML,Vc)=>{"use strict";var sy=Oc();Vc.exports=function(i){var e=+i;return e!==e||e===0?0:sy(e)}});var Nc=f((CL,_c)=>{"use strict";var ny=ma(),oy=Math.max,uy=Math.min;_c.exports=function(i,e){var t=ny(i);return t<0?oy(t+e,0):uy(t,e)}});var qc=f((DL,Fc)=>{"use strict";var ly=ma(),cy=Math.min;Fc.exports=function(i){var e=ly(i);return e>0?cy(e,9007199254740991):0}});var ba=f((BL,Uc)=>{"use strict";var dy=qc();Uc.exports=function(i){return dy(i.length)}});var Gc=f((OL,jc)=>{"use strict";var py=Gt(),hy=Nc(),fy=ba(),Hc=function(i){return function(e,t,r){var a=py(e),s=fy(a);if(s===0)return!i&&-1;var n=hy(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}};jc.exports={includes:Hc(!0),indexOf:Hc(!1)}});var Qc=f((VL,Wc)=>{"use strict";var my=te(),En=Le(),by=Gt(),Sy=Gc().indexOf,gy=pa(),Yc=my([].push);Wc.exports=function(i,e){var t=by(i),r=0,a=[],s;for(s in t)!En(gy,s)&&En(t,s)&&Yc(a,s);for(;e.length>r;)En(t,s=e[r++])&&(~Sy(a,s)||Yc(a,s));return a}});var xn=f((_L,zc)=>{"use strict";zc.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Jc=f((NL,Kc)=>{"use strict";var vy=Qc(),yy=xn();Kc.exports=Object.keys||function(e){return vy(e,yy)}});var Zc=f(Xc=>{"use strict";var Ty=Se(),Iy=Qs(),Ey=vt(),xy=Ve(),Py=Gt(),Ay=Jc();Xc.f=Ty&&!Iy?Object.defineProperties:function(e,t){xy(e);for(var r=Py(t),a=Ay(t),s=a.length,n=0,o;s>n;)Ey.f(e,o=a[n++],r[o]);return e}});var Pn=f((qL,ed)=>{"use strict";var wy=qe();ed.exports=wy("document","documentElement")});var Rn=f((UL,od)=>{"use strict";var ky=Ve(),Ry=Zc(),td=xn(),Ly=pa(),$y=Pn(),My=na(),Cy=da(),rd=">",id="<",wn="prototype",kn="script",sd=Cy("IE_PROTO"),An=function(){},nd=function(i){return id+kn+rd+i+id+"/"+kn+rd},ad=function(i){i.write(nd("")),i.close();var e=i.parentWindow.Object;return i=null,e},Dy=function(){var i=My("iframe"),e="java"+kn+":",t;return i.style.display="none",$y.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(nd("document.F=Object")),t.close(),t.F},Sa,ga=function(){try{Sa=new ActiveXObject("htmlfile")}catch{}ga=typeof document<"u"?document.domain&&Sa?ad(Sa):Dy():ad(Sa);for(var i=td.length;i--;)delete ga[wn][td[i]];return ga()};Ly[sd]=!0;od.exports=Object.create||function(e,t){var r;return e!==null?(An[wn]=ky(e),r=new An,An[wn]=null,r[sd]=e):r=ga(),t===void 0?r:Ry.f(r,t)}});var ld=f((HL,ud)=>{"use strict";var By=de();ud.exports=!By(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var $n=f((jL,dd)=>{"use strict";var Oy=Le(),Vy=F(),_y=$r(),Ny=da(),Fy=ld(),cd=Ny("IE_PROTO"),Ln=Object,qy=Ln.prototype;dd.exports=Fy?Ln.getPrototypeOf:function(i){var e=_y(i);if(Oy(e,cd))return e[cd];var t=e.constructor;return Vy(t)&&e instanceof t?t.prototype:e instanceof Ln?qy:null}});var Jt=f((GL,pd)=>{"use strict";var Uy=Qt();pd.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:Uy(i,e,t),i}});var Bn=f((YL,md)=>{"use strict";var Hy=de(),jy=F(),Gy=be(),Yy=Rn(),hd=$n(),Wy=Jt(),Qy=K(),zy=Re(),Dn=Qy("iterator"),fd=!1,He,Mn,Cn;[].keys&&(Cn=[].keys(),"next"in Cn?(Mn=hd(hd(Cn)),Mn!==Object.prototype&&(He=Mn)):fd=!0);var Ky=!Gy(He)||Hy(function(){var i={};return He[Dn].call(i)!==i});Ky?He={}:zy&&(He=Yy(He));jy(He[Dn])||Wy(He,Dn,function(){return this});md.exports={IteratorPrototype:He,BUGGY_SAFARI_ITERATORS:fd}});var va=f((WL,Sd)=>{"use strict";var Jy=K(),Xy=Jy("toStringTag"),bd={};bd[Xy]="z";Sd.exports=String(bd)==="[object z]"});var Vr=f((QL,gd)=>{"use strict";var Zy=va(),eT=F(),ya=Ht(),tT=K(),rT=tT("toStringTag"),iT=Object,aT=ya(function(){return arguments}())==="Arguments",sT=function(i,e){try{return i[e]}catch{}};gd.exports=Zy?ya:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=sT(e=iT(i),rT))=="string"?t:aT?ya(e):(r=ya(e))==="Object"&&eT(e.callee)?"Arguments":r}});var yd=f((zL,vd)=>{"use strict";var nT=va(),oT=Vr();vd.exports=nT?{}.toString:function(){return"[object "+oT(this)+"]"}});var _r=f((KL,Id)=>{"use strict";var uT=va(),lT=vt().f,cT=Qt(),dT=Le(),pT=yd(),hT=K(),Td=hT("toStringTag");Id.exports=function(i,e,t,r){var a=t?i:i&&i.prototype;a&&(dT(a,Td)||lT(a,Td,{configurable:!0,value:e}),r&&!uT&&cT(a,"toString",pT))}});var xd=f((JL,Ed)=>{"use strict";var fT=Bn().IteratorPrototype,mT=Rn(),bT=Mr(),ST=_r(),gT=gt(),vT=function(){return this};Ed.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=mT(fT,{next:bT(+!r,t)}),ST(i,a,!1,!0),gT[a]=vT,i}});var Ad=f((XL,Pd)=>{"use strict";var yT=te(),TT=Ue();Pd.exports=function(i,e,t){try{return yT(TT(Object.getOwnPropertyDescriptor(i,e)[t]))}catch{}}});var kd=f((ZL,wd)=>{"use strict";var IT=be();wd.exports=function(i){return IT(i)||i===null}});var Ld=f((e$,Rd)=>{"use strict";var ET=kd(),xT=String,PT=TypeError;Rd.exports=function(i){if(ET(i))return i;throw new PT("Can't set "+xT(i)+" as a prototype")}});var On=f((t$,$d)=>{"use strict";var AT=Ad(),wT=be(),kT=Pr(),RT=Ld();$d.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=AT(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch{}return function(a,s){return kT(a),RT(s),wT(a)&&(i?t(a,s):a.__proto__=s),a}}():void 0)});var Ud=f((r$,qd)=>{"use strict";var LT=ge(),$T=pe(),Ta=Re(),Nd=Dc(),MT=F(),CT=xd(),Md=$n(),Cd=On(),DT=_r(),BT=Qt(),Vn=Jt(),OT=K(),Dd=gt(),Fd=Bn(),VT=Nd.PROPER,_T=Nd.CONFIGURABLE,Bd=Fd.IteratorPrototype,Ia=Fd.BUGGY_SAFARI_ITERATORS,Nr=OT("iterator"),Od="keys",Fr="values",Vd="entries",_d=function(){return this};qd.exports=function(i,e,t,r,a,s,n){CT(t,e,r);var o=function(v){if(v===a&&p)return p;if(!Ia&&v&&v in c)return c[v];switch(v){case Od:return function(){return new t(this,v)};case Fr:return function(){return new t(this,v)};case Vd:return function(){return new t(this,v)}}return function(){return new t(this)}},l=e+" Iterator",u=!1,c=i.prototype,d=c[Nr]||c["@@iterator"]||a&&c[a],p=!Ia&&d||o(a),h=e==="Array"&&c.entries||d,m,b,S;if(h&&(m=Md(h.call(new i)),m!==Object.prototype&&m.next&&(!Ta&&Md(m)!==Bd&&(Cd?Cd(m,Bd):MT(m[Nr])||Vn(m,Nr,_d)),DT(m,l,!0,!0),Ta&&(Dd[l]=_d))),VT&&a===Fr&&d&&d.name!==Fr&&(!Ta&&_T?BT(c,"name",Fr):(u=!0,p=function(){return $T(d,this)})),a)if(b={values:o(Fr),keys:s?p:o(Od),entries:o(Vd)},n)for(S in b)(Ia||u||!(S in c))&&Vn(c,S,b[S]);else LT({target:e,proto:!0,forced:Ia||u},b);return(!Ta||n)&&c[Nr]!==p&&Vn(c,Nr,p,{name:a}),Dd[e]=p,b}});var jd=f((i$,Hd)=>{"use strict";Hd.exports=function(i,e){return{value:i,done:e}}});var Nn=f((a$,zd)=>{"use strict";var NT=Gt(),_n=Hs(),Gd=gt(),Wd=Sn(),FT=vt().f,qT=Ud(),Ea=jd(),UT=Re(),HT=Se(),Qd="Array Iterator",jT=Wd.set,GT=Wd.getterFor(Qd);zd.exports=qT(Array,"Array",function(i,e){jT(this,{type:Qd,target:NT(i),index:0,kind:e})},function(){var i=GT(this),e=i.target,t=i.index++;if(!e||t>=e.length)return i.target=void 0,Ea(void 0,!0);switch(i.kind){case"keys":return Ea(t,!1);case"values":return Ea(e[t],!1)}return Ea([t,e[t]],!1)},"values");var Yd=Gd.Arguments=Gd.Array;_n("keys");_n("values");_n("entries");if(!UT&&HT&&Yd.name!=="values")try{FT(Yd,"name",{value:"values"})}catch{}});var Jd=f((s$,Kd)=>{"use strict";var YT=K(),WT=gt(),QT=YT("iterator"),zT=Array.prototype;Kd.exports=function(i){return i!==void 0&&(WT.Array===i||zT[QT]===i)}});var Fn=f((n$,Zd)=>{"use strict";var KT=Vr(),Xd=Rr(),JT=jt(),XT=gt(),ZT=K(),eI=ZT("iterator");Zd.exports=function(i){if(!JT(i))return Xd(i,eI)||Xd(i,"@@iterator")||XT[KT(i)]}});var tp=f((o$,ep)=>{"use strict";var tI=pe(),rI=Ue(),iI=Ve(),aI=kr(),sI=Fn(),nI=TypeError;ep.exports=function(i,e){var t=arguments.length<2?sI(i):e;if(rI(t))return iI(tI(t,i));throw new nI(aI(i)+" is not iterable")}});var ap=f((u$,ip)=>{"use strict";var oI=pe(),rp=Ve(),uI=Rr();ip.exports=function(i,e,t){var r,a;rp(i);try{if(r=uI(i,"return"),!r){if(e==="throw")throw t;return t}r=oI(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return rp(r),t}});var Pa=f((l$,up)=>{"use strict";var lI=Br(),cI=pe(),dI=Ve(),pI=kr(),hI=Jd(),fI=ba(),sp=wr(),mI=tp(),bI=Fn(),np=ap(),SI=TypeError,xa=function(i,e){this.stopped=i,this.result=e},op=xa.prototype;up.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=lI(e,r),u,c,d,p,h,m,b,S=function(w){return u&&np(u,"normal",w),new xa(!0,w)},v=function(w){return a?(dI(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(c=bI(i),!c)throw new SI(pI(i)+" is not iterable");if(hI(c)){for(d=0,p=fI(i);p>d;d++)if(h=v(i[d]),h&&sp(op,h))return h;return new xa(!1)}u=mI(i,c)}for(m=s?i.next:u.next;!(b=cI(m,u)).done;){try{h=v(b.value)}catch(w){np(u,"throw",w)}if(typeof h=="object"&&h&&sp(op,h))return h}return new xa(!1)}});var cp=f((c$,lp)=>{"use strict";var gI=Se(),vI=vt(),yI=Mr();lp.exports=function(i,e,t){gI?vI.f(i,e,yI(0,t)):i[e]=t}});var dp=f(()=>{"use strict";var TI=ge(),II=Pa(),EI=cp();TI({target:"Object",stat:!0},{fromEntries:function(e){var t={};return II(e,function(r,a){EI(t,r,a)},{AS_ENTRIES:!0}),t}})});var hp=f((h$,pp)=>{"use strict";Nn();dp();var xI=ua();pp.exports=xI.Object.fromEntries});var mp=f((f$,fp)=>{"use strict";fp.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 Sp=f(()=>{"use strict";Nn();var PI=mp(),AI=q(),wI=_r(),bp=gt();for(Aa in PI)wI(AI[Aa],Aa),bp[Aa]=bp.Array;var Aa});var vp=f((S$,gp)=>{"use strict";var kI=hp();Sp();gp.exports=kI});var qn=f((g$,yp)=>{"use strict";var RI=vp();yp.exports=RI});var Tp=f(()=>{"use strict"});var Un=f((T$,Ip)=>{"use strict";var qr=q(),LI=Yt(),$I=Ht(),wa=function(i){return LI.slice(0,i.length)===i};Ip.exports=function(){return wa("Bun/")?"BUN":wa("Cloudflare-Workers")?"CLOUDFLARE":wa("Deno/")?"DENO":wa("Node.js/")?"NODE":qr.Bun&&typeof Bun.version=="string"?"BUN":qr.Deno&&typeof Deno.version=="object"?"DENO":$I(qr.process)==="process"?"NODE":qr.window&&qr.document?"BROWSER":"REST"}()});var ka=f((I$,Ep)=>{"use strict";var MI=Un();Ep.exports=MI==="NODE"});var Pp=f((E$,xp)=>{"use strict";var CI=vt();xp.exports=function(i,e,t){return CI.f(i,e,t)}});var kp=f((x$,wp)=>{"use strict";var DI=qe(),BI=Pp(),OI=K(),VI=Se(),Ap=OI("species");wp.exports=function(i){var e=DI(i);VI&&e&&!e[Ap]&&BI(e,Ap,{configurable:!0,get:function(){return this}})}});var Lp=f((P$,Rp)=>{"use strict";var _I=wr(),NI=TypeError;Rp.exports=function(i,e){if(_I(e,i))return i;throw new NI("Incorrect invocation")}});var jn=f((A$,$p)=>{"use strict";var FI=te(),qI=F(),Hn=Lr(),UI=FI(Function.toString);qI(Hn.inspectSource)||(Hn.inspectSource=function(i){return UI(i)});$p.exports=Hn.inspectSource});var Vp=f((w$,Op)=>{"use strict";var HI=te(),jI=de(),Mp=F(),GI=Vr(),YI=qe(),WI=jn(),Cp=function(){},Dp=YI("Reflect","construct"),Gn=/^\s*(?:class|function)\b/,QI=HI(Gn.exec),zI=!Gn.test(Cp),Ur=function(e){if(!Mp(e))return!1;try{return Dp(Cp,[],e),!0}catch{return!1}},Bp=function(e){if(!Mp(e))return!1;switch(GI(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return zI||!!QI(Gn,WI(e))}catch{return!0}};Bp.sham=!0;Op.exports=!Dp||jI(function(){var i;return Ur(Ur.call)||!Ur(Object)||!Ur(function(){i=!0})||i})?Bp:Ur});var Np=f((k$,_p)=>{"use strict";var KI=Vp(),JI=kr(),XI=TypeError;_p.exports=function(i){if(KI(i))return i;throw new XI(JI(i)+" is not a constructor")}});var Yn=f((R$,qp)=>{"use strict";var Fp=Ve(),ZI=Np(),eE=jt(),tE=K(),rE=tE("species");qp.exports=function(i,e){var t=Fp(i).constructor,r;return t===void 0||eE(r=Fp(t)[rE])?e:ZI(r)}});var Hp=f((L$,Up)=>{"use strict";var iE=te();Up.exports=iE([].slice)});var Gp=f(($$,jp)=>{"use strict";var aE=TypeError;jp.exports=function(i,e){if(i<e)throw new aE("Not enough arguments");return i}});var Wn=f((M$,Yp)=>{"use strict";var sE=Yt();Yp.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(sE)});var ro=f((C$,th)=>{"use strict";var he=q(),nE=gn(),oE=Br(),Wp=F(),uE=Le(),eh=de(),Qp=Pn(),lE=Hp(),zp=na(),cE=Gp(),dE=Wn(),pE=ka(),Zn=he.setImmediate,eo=he.clearImmediate,hE=he.process,Qn=he.Dispatch,fE=he.Function,Kp=he.MessageChannel,mE=he.String,zn=0,Hr={},Jp="onreadystatechange",jr,Tt,Kn,Jn;eh(function(){jr=he.location});var to=function(i){if(uE(Hr,i)){var e=Hr[i];delete Hr[i],e()}},Xn=function(i){return function(){to(i)}},Xp=function(i){to(i.data)},Zp=function(i){he.postMessage(mE(i),jr.protocol+"//"+jr.host)};(!Zn||!eo)&&(Zn=function(e){cE(arguments.length,1);var t=Wp(e)?e:fE(e),r=lE(arguments,1);return Hr[++zn]=function(){nE(t,void 0,r)},Tt(zn),zn},eo=function(e){delete Hr[e]},pE?Tt=function(i){hE.nextTick(Xn(i))}:Qn&&Qn.now?Tt=function(i){Qn.now(Xn(i))}:Kp&&!dE?(Kn=new Kp,Jn=Kn.port2,Kn.port1.onmessage=Xp,Tt=oE(Jn.postMessage,Jn)):he.addEventListener&&Wp(he.postMessage)&&!he.importScripts&&jr&&jr.protocol!=="file:"&&!eh(Zp)?(Tt=Zp,he.addEventListener("message",Xp,!1)):Jp in zp("script")?Tt=function(i){Qp.appendChild(zp("script"))[Jp]=function(){Qp.removeChild(this),to(i)}}:Tt=function(i){setTimeout(Xn(i),0)});th.exports={set:Zn,clear:eo}});var ah=f((D$,ih)=>{"use strict";var rh=q(),bE=Se(),SE=Object.getOwnPropertyDescriptor;ih.exports=function(i){if(!bE)return rh[i];var e=SE(rh,i);return e&&e.value}});var io=f((B$,nh)=>{"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}}};nh.exports=sh});var uh=f((O$,oh)=>{"use strict";var gE=Yt();oh.exports=/ipad|iphone|ipod/i.test(gE)&&typeof Pebble<"u"});var ch=f((V$,lh)=>{"use strict";var vE=Yt();lh.exports=/web0s(?!.*chrome)/i.test(vE)});var Sh=f((_$,bh)=>{"use strict";var Zt=q(),yE=ah(),dh=Br(),ao=ro().set,TE=io(),IE=Wn(),EE=uh(),xE=ch(),so=ka(),ph=Zt.MutationObserver||Zt.WebKitMutationObserver,hh=Zt.document,fh=Zt.process,Ra=Zt.Promise,uo=yE("queueMicrotask"),Xt,no,oo,La,mh;uo||(Gr=new TE,Yr=function(){var i,e;for(so&&(i=fh.domain)&&i.exit();e=Gr.get();)try{e()}catch(t){throw Gr.head&&Xt(),t}i&&i.enter()},!IE&&!so&&!xE&&ph&&hh?(no=!0,oo=hh.createTextNode(""),new ph(Yr).observe(oo,{characterData:!0}),Xt=function(){oo.data=no=!no}):!EE&&Ra&&Ra.resolve?(La=Ra.resolve(void 0),La.constructor=Ra,mh=dh(La.then,La),Xt=function(){mh(Yr)}):so?Xt=function(){fh.nextTick(Yr)}:(ao=dh(ao,Zt),Xt=function(){ao(Yr)}),uo=function(i){Gr.head||Xt(),Gr.add(i)});var Gr,Yr;bh.exports=uo});var vh=f((N$,gh)=>{"use strict";gh.exports=function(i,e){try{arguments.length===1?console.error(i):console.error(i,e)}catch{}}});var $a=f((F$,yh)=>{"use strict";yh.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var It=f((q$,Th)=>{"use strict";var PE=q();Th.exports=PE.Promise});var er=f((U$,Ph)=>{"use strict";var AE=q(),Wr=It(),wE=F(),kE=yn(),RE=jn(),LE=K(),Ih=Un(),$E=Re(),lo=Xs(),Eh=Wr&&Wr.prototype,ME=LE("species"),co=!1,xh=wE(AE.PromiseRejectionEvent),CE=kE("Promise",function(){var i=RE(Wr),e=i!==String(Wr);if(!e&&lo===66||$E&&!(Eh.catch&&Eh.finally))return!0;if(!lo||lo<51||!/native code/.test(i)){var t=new Wr(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[ME]=r,co=t.then(function(){})instanceof r,!co)return!0}return!e&&(Ih==="BROWSER"||Ih==="DENO")&&!xh});Ph.exports={CONSTRUCTOR:CE,REJECTION_EVENT:xh,SUBCLASSING:co}});var tr=f((H$,wh)=>{"use strict";var Ah=Ue(),DE=TypeError,BE=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw new DE("Bad Promise constructor");e=r,t=a}),this.resolve=Ah(e),this.reject=Ah(t)};wh.exports.f=function(i){return new BE(i)}});var Yh=f(()=>{"use strict";var OE=ge(),VE=Re(),Ba=ka(),rt=q(),sr=pe(),kh=Jt(),Rh=On(),_E=_r(),NE=kp(),FE=Ue(),Da=F(),qE=be(),UE=Lp(),HE=Yn(),Dh=ro().set,bo=Sh(),jE=vh(),GE=$a(),YE=io(),Bh=Sn(),Oa=It(),So=er(),Oh=tr(),Va="Promise",Vh=So.CONSTRUCTOR,WE=So.REJECTION_EVENT,QE=So.SUBCLASSING,po=Bh.getterFor(Va),zE=Bh.set,rr=Oa&&Oa.prototype,Et=Oa,Ma=rr,_h=rt.TypeError,ho=rt.document,go=rt.process,fo=Oh.f,KE=fo,JE=!!(ho&&ho.createEvent&&rt.dispatchEvent),Nh="unhandledrejection",XE="rejectionhandled",Lh=0,Fh=1,ZE=2,vo=1,qh=2,Ca,$h,ex,Mh,Uh=function(i){var e;return qE(i)&&Da(e=i.then)?e:!1},Hh=function(i,e){var t=e.value,r=e.state===Fh,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,l,u,c;try{a?(r||(e.rejection===qh&&rx(e),e.rejection=vo),a===!0?l=t:(o&&o.enter(),l=a(t),o&&(o.exit(),c=!0)),l===i.promise?n(new _h("Promise-chain cycle")):(u=Uh(l))?sr(u,l,s,n):s(l)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},jh=function(i,e){i.notified||(i.notified=!0,bo(function(){for(var t=i.reactions,r;r=t.get();)Hh(r,i);i.notified=!1,e&&!i.rejection&&tx(i)}))},Gh=function(i,e,t){var r,a;JE?(r=ho.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),rt.dispatchEvent(r)):r={promise:e,reason:t},!WE&&(a=rt["on"+i])?a(r):i===Nh&&jE("Unhandled promise rejection",t)},tx=function(i){sr(Dh,rt,function(){var e=i.facade,t=i.value,r=Ch(i),a;if(r&&(a=GE(function(){Ba?go.emit("unhandledRejection",t,e):Gh(Nh,e,t)}),i.rejection=Ba||Ch(i)?qh:vo,a.error))throw a.value})},Ch=function(i){return i.rejection!==vo&&!i.parent},rx=function(i){sr(Dh,rt,function(){var e=i.facade;Ba?go.emit("rejectionHandled",e):Gh(XE,e,i.value)})},ir=function(i,e,t){return function(r){i(e,r,t)}},ar=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=ZE,jh(i,!0))},mo=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw new _h("Promise can't be resolved itself");var r=Uh(e);r?bo(function(){var a={done:!1};try{sr(r,e,ir(mo,a,i),ir(ar,a,i))}catch(s){ar(a,s,i)}}):(i.value=e,i.state=Fh,jh(i,!1))}catch(a){ar({done:!1},a,i)}}};if(Vh&&(Et=function(e){UE(this,Ma),FE(e),sr(Ca,this);var t=po(this);try{e(ir(mo,t),ir(ar,t))}catch(r){ar(t,r)}},Ma=Et.prototype,Ca=function(e){zE(this,{type:Va,done:!1,notified:!1,parent:!1,reactions:new YE,rejection:!1,state:Lh,value:void 0})},Ca.prototype=kh(Ma,"then",function(e,t){var r=po(this),a=fo(HE(this,Et));return r.parent=!0,a.ok=Da(e)?e:!0,a.fail=Da(t)&&t,a.domain=Ba?go.domain:void 0,r.state===Lh?r.reactions.add(a):bo(function(){Hh(a,r)}),a.promise}),$h=function(){var i=new Ca,e=po(i);this.promise=i,this.resolve=ir(mo,e),this.reject=ir(ar,e)},Oh.f=fo=function(i){return i===Et||i===ex?new $h(i):KE(i)},!VE&&Da(Oa)&&rr!==Object.prototype)){Mh=rr.then,QE||kh(rr,"then",function(e,t){var r=this;return new Et(function(a,s){sr(Mh,r,a,s)}).then(e,t)},{unsafe:!0});try{delete rr.constructor}catch{}Rh&&Rh(rr,Ma)}OE({global:!0,constructor:!0,wrap:!0,forced:Vh},{Promise:Et});_E(Et,Va,!1,!0);NE(Va)});var Jh=f((Y$,Kh)=>{"use strict";var ix=K(),Qh=ix("iterator"),zh=!1;try{Wh=0,yo={next:function(){return{done:!!Wh++}},return:function(){zh=!0}},yo[Qh]=function(){return this},Array.from(yo,function(){throw 2})}catch{}var Wh,yo;Kh.exports=function(i,e){try{if(!e&&!zh)return!1}catch{return!1}var t=!1;try{var r={};r[Qh]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch{}return t}});var To=f((W$,Xh)=>{"use strict";var ax=It(),sx=Jh(),nx=er().CONSTRUCTOR;Xh.exports=nx||!sx(function(i){ax.all(i).then(void 0,function(){})})});var Zh=f(()=>{"use strict";var ox=ge(),ux=pe(),lx=Ue(),cx=tr(),dx=$a(),px=Pa(),hx=To();ox({target:"Promise",stat:!0,forced:hx},{all:function(e){var t=this,r=cx.f(t),a=r.resolve,s=r.reject,n=dx(function(){var o=lx(t.resolve),l=[],u=0,c=1;px(e,function(d){var p=u++,h=!1;c++,ux(o,t,d).then(function(m){h||(h=!0,l[p]=m,--c||a(l))},s)}),--c||a(l)});return n.error&&s(n.value),r.promise}})});var tf=f(()=>{"use strict";var fx=ge(),mx=Re(),bx=er().CONSTRUCTOR,Eo=It(),Sx=qe(),gx=F(),vx=Jt(),ef=Eo&&Eo.prototype;fx({target:"Promise",proto:!0,forced:bx,real:!0},{catch:function(i){return this.then(void 0,i)}});!mx&&gx(Eo)&&(Io=Sx("Promise").prototype.catch,ef.catch!==Io&&vx(ef,"catch",Io,{unsafe:!0}));var Io});var rf=f(()=>{"use strict";var yx=ge(),Tx=pe(),Ix=Ue(),Ex=tr(),xx=$a(),Px=Pa(),Ax=To();yx({target:"Promise",stat:!0,forced:Ax},{race:function(e){var t=this,r=Ex.f(t),a=r.reject,s=xx(function(){var n=Ix(t.resolve);Px(e,function(o){Tx(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var af=f(()=>{"use strict";var wx=ge(),kx=tr(),Rx=er().CONSTRUCTOR;wx({target:"Promise",stat:!0,forced:Rx},{reject:function(e){var t=kx.f(this),r=t.reject;return r(e),t.promise}})});var xo=f((rM,sf)=>{"use strict";var Lx=Ve(),$x=be(),Mx=tr();sf.exports=function(i,e){if(Lx(i),$x(e)&&e.constructor===i)return e;var t=Mx.f(i),r=t.resolve;return r(e),t.promise}});var uf=f(()=>{"use strict";var Cx=ge(),Dx=qe(),nf=Re(),Bx=It(),of=er().CONSTRUCTOR,Ox=xo(),Vx=Dx("Promise"),_x=nf&&!of;Cx({target:"Promise",stat:!0,forced:nf||of},{resolve:function(e){return Ox(_x&&this===Vx?Bx:this,e)}})});var lf=f(()=>{"use strict";Yh();Zh();tf();rf();af();uf()});var hf=f(()=>{"use strict";var Nx=ge(),Fx=Re(),_a=It(),qx=de(),df=qe(),pf=F(),Ux=Yn(),cf=xo(),Hx=Jt(),Ao=_a&&_a.prototype,jx=!!_a&&qx(function(){Ao.finally.call({then:function(){}},function(){})});Nx({target:"Promise",proto:!0,real:!0,forced:jx},{finally:function(i){var e=Ux(this,df("Promise")),t=pf(i);return this.then(t?function(r){return cf(e,i()).then(function(){return r})}:i,t?function(r){return cf(e,i()).then(function(){throw r})}:i)}});!Fx&&pf(_a)&&(Po=df("Promise").prototype.finally,Ao.finally!==Po&&Hx(Ao,"finally",Po,{unsafe:!0}));var Po});var Na=f((lM,ff)=>{"use strict";var Gx=qe();ff.exports=Gx});var bf=f((cM,mf)=>{"use strict";Tp();lf();hf();var Yx=Na();mf.exports=Yx("Promise","finally")});var gf=f((dM,Sf)=>{"use strict";var Wx=bf();Sf.exports=Wx});var Fa=f((pM,vf)=>{"use strict";var Qx=gf();vf.exports=Qx});var jf=f(()=>{"use strict";var EP=ge(),xP=$r(),PP=ba(),AP=ma(),wP=Hs();EP({target:"Array",proto:!0},{at:function(e){var t=xP(this),r=PP(t),a=AP(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});wP("at")});var Yf=f((TC,Gf)=>{"use strict";jf();var kP=Na();Gf.exports=kP("Array","at")});var Qf=f((IC,Wf)=>{"use strict";var RP=Yf();Wf.exports=RP});var Jr=f((EC,zf)=>{"use strict";var LP=Qf();zf.exports=LP});var Vm=f(()=>{"use strict"});var _m=f(()=>{"use strict"});var Fm=f((EO,Nm)=>{"use strict";var FA=be(),qA=Ht(),UA=K(),HA=UA("match");Nm.exports=function(i){var e;return FA(i)&&((e=i[HA])!==void 0?!!e:qA(i)==="RegExp")}});var Um=f((xO,qm)=>{"use strict";var jA=Vr(),GA=String;qm.exports=function(i){if(jA(i)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return GA(i)}});var jm=f((PO,Hm)=>{"use strict";var YA=Ve();Hm.exports=function(){var i=YA(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 Wm=f((AO,Ym)=>{"use strict";var WA=pe(),QA=Le(),zA=wr(),KA=jm(),Gm=RegExp.prototype;Ym.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in Gm)&&!QA(i,"flags")&&zA(Gm,i)?WA(KA,i):e}});var zm=f((wO,Qm)=>{"use strict";var ru=te(),JA=$r(),XA=Math.floor,eu=ru("".charAt),ZA=ru("".replace),tu=ru("".slice),ew=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,tw=/\$([$&'`]|\d{1,2})/g;Qm.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,l=tw;return a!==void 0&&(a=JA(a),l=ew),ZA(s,l,function(u,c){var d;switch(eu(c,0)){case"$":return"$";case"&":return i;case"`":return tu(e,0,t);case"'":return tu(e,n);case"<":d=a[tu(c,1,-1)];break;default:var p=+c;if(p===0)return u;if(p>o){var h=XA(p/10);return h===0?u:h<=o?r[h-1]===void 0?eu(c,1):r[h-1]+eu(c,1):u}d=r[p-1]}return d===void 0?"":d})}});var Xm=f(()=>{"use strict";var rw=ge(),iw=pe(),au=te(),Km=Pr(),aw=F(),sw=jt(),nw=Fm(),mr=Um(),ow=Rr(),uw=Wm(),lw=zm(),cw=K(),dw=Re(),pw=cw("replace"),hw=TypeError,iu=au("".indexOf),fw=au("".replace),Jm=au("".slice),mw=Math.max;rw({target:"String",proto:!0},{replaceAll:function(e,t){var r=Km(this),a,s,n,o,l,u,c,d,p,h,m=0,b="";if(!sw(e)){if(a=nw(e),a&&(s=mr(Km(uw(e))),!~iu(s,"g")))throw new hw("`.replaceAll` does not allow non-global regexes");if(n=ow(e,pw),n)return iw(n,e,r,t);if(dw&&a)return fw(mr(r),e,t)}for(o=mr(r),l=mr(e),u=aw(t),u||(t=mr(t)),c=l.length,d=mw(1,c),p=iu(o,l);p!==-1;)h=u?mr(t(l,p,o)):lw(l,o,p,[],void 0,t),b+=Jm(o,m,p)+h,m=p+c,p=p+d>o.length?-1:iu(o,l,p+d);return m<o.length&&(b+=Jm(o,m)),b}})});var eb=f((LO,Zm)=>{"use strict";Vm();_m();Xm();var bw=Na();Zm.exports=bw("String","replaceAll")});var rb=f(($O,tb)=>{"use strict";var Sw=eb();tb.exports=Sw});var ab=f((MO,ib)=>{"use strict";var gw=rb();ib.exports=gw});var _u="2.0.108-dev.3b4522e2.0";var ee=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(ee||{}),tt=(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))(tt||{});var ia=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(ia||{}),Vs=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Vs||{});var _s=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(_s||{});import{assertNever as ju,assertNonNullable as DS,isNonNullable as aa,ValueSubject as Ns,Subject as BS,Subscription as OS,merge as VS,observableFrom as _S,fromEvent as Fu,map as qu,tap as Uu,filterChanged as NS,isNullable as Fs,ErrorCategory as Hu}from"@vkontakte/videoplayer-shared";var Nu=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 sa=class{constructor(e){this.connection$=new Ns(void 0);this.castState$=new Ns("NOT_AVAILABLE");this.errorEvent$=new BS;this.realCastState$=new Ns("NOT_AVAILABLE");this.subscription=new OS;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=aa(window.chrome?.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},a||Nu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Hu.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(){aa(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Fs(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Fs(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(Fu(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 ju(a.sessionState)}})).add(VS(Fu(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Uu(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),qu(a=>a.castState)),_S([r.getCastState()])).pipe(NS(),qu(FS),Uu(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=aa(this.connection$.getValue());if(s&&!n){let o=r.getCurrentSession();DS(o);let l=o.getCastDevice(),u=o.getMediaSession()?.media.contentId;(Fs(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"?aa(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:Hu.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},FS=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 ju(i)}};var rS=Oe(qn(),1);var Rf=Oe(Fa(),1);import{assertNever as yf}from"@vkontakte/videoplayer-shared";var z=(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:yf(t)}return i},wo=(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:yf(e)}};var I=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};import{isNonNullable as zx,Subject as qa,merge as Tf}from"@vkontakte/videoplayer-shared";var L=class{constructor(e){this.transitionStarted$=new qa;this.transitionEnded$=new qa;this.transitionUpdated$=new qa;this.forceChanged$=new qa;this.stateChangeStarted$=Tf(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Tf(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||zx(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 Kx}from"@vkontakte/videoplayer-shared";var If=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 Kx(i)}};import{assertNever as nr,assertNonNullable as xt,debounce as Ef,ErrorCategory as xf,fromEvent as Pt,isNonNullable as Pf,map as Af,merge as wf,observableFrom as Jx,Subject as Xx,Subscription as ko,timeout as Zx,getHighestQuality as eP}from"@vkontakte/videoplayer-shared";var tP=5,rP=5,iP=500,kf=7e3,Qr=class{constructor(e){this.subscription=new ko;this.loadMediaTimeoutSubscription=new ko;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:nr(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:nr(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:nr(e)}break}default:nr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(If(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 ko;this.subscription.add(e),this.subscription.add(wf(this.videoState.stateChangeStarted$.pipe(Af(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(Af(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 Xx;e.add(a.pipe(Ef(iP)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Pt(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)>tP)&&a.next(o),s=o})),e.add(Pt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Pt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Pt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(Pt(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<rP&&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:nr(n)}}),t(Pt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(Pt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=wf(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Jx(["init"])).pipe(Ef(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];xt(u);let c=eP(Object.keys(u));xt(c);let d=u[c];xt(d),r=d,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let u=t[e];xt(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];xt(u),r=u.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let u=t[e];xt(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];xt(u),r=z(u.url),a="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let u="Unsupported format for Chromecast",c=new Error(u);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:xf.VIDEO_PIPELINE,message:u,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return nr(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 Pf(o)&&(n.metadata.title=o),Pf(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(Zx(kf).subscribe(()=>s(`timeout(${kf})`)))});(0,Rf.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:xf.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as $f}from"@vkontakte/videoplayer-shared";import{clearVideoElement as aP}from"@vkontakte/videoplayer-shared";var Lf=i=>{try{i.pause(),i.playbackRate=0,aP(i),i.remove()}catch(e){console.error(e)}};import{fromEvent as sP,Subscription as nP}from"@vkontakte/videoplayer-shared";var Ro=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)}},Lo=window.WeakMap?new WeakMap:new Ro,$o=window.WeakMap?new WeakMap:new Map,oP=(i,e=20)=>{let t=0;return sP(i,"ratechange").subscribe(r=>{t++,t>=e&&(i.currentTime=i.currentTime,t=0)})},re=(i,{audioVideoSyncRate:e})=>{let t=i.querySelector("video"),r=!!t;t?$f(t):(t=document.createElement("video"),i.appendChild(t)),Lo.set(t,r);let a=new nP;return a.add(oP(t,e)),$o.set(t,a),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},ie=i=>{$o.get(i)?.unsubscribe(),$o.delete(i);let t=Lo.get(i);Lo.delete(i),t?$f(i):Lf(i)};import{assertNonNullable as zr,isNonNullable as Ne,isNullable as cP,fromEvent as or,merge as Mf,observableFrom as Cf,filterChanged as Df,map as Kr,Subject as Bf,Subscription as dP,ValueSubject as pP,ErrorCategory as hP}from"@vkontakte/videoplayer-shared";import{isNonNullable as Mo,isNullable as uP,Subscription as lP}from"@vkontakte/videoplayer-shared";var Ua=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),l=uP(a),u=new lP;return a&&u.add(a.subscribe(c=>{let d=i.getState();r(c,d)&&i.setState(c)},s)),r(o,n)||(t(n),l&&i.setState(n)),u.add(i.stateChangeStarted$.subscribe(c=>{t(c.to),l&&i.setState(c.to)},s)),u},_e=(i,e,t)=>Ua(e,()=>i.loop,r=>{Mo(r)&&(i.loop=r)},{onError:t}),ae=(i,e,t,r)=>Ua(e,()=>({muted:i.muted,volume:i.volume}),a=>{Mo(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}),ve=(i,e,t,r)=>Ua(e,()=>i.playbackRate,a=>{Mo(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),it=Ua;var fP=i=>["__",i.language,i.label].join("|"),mP=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},Co=class i{constructor(){this.available$=new Bf;this.current$=new pP(void 0);this.error$=new Bf;this.subscription=new dP;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:hP.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(it(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{Ne(s)&&this.setInternal(s)},{equal:(s,n)=>Ne(s)&&Ne(n)&&s.length===n.length&&s.every(({id:o},l)=>o===n[l].id),changed$:this.available$.pipe(Kr(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(it(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{Ne(s)&&this.setExternal(s)},{equal:(s,n)=>Ne(s)&&Ne(n)&&s.length===n.length&&s.every(({id:o},l)=>o===n[l].id),changed$:this.available$.pipe(Kr(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(it(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(it(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(or(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(Mf(or(e,"addtrack"),or(e,"removetrack"),Cf(["init"])).pipe(Kr(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Df((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add(Mf(or(e,"change"),Cf(["init"])).pipe(Kr(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Kr(r=>r&&this.htmlTextTrackToITextTrack(r).id),Df()).subscribe(this.current$));let t=r=>this.applyCueSettings(r.target?.activeCues??null);this.subscription.add(or(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(or(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;Ne(t.align)&&(a.align=t.align),Ne(t.position)&&(a.position=t.position),Ne(t.size)&&(a.size=t.size),Ne(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:fP(e),s=this.externalTracks.has(a),n=a.includes("auto");return s?{id:a,type:"external",isAuto:n,language:t,label:r,url:this.externalTracks.get(a)?.url}:{id:a,type:"internal",isAuto:n,language:t,label:r,url:this.internalTracks.get(a)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:a,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===a&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(a=>a.id===r)).forEach(([,r])=>this.detach(r))}select(e){zr(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(cP(e)||!mP(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)}},ye=Co;var Ge=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 Of=i=>{let e=i;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Do=i=>{let e=Of(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},Vf=i=>{let e=Of(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};import{fromEvent as Te,map as at,merge as Nf,filterChanged as SP,isNonNullable as Ff,Subject as gP,filter as qf,mapTo as Uf,combine as vP,once as yP,ErrorCategory as TP,ValueSubject as Hf,clientChecker as IP}from"@vkontakte/videoplayer-shared";var bP=3,_f=(i,e,t=bP)=>{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 se=i=>{let e=T=>Te(i,T).pipe(Uf(void 0)),r=Nf(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(T=>Te(i,T))).pipe(at(T=>T.type==="ended"?i.readyState<2:i.readyState<3),SP()),a=Nf(Te(i,"progress"),Te(i,"timeupdate")).pipe(at(()=>_f(i.buffered,i.currentTime))),s=IP.isSafari?vP({play:e("play").pipe(yP()),playing:e("playing")}).pipe(Uf(void 0)):e("playing"),n=Te(i,"volumechange").pipe(at(()=>({muted:i.muted,volume:i.volume}))),o=Te(i,"ratechange").pipe(at(()=>i.playbackRate)),l=Te(i,"error").pipe(qf(()=>!!(i.error||i.played.length)),at(()=>{let T=i.error;return{id:T?`MediaError#${T.code}`:"HtmlVideoError",category:TP.VIDEO_PIPELINE,message:T?T.message:"Error event from HTML video element",thrown:i.error??void 0}})),u=Te(i,"timeupdate").pipe(at(()=>i.currentTime)),c=new gP,d=.3,p;u.subscribe(T=>{i.loop&&Ff(p)&&Ff(T)&&p>=i.duration-d&&T<=d&&c.next(p),p=T});let h=e("pause").pipe(qf(()=>!i.error&&p!==i.duration)),m=Te(i,"enterpictureinpicture"),b=Te(i,"leavepictureinpicture"),S=new Hf(Vf(i));m.subscribe(()=>S.next(!0)),b.subscribe(()=>S.next(!1));let v=new Hf(Do(i));return Te(i,"fullscreenchange").pipe(at(()=>Do(i))).subscribe(v),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:l,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:u,durationChange$:Te(i,"durationchange").pipe(at(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:v}};import{VideoQuality as st}from"@vkontakte/videoplayer-shared";var nt=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 No=Oe(Jr(),1);import{isNonNullable as ot,isNullable as Oo,now as tm,isHigher as Vo,isHigherOrEqual as Zf,isInvariantQuality as em,isLower as _o,isLowerOrEqual as $P,videoSizeToQuality as MP,assertNotEmptyArray as CP}from"@vkontakte/videoplayer-shared";var Bo=!1,Ye={},Kf=i=>{Bo=i},Jf=()=>{Ye={}},Xf=i=>{i(Ye)},Xr=(i,e)=>{Bo&&(Ye.meta=Ye.meta??{},Ye.meta[i]=e)},J=class{constructor(e){this.name=e}next(e){if(!Bo)return;Ye.series=Ye.series??{};let t=Ye.series[this.name]??[];t.push([Date.now(),e]),Ye.series[this.name]=t}};var DP=new J("best_bitrate"),BP=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t,Ha=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=tm()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},OP='Assertion "ABR Tracks is empty array" failed',VP=(i,{container:e,throughput:t,tuning:r,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:l,history:u,droppedVideoMaxQualityLimit:c,abrLogger:d})=>{CP(i,OP);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&&MP(h),b=r.considerPlaybackRate&&ot(o)?o:1,S=i.filter(P=>!em(P.quality)).sort((P,B)=>Vo(P.quality,B.quality)?-1:1),v=(0,No.default)(S,-1)?.quality,w=(0,No.default)(S,0)?.quality,T=Oo(a)||ot(a.min)&&ot(a.max)&&_o(a.max,a.min)||ot(a.min)&&w&&Vo(a.min,w)||ot(a.max)&&v&&_o(a.max,v),g=b*BP(n??.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),y={},E=S.filter(P=>(m?_o(P.quality,m):!0)?(ot(t)&&isFinite(t)&&ot(P.bitrate)?t-s>=P.bitrate*g:!0)?r.lazyQualitySwitch&&ot(r.minBufferToSwitchUp)&&l&&!em(l.quality)&&(n??0)<r.minBufferToSwitchUp&&Vo(P.quality,l.quality)?(y[P.quality]="Buffer",!1):!!c&&Zf(P.quality,c)?(y[P.quality]="DroppedFramesLimit",!1):T||(Oo(a.max)||$P(P.quality,a.max))&&(Oo(a.min)||Zf(P.quality,a.min))?!0:(y[P.quality]="FitsQualityLimits",!1):(y[P.quality]="FitsThroughput",!1):(y[P.quality]="FitsContainer",!1))[0];E&&E.bitrate&&DP.next(E.bitrate);let k=E??S[Math.ceil((S.length-1)/2)]??i[0];k.quality!==u?.last?.quality&&d({message:`
7
- [available tracks]
8
- ${i.map(P=>`{ id: ${P.id}, quality: ${P.quality}, bitrate: ${P.bitrate} }`).join(`
6
+ var Ug=Object.create;var Hu=Object.defineProperty;var Hg=Object.getOwnPropertyDescriptor;var jg=Object.getOwnPropertyNames;var Gg=Object.getPrototypeOf,Wg=Object.prototype.hasOwnProperty;var f=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var Yg=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of jg(e))!Wg.call(i,a)&&a!==t&&Hu(i,a,{get:()=>e[a],enumerable:!(r=Hg(e,a))||r.enumerable});return i};var _e=(i,e,t)=>(t=i!=null?Ug(Gg(i)):{},Yg(e||!i||!i.__esModule?Hu(t,"default",{value:i,enumerable:!0}):t,i));var fe=f((FR,Ju)=>{"use strict";Ju.exports=function(i){try{return!!i()}catch{return!0}}});var Rr=f((qR,Xu)=>{"use strict";var tS=fe();Xu.exports=!tS(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var ae=f((UR,tc)=>{"use strict";var Zu=Rr(),ec=Function.prototype,Ys=ec.call,rS=Zu&&ec.bind.bind(Ys,Ys);tc.exports=Zu?rS:function(i){return function(){return Ys.apply(i,arguments)}}});var Yt=f((HR,ic)=>{"use strict";var rc=ae(),iS=rc({}.toString),aS=rc("".slice);ic.exports=function(i){return aS(iS(i),8,-1)}});var sc=f((jR,ac)=>{"use strict";var sS=ae(),nS=fe(),oS=Yt(),Qs=Object,uS=sS("".split);ac.exports=nS(function(){return!Qs("z").propertyIsEnumerable(0)})?function(i){return oS(i)==="String"?uS(i,""):Qs(i)}:Qs});var Qt=f((GR,nc)=>{"use strict";nc.exports=function(i){return i==null}});var $r=f((WR,oc)=>{"use strict";var cS=Qt(),lS=TypeError;oc.exports=function(i){if(cS(i))throw new lS("Can't call method on "+i);return i}});var zt=f((YR,uc)=>{"use strict";var dS=sc(),pS=$r();uc.exports=function(i){return dS(pS(i))}});var zs=f((QR,cc)=>{"use strict";cc.exports=function(){}});var It=f((zR,lc)=>{"use strict";lc.exports={}});var H=f((Ks,dc)=>{"use strict";var Lr=function(i){return i&&i.Math===Math&&i};dc.exports=Lr(typeof globalThis=="object"&&globalThis)||Lr(typeof window=="object"&&window)||Lr(typeof self=="object"&&self)||Lr(typeof global=="object"&&global)||Lr(typeof Ks=="object"&&Ks)||function(){return this}()||Function("return this")()});var U=f((KR,pc)=>{"use strict";var Js=typeof document=="object"&&document.all;pc.exports=typeof Js>"u"&&Js!==void 0?function(i){return typeof i=="function"||i===Js}:function(i){return typeof i=="function"}});var mc=f((JR,fc)=>{"use strict";var hS=H(),fS=U(),hc=hS.WeakMap;fc.exports=fS(hc)&&/native code/.test(String(hc))});var ve=f((XR,bc)=>{"use strict";var mS=U();bc.exports=function(i){return typeof i=="object"?i!==null:mS(i)}});var ye=f((ZR,gc)=>{"use strict";var bS=fe();gc.exports=!bS(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var ha=f((e$,vc)=>{"use strict";var gS=H(),Sc=ve(),Xs=gS.document,SS=Sc(Xs)&&Sc(Xs.createElement);vc.exports=function(i){return SS?Xs.createElement(i):{}}});var Zs=f((t$,yc)=>{"use strict";var vS=ye(),yS=fe(),TS=ha();yc.exports=!vS&&!yS(function(){return Object.defineProperty(TS("div"),"a",{get:function(){return 7}}).a!==7})});var en=f((r$,Tc)=>{"use strict";var IS=ye(),ES=fe();Tc.exports=IS&&ES(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Ne=f((i$,Ic)=>{"use strict";var xS=ve(),PS=String,AS=TypeError;Ic.exports=function(i){if(xS(i))return i;throw new AS(PS(i)+" is not an object")}});var me=f((a$,Ec)=>{"use strict";var kS=Rr(),fa=Function.prototype.call;Ec.exports=kS?fa.bind(fa):function(){return fa.apply(fa,arguments)}});var ma=f((s$,xc)=>{"use strict";xc.exports={}});var He=f((n$,Ac)=>{"use strict";var tn=ma(),rn=H(),wS=U(),Pc=function(i){return wS(i)?i:void 0};Ac.exports=function(i,e){return arguments.length<2?Pc(tn[i])||Pc(rn[i]):tn[i]&&tn[i][e]||rn[i]&&rn[i][e]}});var Mr=f((o$,kc)=>{"use strict";var RS=ae();kc.exports=RS({}.isPrototypeOf)});var Kt=f((u$,$c)=>{"use strict";var $S=H(),wc=$S.navigator,Rc=wc&&wc.userAgent;$c.exports=Rc?String(Rc):""});var sn=f((c$,Vc)=>{"use strict";var Bc=H(),an=Kt(),Lc=Bc.process,Mc=Bc.Deno,Cc=Lc&&Lc.versions||Mc&&Mc.version,Dc=Cc&&Cc.v8,$e,ba;Dc&&($e=Dc.split("."),ba=$e[0]>0&&$e[0]<4?1:+($e[0]+$e[1]));!ba&&an&&($e=an.match(/Edge\/(\d+)/),(!$e||$e[1]>=74)&&($e=an.match(/Chrome\/(\d+)/),$e&&(ba=+$e[1])));Vc.exports=ba});var nn=f((l$,_c)=>{"use strict";var Oc=sn(),LS=fe(),MS=H(),CS=MS.String;_c.exports=!!Object.getOwnPropertySymbols&&!LS(function(){var i=Symbol("symbol detection");return!CS(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&Oc&&Oc<41})});var on=f((d$,Nc)=>{"use strict";var DS=nn();Nc.exports=DS&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var un=f((p$,Fc)=>{"use strict";var BS=He(),VS=U(),OS=Mr(),_S=on(),NS=Object;Fc.exports=_S?function(i){return typeof i=="symbol"}:function(i){var e=BS("Symbol");return VS(e)&&OS(e.prototype,NS(i))}});var Cr=f((h$,qc)=>{"use strict";var FS=String;qc.exports=function(i){try{return FS(i)}catch{return"Object"}}});var je=f((f$,Uc)=>{"use strict";var qS=U(),US=Cr(),HS=TypeError;Uc.exports=function(i){if(qS(i))return i;throw new HS(US(i)+" is not a function")}});var Dr=f((m$,Hc)=>{"use strict";var jS=je(),GS=Qt();Hc.exports=function(i,e){var t=i[e];return GS(t)?void 0:jS(t)}});var Gc=f((b$,jc)=>{"use strict";var cn=me(),ln=U(),dn=ve(),WS=TypeError;jc.exports=function(i,e){var t,r;if(e==="string"&&ln(t=i.toString)&&!dn(r=cn(t,i))||ln(t=i.valueOf)&&!dn(r=cn(t,i))||e!=="string"&&ln(t=i.toString)&&!dn(r=cn(t,i)))return r;throw new WS("Can't convert object to primitive value")}});var Le=f((g$,Wc)=>{"use strict";Wc.exports=!0});var zc=f((S$,Qc)=>{"use strict";var Yc=H(),YS=Object.defineProperty;Qc.exports=function(i,e){try{YS(Yc,i,{value:e,configurable:!0,writable:!0})}catch{Yc[i]=e}return e}});var Br=f((v$,Xc)=>{"use strict";var QS=Le(),zS=H(),KS=zc(),Kc="__core-js_shared__",Jc=Xc.exports=zS[Kc]||KS(Kc,{});(Jc.versions||(Jc.versions=[])).push({version:"3.38.0",mode:QS?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var pn=f((y$,el)=>{"use strict";var Zc=Br();el.exports=function(i,e){return Zc[i]||(Zc[i]=e||{})}});var Vr=f((T$,tl)=>{"use strict";var JS=$r(),XS=Object;tl.exports=function(i){return XS(JS(i))}});var Me=f((I$,rl)=>{"use strict";var ZS=ae(),ev=Vr(),tv=ZS({}.hasOwnProperty);rl.exports=Object.hasOwn||function(e,t){return tv(ev(e),t)}});var hn=f((E$,il)=>{"use strict";var rv=ae(),iv=0,av=Math.random(),sv=rv(1 .toString);il.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+sv(++iv+av,36)}});var J=f((x$,sl)=>{"use strict";var nv=H(),ov=pn(),al=Me(),uv=hn(),cv=nn(),lv=on(),Jt=nv.Symbol,fn=ov("wks"),dv=lv?Jt.for||Jt:Jt&&Jt.withoutSetter||uv;sl.exports=function(i){return al(fn,i)||(fn[i]=cv&&al(Jt,i)?Jt[i]:dv("Symbol."+i)),fn[i]}});var cl=f((P$,ul)=>{"use strict";var pv=me(),nl=ve(),ol=un(),hv=Dr(),fv=Gc(),mv=J(),bv=TypeError,gv=mv("toPrimitive");ul.exports=function(i,e){if(!nl(i)||ol(i))return i;var t=hv(i,gv),r;if(t){if(e===void 0&&(e="default"),r=pv(t,i,e),!nl(r)||ol(r))return r;throw new bv("Can't convert object to primitive value")}return e===void 0&&(e="number"),fv(i,e)}});var mn=f((A$,ll)=>{"use strict";var Sv=cl(),vv=un();ll.exports=function(i){var e=Sv(i,"string");return vv(e)?e:e+""}});var Et=f(pl=>{"use strict";var yv=ye(),Tv=Zs(),Iv=en(),ga=Ne(),dl=mn(),Ev=TypeError,bn=Object.defineProperty,xv=Object.getOwnPropertyDescriptor,gn="enumerable",Sn="configurable",vn="writable";pl.f=yv?Iv?function(e,t,r){if(ga(e),t=dl(t),ga(r),typeof e=="function"&&t==="prototype"&&"value"in r&&vn in r&&!r[vn]){var a=xv(e,t);a&&a[vn]&&(e[t]=r.value,r={configurable:Sn in r?r[Sn]:a[Sn],enumerable:gn in r?r[gn]:a[gn],writable:!1})}return bn(e,t,r)}:bn:function(e,t,r){if(ga(e),t=dl(t),ga(r),Tv)try{return bn(e,t,r)}catch{}if("get"in r||"set"in r)throw new Ev("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Or=f((w$,hl)=>{"use strict";hl.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var Xt=f((R$,fl)=>{"use strict";var Pv=ye(),Av=Et(),kv=Or();fl.exports=Pv?function(i,e,t){return Av.f(i,e,kv(1,t))}:function(i,e,t){return i[e]=t,i}});var Sa=f(($$,bl)=>{"use strict";var wv=pn(),Rv=hn(),ml=wv("keys");bl.exports=function(i){return ml[i]||(ml[i]=Rv(i))}});var va=f((L$,gl)=>{"use strict";gl.exports={}});var En=f((M$,yl)=>{"use strict";var $v=mc(),vl=H(),Lv=ve(),Mv=Xt(),yn=Me(),Tn=Br(),Cv=Sa(),Dv=va(),Sl="Object already initialized",In=vl.TypeError,Bv=vl.WeakMap,ya,_r,Ta,Vv=function(i){return Ta(i)?_r(i):ya(i,{})},Ov=function(i){return function(e){var t;if(!Lv(e)||(t=_r(e)).type!==i)throw new In("Incompatible receiver, "+i+" required");return t}};$v||Tn.state?(Ce=Tn.state||(Tn.state=new Bv),Ce.get=Ce.get,Ce.has=Ce.has,Ce.set=Ce.set,ya=function(i,e){if(Ce.has(i))throw new In(Sl);return e.facade=i,Ce.set(i,e),e},_r=function(i){return Ce.get(i)||{}},Ta=function(i){return Ce.has(i)}):(xt=Cv("state"),Dv[xt]=!0,ya=function(i,e){if(yn(i,xt))throw new In(Sl);return e.facade=i,Mv(i,xt,e),e},_r=function(i){return yn(i,xt)?i[xt]:{}},Ta=function(i){return yn(i,xt)});var Ce,xt;yl.exports={set:ya,get:_r,has:Ta,enforce:Vv,getterFor:Ov}});var xn=f((C$,xl)=>{"use strict";var _v=Rr(),El=Function.prototype,Tl=El.apply,Il=El.call;xl.exports=typeof Reflect=="object"&&Reflect.apply||(_v?Il.bind(Tl):function(){return Il.apply(Tl,arguments)})});var Pn=f((D$,Pl)=>{"use strict";var Nv=Yt(),Fv=ae();Pl.exports=function(i){if(Nv(i)==="Function")return Fv(i)}});var Rl=f(wl=>{"use strict";var Al={}.propertyIsEnumerable,kl=Object.getOwnPropertyDescriptor,qv=kl&&!Al.call({1:2},1);wl.f=qv?function(e){var t=kl(this,e);return!!t&&t.enumerable}:Al});var Ml=f(Ll=>{"use strict";var Uv=ye(),Hv=me(),jv=Rl(),Gv=Or(),Wv=zt(),Yv=mn(),Qv=Me(),zv=Zs(),$l=Object.getOwnPropertyDescriptor;Ll.f=Uv?$l:function(e,t){if(e=Wv(e),t=Yv(t),zv)try{return $l(e,t)}catch{}if(Qv(e,t))return Gv(!Hv(jv.f,e,t),e[t])}});var An=f((O$,Cl)=>{"use strict";var Kv=fe(),Jv=U(),Xv=/#|\.prototype\./,Nr=function(i,e){var t=ey[Zv(i)];return t===ry?!0:t===ty?!1:Jv(e)?Kv(e):!!e},Zv=Nr.normalize=function(i){return String(i).replace(Xv,".").toLowerCase()},ey=Nr.data={},ty=Nr.NATIVE="N",ry=Nr.POLYFILL="P";Cl.exports=Nr});var Fr=f((_$,Bl)=>{"use strict";var Dl=Pn(),iy=je(),ay=Rr(),sy=Dl(Dl.bind);Bl.exports=function(i,e){return iy(i),e===void 0?i:ay?sy(i,e):function(){return i.apply(e,arguments)}}});var Te=f((N$,Ol)=>{"use strict";var qr=H(),ny=xn(),oy=Pn(),uy=U(),cy=Ml().f,ly=An(),Zt=ma(),dy=Fr(),er=Xt(),Vl=Me();Br();var py=function(i){var e=function(t,r,a){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,r)}return new i(t,r,a)}return ny(i,this,arguments)};return e.prototype=i.prototype,e};Ol.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?qr:a?qr[t]:qr[t]&&qr[t].prototype,o=r?Zt:Zt[t]||er(Zt,t,{})[t],c=o.prototype,u,d,l,p,h,m,b,g,v;for(p in e)u=ly(r?p:t+(a?".":"#")+p,i.forced),d=!u&&n&&Vl(n,p),m=o[p],d&&(i.dontCallGetSet?(v=cy(n,p),b=v&&v.value):b=n[p]),h=d&&b?b:e[p],!(!u&&!s&&typeof m==typeof h)&&(i.bind&&d?g=dy(h,qr):i.wrap&&d?g=py(h):s&&uy(h)?g=oy(h):g=h,(i.sham||h&&h.sham||m&&m.sham)&&er(g,"sham",!0),er(o,p,g),s&&(l=t+"Prototype",Vl(Zt,l)||er(Zt,l,{}),er(Zt[l],p,h),i.real&&c&&(u||!c[p])&&er(c,p,h)))}});var Fl=f((F$,Nl)=>{"use strict";var kn=ye(),hy=Me(),_l=Function.prototype,fy=kn&&Object.getOwnPropertyDescriptor,wn=hy(_l,"name"),my=wn&&function(){}.name==="something",by=wn&&(!kn||kn&&fy(_l,"name").configurable);Nl.exports={EXISTS:wn,PROPER:my,CONFIGURABLE:by}});var Ul=f((q$,ql)=>{"use strict";var gy=Math.ceil,Sy=Math.floor;ql.exports=Math.trunc||function(e){var t=+e;return(t>0?Sy:gy)(t)}});var Ia=f((U$,Hl)=>{"use strict";var vy=Ul();Hl.exports=function(i){var e=+i;return e!==e||e===0?0:vy(e)}});var Gl=f((H$,jl)=>{"use strict";var yy=Ia(),Ty=Math.max,Iy=Math.min;jl.exports=function(i,e){var t=yy(i);return t<0?Ty(t+e,0):Iy(t,e)}});var Yl=f((j$,Wl)=>{"use strict";var Ey=Ia(),xy=Math.min;Wl.exports=function(i){var e=Ey(i);return e>0?xy(e,9007199254740991):0}});var Ea=f((G$,Ql)=>{"use strict";var Py=Yl();Ql.exports=function(i){return Py(i.length)}});var Jl=f((W$,Kl)=>{"use strict";var Ay=zt(),ky=Gl(),wy=Ea(),zl=function(i){return function(e,t,r){var a=Ay(e),s=wy(a);if(s===0)return!i&&-1;var n=ky(r,s),o;if(i&&t!==t){for(;s>n;)if(o=a[n++],o!==o)return!0}else for(;s>n;n++)if((i||n in a)&&a[n]===t)return i||n||0;return!i&&-1}};Kl.exports={includes:zl(!0),indexOf:zl(!1)}});var ed=f((Y$,Zl)=>{"use strict";var Ry=ae(),Rn=Me(),$y=zt(),Ly=Jl().indexOf,My=va(),Xl=Ry([].push);Zl.exports=function(i,e){var t=$y(i),r=0,a=[],s;for(s in t)!Rn(My,s)&&Rn(t,s)&&Xl(a,s);for(;e.length>r;)Rn(t,s=e[r++])&&(~Ly(a,s)||Xl(a,s));return a}});var $n=f((Q$,td)=>{"use strict";td.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var id=f((z$,rd)=>{"use strict";var Cy=ed(),Dy=$n();rd.exports=Object.keys||function(e){return Cy(e,Dy)}});var sd=f(ad=>{"use strict";var By=ye(),Vy=en(),Oy=Et(),_y=Ne(),Ny=zt(),Fy=id();ad.f=By&&!Vy?Object.defineProperties:function(e,t){_y(e);for(var r=Ny(t),a=Fy(t),s=a.length,n=0,o;s>n;)Oy.f(e,o=a[n++],r[o]);return e}});var Ln=f((J$,nd)=>{"use strict";var qy=He();nd.exports=qy("document","documentElement")});var Bn=f((X$,hd)=>{"use strict";var Uy=Ne(),Hy=sd(),od=$n(),jy=va(),Gy=Ln(),Wy=ha(),Yy=Sa(),ud=">",cd="<",Cn="prototype",Dn="script",dd=Yy("IE_PROTO"),Mn=function(){},pd=function(i){return cd+Dn+ud+i+cd+"/"+Dn+ud},ld=function(i){i.write(pd("")),i.close();var e=i.parentWindow.Object;return i=null,e},Qy=function(){var i=Wy("iframe"),e="java"+Dn+":",t;return i.style.display="none",Gy.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(pd("document.F=Object")),t.close(),t.F},xa,Pa=function(){try{xa=new ActiveXObject("htmlfile")}catch{}Pa=typeof document<"u"?document.domain&&xa?ld(xa):Qy():ld(xa);for(var i=od.length;i--;)delete Pa[Cn][od[i]];return Pa()};jy[dd]=!0;hd.exports=Object.create||function(e,t){var r;return e!==null?(Mn[Cn]=Uy(e),r=new Mn,Mn[Cn]=null,r[dd]=e):r=Pa(),t===void 0?r:Hy.f(r,t)}});var md=f((Z$,fd)=>{"use strict";var zy=fe();fd.exports=!zy(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var On=f((eL,gd)=>{"use strict";var Ky=Me(),Jy=U(),Xy=Vr(),Zy=Sa(),eT=md(),bd=Zy("IE_PROTO"),Vn=Object,tT=Vn.prototype;gd.exports=eT?Vn.getPrototypeOf:function(i){var e=Xy(i);if(Ky(e,bd))return e[bd];var t=e.constructor;return Jy(t)&&e instanceof t?t.prototype:e instanceof Vn?tT:null}});var tr=f((tL,Sd)=>{"use strict";var rT=Xt();Sd.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:rT(i,e,t),i}});var qn=f((rL,Td)=>{"use strict";var iT=fe(),aT=U(),sT=ve(),nT=Bn(),vd=On(),oT=tr(),uT=J(),cT=Le(),Fn=uT("iterator"),yd=!1,Ge,_n,Nn;[].keys&&(Nn=[].keys(),"next"in Nn?(_n=vd(vd(Nn)),_n!==Object.prototype&&(Ge=_n)):yd=!0);var lT=!sT(Ge)||iT(function(){var i={};return Ge[Fn].call(i)!==i});lT?Ge={}:cT&&(Ge=nT(Ge));aT(Ge[Fn])||oT(Ge,Fn,function(){return this});Td.exports={IteratorPrototype:Ge,BUGGY_SAFARI_ITERATORS:yd}});var Aa=f((iL,Ed)=>{"use strict";var dT=J(),pT=dT("toStringTag"),Id={};Id[pT]="z";Ed.exports=String(Id)==="[object z]"});var Ur=f((aL,xd)=>{"use strict";var hT=Aa(),fT=U(),ka=Yt(),mT=J(),bT=mT("toStringTag"),gT=Object,ST=ka(function(){return arguments}())==="Arguments",vT=function(i,e){try{return i[e]}catch{}};xd.exports=hT?ka:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=vT(e=gT(i),bT))=="string"?t:ST?ka(e):(r=ka(e))==="Object"&&fT(e.callee)?"Arguments":r}});var Ad=f((sL,Pd)=>{"use strict";var yT=Aa(),TT=Ur();Pd.exports=yT?{}.toString:function(){return"[object "+TT(this)+"]"}});var Hr=f((nL,wd)=>{"use strict";var IT=Aa(),ET=Et().f,xT=Xt(),PT=Me(),AT=Ad(),kT=J(),kd=kT("toStringTag");wd.exports=function(i,e,t,r){var a=t?i:i&&i.prototype;a&&(PT(a,kd)||ET(a,kd,{configurable:!0,value:e}),r&&!IT&&xT(a,"toString",AT))}});var $d=f((oL,Rd)=>{"use strict";var wT=qn().IteratorPrototype,RT=Bn(),$T=Or(),LT=Hr(),MT=It(),CT=function(){return this};Rd.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=RT(wT,{next:$T(+!r,t)}),LT(i,a,!1,!0),MT[a]=CT,i}});var Md=f((uL,Ld)=>{"use strict";var DT=ae(),BT=je();Ld.exports=function(i,e,t){try{return DT(BT(Object.getOwnPropertyDescriptor(i,e)[t]))}catch{}}});var Dd=f((cL,Cd)=>{"use strict";var VT=ve();Cd.exports=function(i){return VT(i)||i===null}});var Vd=f((lL,Bd)=>{"use strict";var OT=Dd(),_T=String,NT=TypeError;Bd.exports=function(i){if(OT(i))return i;throw new NT("Can't set "+_T(i)+" as a prototype")}});var Un=f((dL,Od)=>{"use strict";var FT=Md(),qT=ve(),UT=$r(),HT=Vd();Od.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=FT(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch{}return function(a,s){return UT(a),HT(s),qT(a)&&(i?t(a,s):a.__proto__=s),a}}():void 0)});var Qd=f((pL,Yd)=>{"use strict";var jT=Te(),GT=me(),wa=Le(),Gd=Fl(),WT=U(),YT=$d(),_d=On(),Nd=Un(),QT=Hr(),zT=Xt(),Hn=tr(),KT=J(),Fd=It(),Wd=qn(),JT=Gd.PROPER,XT=Gd.CONFIGURABLE,qd=Wd.IteratorPrototype,Ra=Wd.BUGGY_SAFARI_ITERATORS,jr=KT("iterator"),Ud="keys",Gr="values",Hd="entries",jd=function(){return this};Yd.exports=function(i,e,t,r,a,s,n){YT(t,e,r);var o=function(v){if(v===a&&p)return p;if(!Ra&&v&&v in d)return d[v];switch(v){case Ud:return function(){return new t(this,v)};case Gr:return function(){return new t(this,v)};case Hd:return function(){return new t(this,v)}}return function(){return new t(this)}},c=e+" Iterator",u=!1,d=i.prototype,l=d[jr]||d["@@iterator"]||a&&d[a],p=!Ra&&l||o(a),h=e==="Array"&&d.entries||l,m,b,g;if(h&&(m=_d(h.call(new i)),m!==Object.prototype&&m.next&&(!wa&&_d(m)!==qd&&(Nd?Nd(m,qd):WT(m[jr])||Hn(m,jr,jd)),QT(m,c,!0,!0),wa&&(Fd[c]=jd))),JT&&a===Gr&&l&&l.name!==Gr&&(!wa&&XT?zT(d,"name",Gr):(u=!0,p=function(){return GT(l,this)})),a)if(b={values:o(Gr),keys:s?p:o(Ud),entries:o(Hd)},n)for(g in b)(Ra||u||!(g in d))&&Hn(d,g,b[g]);else jT({target:e,proto:!0,forced:Ra||u},b);return(!wa||n)&&d[jr]!==p&&Hn(d,jr,p,{name:a}),Fd[e]=p,b}});var Kd=f((hL,zd)=>{"use strict";zd.exports=function(i,e){return{value:i,done:e}}});var Gn=f((fL,tp)=>{"use strict";var ZT=zt(),jn=zs(),Jd=It(),Zd=En(),eI=Et().f,tI=Qd(),$a=Kd(),rI=Le(),iI=ye(),ep="Array Iterator",aI=Zd.set,sI=Zd.getterFor(ep);tp.exports=tI(Array,"Array",function(i,e){aI(this,{type:ep,target:ZT(i),index:0,kind:e})},function(){var i=sI(this),e=i.target,t=i.index++;if(!e||t>=e.length)return i.target=void 0,$a(void 0,!0);switch(i.kind){case"keys":return $a(t,!1);case"values":return $a(e[t],!1)}return $a([t,e[t]],!1)},"values");var Xd=Jd.Arguments=Jd.Array;jn("keys");jn("values");jn("entries");if(!rI&&iI&&Xd.name!=="values")try{eI(Xd,"name",{value:"values"})}catch{}});var ip=f((mL,rp)=>{"use strict";var nI=J(),oI=It(),uI=nI("iterator"),cI=Array.prototype;rp.exports=function(i){return i!==void 0&&(oI.Array===i||cI[uI]===i)}});var Wn=f((bL,sp)=>{"use strict";var lI=Ur(),ap=Dr(),dI=Qt(),pI=It(),hI=J(),fI=hI("iterator");sp.exports=function(i){if(!dI(i))return ap(i,fI)||ap(i,"@@iterator")||pI[lI(i)]}});var op=f((gL,np)=>{"use strict";var mI=me(),bI=je(),gI=Ne(),SI=Cr(),vI=Wn(),yI=TypeError;np.exports=function(i,e){var t=arguments.length<2?vI(i):e;if(bI(t))return gI(mI(t,i));throw new yI(SI(i)+" is not iterable")}});var lp=f((SL,cp)=>{"use strict";var TI=me(),up=Ne(),II=Dr();cp.exports=function(i,e,t){var r,a;up(i);try{if(r=II(i,"return"),!r){if(e==="throw")throw t;return t}r=TI(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return up(r),t}});var Ma=f((vL,fp)=>{"use strict";var EI=Fr(),xI=me(),PI=Ne(),AI=Cr(),kI=ip(),wI=Ea(),dp=Mr(),RI=op(),$I=Wn(),pp=lp(),LI=TypeError,La=function(i,e){this.stopped=i,this.result=e},hp=La.prototype;fp.exports=function(i,e,t){var r=t&&t.that,a=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),c=EI(e,r),u,d,l,p,h,m,b,g=function(A){return u&&pp(u,"normal",A),new La(!0,A)},v=function(A){return a?(PI(A),o?c(A[0],A[1],g):c(A[0],A[1])):o?c(A,g):c(A)};if(s)u=i.iterator;else if(n)u=i;else{if(d=$I(i),!d)throw new LI(AI(i)+" is not iterable");if(kI(d)){for(l=0,p=wI(i);p>l;l++)if(h=v(i[l]),h&&dp(hp,h))return h;return new La(!1)}u=RI(i,d)}for(m=s?i.next:u.next;!(b=xI(m,u)).done;){try{h=v(b.value)}catch(A){pp(u,"throw",A)}if(typeof h=="object"&&h&&dp(hp,h))return h}return new La(!1)}});var bp=f((yL,mp)=>{"use strict";var MI=ye(),CI=Et(),DI=Or();mp.exports=function(i,e,t){MI?CI.f(i,e,DI(0,t)):i[e]=t}});var gp=f(()=>{"use strict";var BI=Te(),VI=Ma(),OI=bp();BI({target:"Object",stat:!0},{fromEntries:function(e){var t={};return VI(e,function(r,a){OI(t,r,a)},{AS_ENTRIES:!0}),t}})});var vp=f((EL,Sp)=>{"use strict";Gn();gp();var _I=ma();Sp.exports=_I.Object.fromEntries});var Tp=f((xL,yp)=>{"use strict";yp.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}});var Ep=f(()=>{"use strict";Gn();var NI=Tp(),FI=H(),qI=Hr(),Ip=It();for(Ca in NI)qI(FI[Ca],Ca),Ip[Ca]=Ip.Array;var Ca});var Pp=f((kL,xp)=>{"use strict";var UI=vp();Ep();xp.exports=UI});var Yn=f((wL,Ap)=>{"use strict";var HI=Pp();Ap.exports=HI});var kp=f(()=>{"use strict"});var Qn=f((LL,wp)=>{"use strict";var Wr=H(),jI=Kt(),GI=Yt(),Da=function(i){return jI.slice(0,i.length)===i};wp.exports=function(){return Da("Bun/")?"BUN":Da("Cloudflare-Workers")?"CLOUDFLARE":Da("Deno/")?"DENO":Da("Node.js/")?"NODE":Wr.Bun&&typeof Bun.version=="string"?"BUN":Wr.Deno&&typeof Deno.version=="object"?"DENO":GI(Wr.process)==="process"?"NODE":Wr.window&&Wr.document?"BROWSER":"REST"}()});var Ba=f((ML,Rp)=>{"use strict";var WI=Qn();Rp.exports=WI==="NODE"});var Lp=f((CL,$p)=>{"use strict";var YI=Et();$p.exports=function(i,e,t){return YI.f(i,e,t)}});var Dp=f((DL,Cp)=>{"use strict";var QI=He(),zI=Lp(),KI=J(),JI=ye(),Mp=KI("species");Cp.exports=function(i){var e=QI(i);JI&&e&&!e[Mp]&&zI(e,Mp,{configurable:!0,get:function(){return this}})}});var Vp=f((BL,Bp)=>{"use strict";var XI=Mr(),ZI=TypeError;Bp.exports=function(i,e){if(XI(e,i))return i;throw new ZI("Incorrect invocation")}});var Kn=f((VL,Op)=>{"use strict";var eE=ae(),tE=U(),zn=Br(),rE=eE(Function.toString);tE(zn.inspectSource)||(zn.inspectSource=function(i){return rE(i)});Op.exports=zn.inspectSource});var Hp=f((OL,Up)=>{"use strict";var iE=ae(),aE=fe(),_p=U(),sE=Ur(),nE=He(),oE=Kn(),Np=function(){},Fp=nE("Reflect","construct"),Jn=/^\s*(?:class|function)\b/,uE=iE(Jn.exec),cE=!Jn.test(Np),Yr=function(e){if(!_p(e))return!1;try{return Fp(Np,[],e),!0}catch{return!1}},qp=function(e){if(!_p(e))return!1;switch(sE(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return cE||!!uE(Jn,oE(e))}catch{return!0}};qp.sham=!0;Up.exports=!Fp||aE(function(){var i;return Yr(Yr.call)||!Yr(Object)||!Yr(function(){i=!0})||i})?qp:Yr});var Gp=f((_L,jp)=>{"use strict";var lE=Hp(),dE=Cr(),pE=TypeError;jp.exports=function(i){if(lE(i))return i;throw new pE(dE(i)+" is not a constructor")}});var Xn=f((NL,Yp)=>{"use strict";var Wp=Ne(),hE=Gp(),fE=Qt(),mE=J(),bE=mE("species");Yp.exports=function(i,e){var t=Wp(i).constructor,r;return t===void 0||fE(r=Wp(t)[bE])?e:hE(r)}});var zp=f((FL,Qp)=>{"use strict";var gE=ae();Qp.exports=gE([].slice)});var Jp=f((qL,Kp)=>{"use strict";var SE=TypeError;Kp.exports=function(i,e){if(i<e)throw new SE("Not enough arguments");return i}});var Zn=f((UL,Xp)=>{"use strict";var vE=Kt();Xp.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(vE)});var uo=f((HL,oh)=>{"use strict";var be=H(),yE=xn(),TE=Fr(),Zp=U(),IE=Me(),nh=fe(),eh=Ln(),EE=zp(),th=ha(),xE=Jp(),PE=Zn(),AE=Ba(),so=be.setImmediate,no=be.clearImmediate,kE=be.process,eo=be.Dispatch,wE=be.Function,rh=be.MessageChannel,RE=be.String,to=0,Qr={},ih="onreadystatechange",zr,Pt,ro,io;nh(function(){zr=be.location});var oo=function(i){if(IE(Qr,i)){var e=Qr[i];delete Qr[i],e()}},ao=function(i){return function(){oo(i)}},ah=function(i){oo(i.data)},sh=function(i){be.postMessage(RE(i),zr.protocol+"//"+zr.host)};(!so||!no)&&(so=function(e){xE(arguments.length,1);var t=Zp(e)?e:wE(e),r=EE(arguments,1);return Qr[++to]=function(){yE(t,void 0,r)},Pt(to),to},no=function(e){delete Qr[e]},AE?Pt=function(i){kE.nextTick(ao(i))}:eo&&eo.now?Pt=function(i){eo.now(ao(i))}:rh&&!PE?(ro=new rh,io=ro.port2,ro.port1.onmessage=ah,Pt=TE(io.postMessage,io)):be.addEventListener&&Zp(be.postMessage)&&!be.importScripts&&zr&&zr.protocol!=="file:"&&!nh(sh)?(Pt=sh,be.addEventListener("message",ah,!1)):ih in th("script")?Pt=function(i){eh.appendChild(th("script"))[ih]=function(){eh.removeChild(this),oo(i)}}:Pt=function(i){setTimeout(ao(i),0)});oh.exports={set:so,clear:no}});var lh=f((jL,ch)=>{"use strict";var uh=H(),$E=ye(),LE=Object.getOwnPropertyDescriptor;ch.exports=function(i){if(!$E)return uh[i];var e=LE(uh,i);return e&&e.value}});var co=f((GL,ph)=>{"use strict";var dh=function(){this.head=null,this.tail=null};dh.prototype={add:function(i){var e={item:i,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var i=this.head;if(i){var e=this.head=i.next;return e===null&&(this.tail=null),i.item}}};ph.exports=dh});var fh=f((WL,hh)=>{"use strict";var ME=Kt();hh.exports=/ipad|iphone|ipod/i.test(ME)&&typeof Pebble<"u"});var bh=f((YL,mh)=>{"use strict";var CE=Kt();mh.exports=/web0s(?!.*chrome)/i.test(CE)});var Eh=f((QL,Ih)=>{"use strict";var ir=H(),DE=lh(),gh=Fr(),lo=uo().set,BE=co(),VE=Zn(),OE=fh(),_E=bh(),po=Ba(),Sh=ir.MutationObserver||ir.WebKitMutationObserver,vh=ir.document,yh=ir.process,Va=ir.Promise,mo=DE("queueMicrotask"),rr,ho,fo,Oa,Th;mo||(Kr=new BE,Jr=function(){var i,e;for(po&&(i=yh.domain)&&i.exit();e=Kr.get();)try{e()}catch(t){throw Kr.head&&rr(),t}i&&i.enter()},!VE&&!po&&!_E&&Sh&&vh?(ho=!0,fo=vh.createTextNode(""),new Sh(Jr).observe(fo,{characterData:!0}),rr=function(){fo.data=ho=!ho}):!OE&&Va&&Va.resolve?(Oa=Va.resolve(void 0),Oa.constructor=Va,Th=gh(Oa.then,Oa),rr=function(){Th(Jr)}):po?rr=function(){yh.nextTick(Jr)}:(lo=gh(lo,ir),rr=function(){lo(Jr)}),mo=function(i){Kr.head||rr(),Kr.add(i)});var Kr,Jr;Ih.exports=mo});var Ph=f((zL,xh)=>{"use strict";xh.exports=function(i,e){try{arguments.length===1?console.error(i):console.error(i,e)}catch{}}});var _a=f((KL,Ah)=>{"use strict";Ah.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var At=f((JL,kh)=>{"use strict";var NE=H();kh.exports=NE.Promise});var ar=f((XL,Lh)=>{"use strict";var FE=H(),Xr=At(),qE=U(),UE=An(),HE=Kn(),jE=J(),wh=Qn(),GE=Le(),bo=sn(),Rh=Xr&&Xr.prototype,WE=jE("species"),go=!1,$h=qE(FE.PromiseRejectionEvent),YE=UE("Promise",function(){var i=HE(Xr),e=i!==String(Xr);if(!e&&bo===66||GE&&!(Rh.catch&&Rh.finally))return!0;if(!bo||bo<51||!/native code/.test(i)){var t=new Xr(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[WE]=r,go=t.then(function(){})instanceof r,!go)return!0}return!e&&(wh==="BROWSER"||wh==="DENO")&&!$h});Lh.exports={CONSTRUCTOR:YE,REJECTION_EVENT:$h,SUBCLASSING:go}});var sr=f((ZL,Ch)=>{"use strict";var Mh=je(),QE=TypeError,zE=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw new QE("Bad Promise constructor");e=r,t=a}),this.resolve=Mh(e),this.reject=Mh(t)};Ch.exports.f=function(i){return new zE(i)}});var Xh=f(()=>{"use strict";var KE=Te(),JE=Le(),Ua=Ba(),st=H(),cr=me(),Dh=tr(),Bh=Un(),XE=Hr(),ZE=Dp(),ex=je(),qa=U(),tx=ve(),rx=Vp(),ix=Xn(),Fh=uo().set,Io=Eh(),ax=Ph(),sx=_a(),nx=co(),qh=En(),Ha=At(),Eo=ar(),Uh=sr(),ja="Promise",Hh=Eo.CONSTRUCTOR,ox=Eo.REJECTION_EVENT,ux=Eo.SUBCLASSING,So=qh.getterFor(ja),cx=qh.set,nr=Ha&&Ha.prototype,kt=Ha,Na=nr,jh=st.TypeError,vo=st.document,xo=st.process,yo=Uh.f,lx=yo,dx=!!(vo&&vo.createEvent&&st.dispatchEvent),Gh="unhandledrejection",px="rejectionhandled",Vh=0,Wh=1,hx=2,Po=1,Yh=2,Fa,Oh,fx,_h,Qh=function(i){var e;return tx(i)&&qa(e=i.then)?e:!1},zh=function(i,e){var t=e.value,r=e.state===Wh,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,c,u,d;try{a?(r||(e.rejection===Yh&&bx(e),e.rejection=Po),a===!0?c=t:(o&&o.enter(),c=a(t),o&&(o.exit(),d=!0)),c===i.promise?n(new jh("Promise-chain cycle")):(u=Qh(c))?cr(u,c,s,n):s(c)):n(t)}catch(l){o&&!d&&o.exit(),n(l)}},Kh=function(i,e){i.notified||(i.notified=!0,Io(function(){for(var t=i.reactions,r;r=t.get();)zh(r,i);i.notified=!1,e&&!i.rejection&&mx(i)}))},Jh=function(i,e,t){var r,a;dx?(r=vo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),st.dispatchEvent(r)):r={promise:e,reason:t},!ox&&(a=st["on"+i])?a(r):i===Gh&&ax("Unhandled promise rejection",t)},mx=function(i){cr(Fh,st,function(){var e=i.facade,t=i.value,r=Nh(i),a;if(r&&(a=sx(function(){Ua?xo.emit("unhandledRejection",t,e):Jh(Gh,e,t)}),i.rejection=Ua||Nh(i)?Yh:Po,a.error))throw a.value})},Nh=function(i){return i.rejection!==Po&&!i.parent},bx=function(i){cr(Fh,st,function(){var e=i.facade;Ua?xo.emit("rejectionHandled",e):Jh(px,e,i.value)})},or=function(i,e,t){return function(r){i(e,r,t)}},ur=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=hx,Kh(i,!0))},To=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw new jh("Promise can't be resolved itself");var r=Qh(e);r?Io(function(){var a={done:!1};try{cr(r,e,or(To,a,i),or(ur,a,i))}catch(s){ur(a,s,i)}}):(i.value=e,i.state=Wh,Kh(i,!1))}catch(a){ur({done:!1},a,i)}}};if(Hh&&(kt=function(e){rx(this,Na),ex(e),cr(Fa,this);var t=So(this);try{e(or(To,t),or(ur,t))}catch(r){ur(t,r)}},Na=kt.prototype,Fa=function(e){cx(this,{type:ja,done:!1,notified:!1,parent:!1,reactions:new nx,rejection:!1,state:Vh,value:void 0})},Fa.prototype=Dh(Na,"then",function(e,t){var r=So(this),a=yo(ix(this,kt));return r.parent=!0,a.ok=qa(e)?e:!0,a.fail=qa(t)&&t,a.domain=Ua?xo.domain:void 0,r.state===Vh?r.reactions.add(a):Io(function(){zh(a,r)}),a.promise}),Oh=function(){var i=new Fa,e=So(i);this.promise=i,this.resolve=or(To,e),this.reject=or(ur,e)},Uh.f=yo=function(i){return i===kt||i===fx?new Oh(i):lx(i)},!JE&&qa(Ha)&&nr!==Object.prototype)){_h=nr.then,ux||Dh(nr,"then",function(e,t){var r=this;return new kt(function(a,s){cr(_h,r,a,s)}).then(e,t)},{unsafe:!0});try{delete nr.constructor}catch{}Bh&&Bh(nr,Na)}KE({global:!0,constructor:!0,wrap:!0,forced:Hh},{Promise:kt});XE(kt,ja,!1,!0);ZE(ja)});var af=f((rM,rf)=>{"use strict";var gx=J(),ef=gx("iterator"),tf=!1;try{Zh=0,Ao={next:function(){return{done:!!Zh++}},return:function(){tf=!0}},Ao[ef]=function(){return this},Array.from(Ao,function(){throw 2})}catch{}var Zh,Ao;rf.exports=function(i,e){try{if(!e&&!tf)return!1}catch{return!1}var t=!1;try{var r={};r[ef]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch{}return t}});var ko=f((iM,sf)=>{"use strict";var Sx=At(),vx=af(),yx=ar().CONSTRUCTOR;sf.exports=yx||!vx(function(i){Sx.all(i).then(void 0,function(){})})});var nf=f(()=>{"use strict";var Tx=Te(),Ix=me(),Ex=je(),xx=sr(),Px=_a(),Ax=Ma(),kx=ko();Tx({target:"Promise",stat:!0,forced:kx},{all:function(e){var t=this,r=xx.f(t),a=r.resolve,s=r.reject,n=Px(function(){var o=Ex(t.resolve),c=[],u=0,d=1;Ax(e,function(l){var p=u++,h=!1;d++,Ix(o,t,l).then(function(m){h||(h=!0,c[p]=m,--d||a(c))},s)}),--d||a(c)});return n.error&&s(n.value),r.promise}})});var uf=f(()=>{"use strict";var wx=Te(),Rx=Le(),$x=ar().CONSTRUCTOR,Ro=At(),Lx=He(),Mx=U(),Cx=tr(),of=Ro&&Ro.prototype;wx({target:"Promise",proto:!0,forced:$x,real:!0},{catch:function(i){return this.then(void 0,i)}});!Rx&&Mx(Ro)&&(wo=Lx("Promise").prototype.catch,of.catch!==wo&&Cx(of,"catch",wo,{unsafe:!0}));var wo});var cf=f(()=>{"use strict";var Dx=Te(),Bx=me(),Vx=je(),Ox=sr(),_x=_a(),Nx=Ma(),Fx=ko();Dx({target:"Promise",stat:!0,forced:Fx},{race:function(e){var t=this,r=Ox.f(t),a=r.reject,s=_x(function(){var n=Vx(t.resolve);Nx(e,function(o){Bx(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var lf=f(()=>{"use strict";var qx=Te(),Ux=sr(),Hx=ar().CONSTRUCTOR;qx({target:"Promise",stat:!0,forced:Hx},{reject:function(e){var t=Ux.f(this),r=t.reject;return r(e),t.promise}})});var $o=f((pM,df)=>{"use strict";var jx=Ne(),Gx=ve(),Wx=sr();df.exports=function(i,e){if(jx(i),Gx(e)&&e.constructor===i)return e;var t=Wx.f(i),r=t.resolve;return r(e),t.promise}});var ff=f(()=>{"use strict";var Yx=Te(),Qx=He(),pf=Le(),zx=At(),hf=ar().CONSTRUCTOR,Kx=$o(),Jx=Qx("Promise"),Xx=pf&&!hf;Yx({target:"Promise",stat:!0,forced:pf||hf},{resolve:function(e){return Kx(Xx&&this===Jx?zx:this,e)}})});var mf=f(()=>{"use strict";Xh();nf();uf();cf();lf();ff()});var vf=f(()=>{"use strict";var Zx=Te(),eP=Le(),Ga=At(),tP=fe(),gf=He(),Sf=U(),rP=Xn(),bf=$o(),iP=tr(),Mo=Ga&&Ga.prototype,aP=!!Ga&&tP(function(){Mo.finally.call({then:function(){}},function(){})});Zx({target:"Promise",proto:!0,real:!0,forced:aP},{finally:function(i){var e=rP(this,gf("Promise")),t=Sf(i);return this.then(t?function(r){return bf(e,i()).then(function(){return r})}:i,t?function(r){return bf(e,i()).then(function(){throw r})}:i)}});!eP&&Sf(Ga)&&(Lo=gf("Promise").prototype.finally,Mo.finally!==Lo&&iP(Mo,"finally",Lo,{unsafe:!0}));var Lo});var Wa=f((vM,yf)=>{"use strict";var sP=He();yf.exports=sP});var If=f((yM,Tf)=>{"use strict";kp();mf();vf();var nP=Wa();Tf.exports=nP("Promise","finally")});var xf=f((TM,Ef)=>{"use strict";var oP=If();Ef.exports=oP});var Ya=f((IM,Pf)=>{"use strict";var uP=xf();Pf.exports=uP});var Kf=f(()=>{"use strict";var OP=Te(),_P=Vr(),NP=Ea(),FP=Ia(),qP=zs();OP({target:"Array",proto:!0},{at:function(e){var t=_P(this),r=NP(t),a=FP(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});qP("at")});var Xf=f((LC,Jf)=>{"use strict";Kf();var UP=Wa();Jf.exports=UP("Array","at")});var em=f((MC,Zf)=>{"use strict";var HP=Xf();Zf.exports=HP});var ri=f((CC,tm)=>{"use strict";var jP=em();tm.exports=jP});var Km=f(()=>{"use strict"});var Jm=f(()=>{"use strict"});var Zm=f((CV,Xm)=>{"use strict";var KA=ve(),JA=Yt(),XA=J(),ZA=XA("match");Xm.exports=function(i){var e;return KA(i)&&((e=i[ZA])!==void 0?!!e:JA(i)==="RegExp")}});var tb=f((DV,eb)=>{"use strict";var ek=Ur(),tk=String;eb.exports=function(i){if(ek(i)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return tk(i)}});var ib=f((BV,rb)=>{"use strict";var rk=Ne();rb.exports=function(){var i=rk(this),e="";return i.hasIndices&&(e+="d"),i.global&&(e+="g"),i.ignoreCase&&(e+="i"),i.multiline&&(e+="m"),i.dotAll&&(e+="s"),i.unicode&&(e+="u"),i.unicodeSets&&(e+="v"),i.sticky&&(e+="y"),e}});var nb=f((VV,sb)=>{"use strict";var ik=me(),ak=Me(),sk=Mr(),nk=ib(),ab=RegExp.prototype;sb.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in ab)&&!ak(i,"flags")&&sk(ab,i)?ik(nk,i):e}});var ub=f((OV,ob)=>{"use strict";var uu=ae(),ok=Vr(),uk=Math.floor,nu=uu("".charAt),ck=uu("".replace),ou=uu("".slice),lk=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,dk=/\$([$&'`]|\d{1,2})/g;ob.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,c=dk;return a!==void 0&&(a=ok(a),c=lk),ck(s,c,function(u,d){var l;switch(nu(d,0)){case"$":return"$";case"&":return i;case"`":return ou(e,0,t);case"'":return ou(e,n);case"<":l=a[ou(d,1,-1)];break;default:var p=+d;if(p===0)return u;if(p>o){var h=uk(p/10);return h===0?u:h<=o?r[h-1]===void 0?nu(d,1):r[h-1]+nu(d,1):u}l=r[p-1]}return l===void 0?"":l})}});var db=f(()=>{"use strict";var pk=Te(),hk=me(),lu=ae(),cb=$r(),fk=U(),mk=Qt(),bk=Zm(),vr=tb(),gk=Dr(),Sk=nb(),vk=ub(),yk=J(),Tk=Le(),Ik=yk("replace"),Ek=TypeError,cu=lu("".indexOf),xk=lu("".replace),lb=lu("".slice),Pk=Math.max;pk({target:"String",proto:!0},{replaceAll:function(e,t){var r=cb(this),a,s,n,o,c,u,d,l,p,h,m=0,b="";if(!mk(e)){if(a=bk(e),a&&(s=vr(cb(Sk(e))),!~cu(s,"g")))throw new Ek("`.replaceAll` does not allow non-global regexes");if(n=gk(e,Ik),n)return hk(n,e,r,t);if(Tk&&a)return xk(vr(r),e,t)}for(o=vr(r),c=vr(e),u=fk(t),u||(t=vr(t)),d=c.length,l=Pk(1,d),p=cu(o,c);p!==-1;)h=u?vr(t(c,p,o)):vk(c,o,p,[],void 0,t),b+=lb(o,m,p)+h,m=p+d,p=p+l>o.length?-1:cu(o,c,p+l);return m<o.length&&(b+=lb(o,m)),b}})});var hb=f((FV,pb)=>{"use strict";Km();Jm();db();var Ak=Wa();pb.exports=Ak("String","replaceAll")});var mb=f((qV,fb)=>{"use strict";var kk=hb();fb.exports=kk});var gb=f((UV,bb)=>{"use strict";var wk=mb();bb.exports=wk});var ju="2.0.108-dev.3ff897f5.0";var ie=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(ie||{}),at=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(at||{});var la=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(la||{}),Hs=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Hs||{});var js=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(js||{});import{assertNever as Ku,assertNonNullable as Qg,isNonNullable as da,ValueSubject as Gs,Subject as zg,Subscription as Kg,merge as Jg,observableFrom as Xg,fromEvent as Wu,map as Yu,tap as Qu,filterChanged as Zg,isNullable as Ws,ErrorCategory as zu}from"@vkontakte/videoplayer-shared";var Gu=i=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",i),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var pa=class{constructor(e){this.connection$=new Gs(void 0);this.castState$=new Gs("NOT_AVAILABLE");this.errorEvent$=new zg;this.realCastState$=new Gs("NOT_AVAILABLE");this.subscription=new Kg;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=da(window.chrome?.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},a||Gu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:zu.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){da(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Ws(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Ws(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(Wu(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{switch(a.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=r.getCurrentSession()?.getMediaSession()?.media?.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Ku(a.sessionState)}})).add(Jg(Wu(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Qu(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),Yu(a=>a.castState)),Xg([r.getCastState()])).pipe(Zg(),Yu(eS),Qu(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=da(this.connection$.getValue());if(s&&!n){let o=r.getCurrentSession();Qg(o);let c=o.getCastDevice(),u=o.getMediaSession()?.media?.contentId;(Ws(u)||u===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a==="CONNECTED"?da(this.connection$.getValue())?"CONNECTED":"AVAILABLE":a)}))}initializeCastApi(){let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:zu.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},eS=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return Ku(i)}};var mg=_e(Yn(),1);var Bf=_e(Ya(),1);import{assertNever as Af}from"@vkontakte/videoplayer-shared";var K=(i,e=0,t=0)=>{switch(t){case 0:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return i;let r=new URL(i);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(i);return!r.searchParams.get("offset_p")&&e===0?i:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:Af(t)}return i},Co=(i,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(i);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(i);return Number(t.searchParams.get("offset_p")??0)}default:Af(e)}};var I=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};import{isNonNullable as cP,Subject as Qa,merge as kf}from"@vkontakte/videoplayer-shared";var L=class{constructor(e){this.transitionStarted$=new Qa;this.transitionEnded$=new Qa;this.transitionUpdated$=new Qa;this.forceChanged$=new Qa;this.stateChangeStarted$=kf(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=kf(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,r=this.state;this.transition=void 0,this.prevState=r,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:r,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,r=this.state;r===e||cP(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as lP}from"@vkontakte/videoplayer-shared";var wf=i=>{switch(i){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return lP(i)}};import{assertNever as lr,assertNonNullable as wt,debounce as Rf,ErrorCategory as $f,fromEvent as Rt,isNonNullable as Lf,map as Mf,merge as Cf,observableFrom as dP,Subject as pP,Subscription as Do,timeout as hP,getHighestQuality as fP}from"@vkontakte/videoplayer-shared";var mP=5,bP=5,gP=500,Df=7e3,Zr=class{constructor(e){this.subscription=new Do;this.loadMediaTimeoutSubscription=new Do;this.videoState=new L("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(a?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:lr(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:lr(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:lr(e)}break}default:lr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(wf(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new Do;this.subscription.add(e),this.subscription.add(Cf(this.videoState.stateChangeStarted$.pipe(Mf(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(Mf(a=>`stateChangeEnded$ ${JSON.stringify(a)}`))).subscribe(a=>this.log({message:`[videoState] ${a}`})));let t=(a,s)=>this.subscription.add(a.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let a=new pP;e.add(a.pipe(Rf(gP)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Rt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>mP)&&a.next(o),s=o})),e.add(Rt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Rt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Rt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(Rt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{this.logRemoteEvent(a);let{remotePlayer:s}=this.params.connection,n=a.value,o=this.params.output.isBuffering$.getValue(),c=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==c&&this.params.output.isBuffering$.next(c),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<bP&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),I(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:lr(n)}}),t(Rt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(Rt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=Cf(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,dP(["init"])).pipe(Rf(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),I(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),I(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&I(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),r={volume:e.volume??t.volume,muted:e.muted??t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,r,a,s;switch(e){case"MPEG":{let u=t[e];wt(u);let d=fP(Object.keys(u));wt(d);let l=u[d];wt(l),r=l,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let u=t[e];wt(u),r=u.url,a="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let u=t[e];wt(u),r=u.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let u=t[e];wt(u),r=u.url,a="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=t[e];wt(u),r=K(u.url),a="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let u="Unsupported format for Chromecast",d=new Error(u);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:$f.VIDEO_PIPELINE,message:u,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return lr(e)}let n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??r,a);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:c}=this.params.meta;return Lf(o)&&(n.metadata.title=o),Lf(c)&&(n.metadata.subtitle=c),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((a,s)=>{this.loadMediaTimeoutSubscription.add(hP(Df).subscribe(()=>s(`timeout(${Df})`)))});(0,Bf.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},a=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${a}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:$f.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as Of}from"@vkontakte/videoplayer-shared";import{clearVideoElement as SP}from"@vkontakte/videoplayer-shared";var Vf=i=>{try{i.pause(),i.playbackRate=0,SP(i),i.remove()}catch(e){console.error(e)}};import{fromEvent as vP,Subscription as yP}from"@vkontakte/videoplayer-shared";var Bo=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},Vo=window.WeakMap?new WeakMap:new Bo,Oo=window.WeakMap?new WeakMap:new Map,TP=(i,e=20)=>{let t=0;return vP(i,"ratechange").subscribe(r=>{t++,t>=e&&(i.currentTime=i.currentTime,t=0)})},se=(i,{audioVideoSyncRate:e})=>{let t=i.querySelector("video"),r=!!t;t?Of(t):(t=document.createElement("video"),i.appendChild(t)),Vo.set(t,r);let a=new yP;return a.add(TP(t,e)),Oo.set(t,a),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},ne=i=>{Oo.get(i)?.unsubscribe(),Oo.delete(i);let t=Vo.get(i);Vo.delete(i),t?Of(i):Vf(i)};import{assertNonNullable as ei,isNonNullable as qe,isNullable as xP,fromEvent as dr,merge as _f,observableFrom as Nf,filterChanged as Ff,map as ti,Subject as qf,Subscription as PP,ValueSubject as AP,ErrorCategory as kP}from"@vkontakte/videoplayer-shared";import{isNonNullable as _o,isNullable as IP,Subscription as EP}from"@vkontakte/videoplayer-shared";var za=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),c=IP(a),u=new EP;return a&&u.add(a.subscribe(d=>{let l=i.getState();r(d,l)&&i.setState(d)},s)),r(o,n)||(t(n),c&&i.setState(n)),u.add(i.stateChangeStarted$.subscribe(d=>{t(d.to),c&&i.setState(d.to)},s)),u},Fe=(i,e,t)=>za(e,()=>i.loop,r=>{_o(r)&&(i.loop=r)},{onError:t}),oe=(i,e,t,r)=>za(e,()=>({muted:i.muted,volume:i.volume}),a=>{_o(a)&&(i.muted=a.muted,i.volume=a.volume)},{equal:(a,s)=>a===s||a?.muted===s?.muted&&a?.volume===s?.volume,changed$:t,onError:r}),Ie=(i,e,t,r)=>za(e,()=>i.playbackRate,a=>{_o(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),nt=za;var wP=i=>["__",i.language,i.label].join("|"),RP=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},No=class i{constructor(){this.available$=new qf;this.current$=new AP(void 0);this.error$=new qf;this.subscription=new PP;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let a=s=>{this.error$.next({id:"TextTracksManager",category:kP.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(nt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{qe(s)&&this.setInternal(s)},{equal:(s,n)=>qe(s)&&qe(n)&&s.length===n.length&&s.every(({id:o},c)=>o===n[c].id),changed$:this.available$.pipe(ti(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(nt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{qe(s)&&this.setExternal(s)},{equal:(s,n)=>qe(s)&&qe(n)&&s.length===n.length&&s.every(({id:o},c)=>o===n[c].id),changed$:this.available$.pipe(ti(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(nt(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:a})),this.subscription.add(nt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){ei(this.video);let{textTracks:e}=this.video;this.subscription.add(dr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(_f(dr(e,"addtrack"),dr(e,"removetrack"),Nf(["init"])).pipe(ti(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Ff((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add(_f(dr(e,"change"),Nf(["init"])).pipe(ti(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),ti(r=>r&&this.htmlTextTrackToITextTrack(r).id),Ff()).subscribe(this.current$));let t=r=>this.applyCueSettings(r.target?.activeCues??null);this.subscription.add(dr(e,"addtrack").subscribe(r=>{r.track?.addEventListener("cuechange",t);let a=s=>{let n=s.target?.cues??null;n&&n.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",a))};r.track?.addEventListener("cuechange",a)})),this.subscription.add(dr(e,"removetrack").subscribe(r=>{r.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let a=r;qe(t.align)&&(a.align=t.align),qe(t.position)&&(a.position=t.position),qe(t.size)&&(a.size=t.size),qe(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){ei(this.video);let t=[...this.video.textTracks];return e?t:t.filter(i.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:r}=e,a=e.id?e.id:wP(e),s=this.externalTracks.has(a),n=a.includes("auto");return s?{id:a,type:"external",isAuto:n,language:t,label:r,url:this.externalTracks.get(a)?.url}:{id:a,type:"internal",isAuto:n,language:t,label:r,url:this.internalTracks.get(a)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:a,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===a&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(a=>a.id===r)).forEach(([,r])=>this.detach(r))}select(e){ei(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(xP(e)||!RP(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){ei(this.video);let t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){ei(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Ee=No;var Ye=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var Uf=i=>{let e=i;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Fo=i=>{let e=Uf(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},Hf=i=>{let e=Uf(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};import{fromEvent as xe,map as ot,merge as Gf,filterChanged as LP,isNonNullable as Wf,Subject as MP,filter as Yf,mapTo as Qf,combine as CP,once as DP,ErrorCategory as BP,ValueSubject as zf,clientChecker as VP}from"@vkontakte/videoplayer-shared";var $P=3,jf=(i,e,t=$P)=>{let r=0,a=0;for(let s=0;s<i.length;s++){let n=i.start(s),o=i.end(s);if(n<=e&&e<=o){if(r=n,a=o,!t)return{from:r,to:a};for(let c=s-1;c>=0;c--)i.end(c)+t>=r&&(r=i.start(c));for(let c=s+1;c<i.length;c++)i.start(c)-t<=a&&(a=i.end(c))}}return{from:r,to:a}};var ue=i=>{let e=y=>xe(i,y).pipe(Qf(void 0)),r=Gf(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(y=>xe(i,y))).pipe(ot(y=>y.type==="ended"?i.readyState<2:i.readyState<3),LP()),a=Gf(xe(i,"progress"),xe(i,"timeupdate")).pipe(ot(()=>jf(i.buffered,i.currentTime))),s=VP.isSafari?CP({play:e("play").pipe(DP()),playing:e("playing")}).pipe(Qf(void 0)):e("playing"),n=xe(i,"volumechange").pipe(ot(()=>({muted:i.muted,volume:i.volume}))),o=xe(i,"ratechange").pipe(ot(()=>i.playbackRate)),c=xe(i,"error").pipe(Yf(()=>!!(i.error||i.played.length)),ot(()=>{let y=i.error;return{id:y?`MediaError#${y.code}`:"HtmlVideoError",category:BP.VIDEO_PIPELINE,message:y?y.message:"Error event from HTML video element",thrown:i.error??void 0}})),u=xe(i,"timeupdate").pipe(ot(()=>i.currentTime)),d=new MP,l=.3,p;u.subscribe(y=>{i.loop&&Wf(p)&&Wf(y)&&p>=i.duration-l&&y<=l&&d.next(p),p=y});let h=e("pause").pipe(Yf(()=>!i.error&&p!==i.duration)),m=xe(i,"enterpictureinpicture"),b=xe(i,"leavepictureinpicture"),g=new zf(Hf(i));m.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new zf(Fo(i));return xe(i,"fullscreenchange").pipe(ot(()=>Fo(i))).subscribe(v),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:d,error$:c,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:u,durationChange$:xe(i,"durationchange").pipe(ot(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v}};import{VideoQuality as ut}from"@vkontakte/videoplayer-shared";var ct=i=>{switch(i){case"mobile":return ut.Q_144P;case"lowest":return ut.Q_240P;case"low":return ut.Q_360P;case"sd":case"medium":return ut.Q_480P;case"hd":case"high":return ut.Q_720P;case"fullhd":case"full":return ut.Q_1080P;case"quadhd":case"quad":return ut.Q_1440P;case"ultrahd":case"ultra":return ut.Q_2160P}};var $t=_e(ri(),1);import{isNonNullable as ce,isNullable as Uo,now as cm,isHigher as Ho,isHigherOrEqual as sm,isInvariantQuality as nm,isLower as jo,isLowerOrEqual as om,videoSizeToQuality as GP,assertNotEmptyArray as lm,assertNonNullable as WP}from"@vkontakte/videoplayer-shared";var qo=!1,Qe={},rm=i=>{qo=i},im=()=>{Qe={}},am=i=>{i(Qe)},ii=(i,e)=>{qo&&(Qe.meta=Qe.meta??{},Qe.meta[i]=e)},X=class{constructor(e){this.name=e}next(e){if(!qo)return;Qe.series=Qe.series??{};let t=Qe.series[this.name]??[];t.push([Date.now(),e]),Qe.series[this.name]=t}};var YP=new X("best_bitrate"),dm=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;var Go=i=>(e,t)=>i*(Number(e.bitrate)-Number(t.bitrate)),ai=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=cm()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},pm='Assertion "ABR Tracks is empty array" failed',Ka=(i,e,t,r)=>{let a=[...e].sort(Go(1)),s=[...t].sort(Go(1)),n=s.filter(c=>ce(c.bitrate)&&ce(i.bitrate)?i.bitrate/c.bitrate>r:!0),o=(0,$t.default)(s,Math.round(s.length*a.indexOf(i)/(a.length+1)))??(0,$t.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,$t.default)(n,-1):(0,$t.default)(s,0)},um=i=>"quality"in i,hm=(i,e,t,r)=>{let a=t&&r&&r.history[t.id]&&cm()-r.history[t.id]<=i.trackCooldown&&(!r.last||t.id!==r.last.id);if(t?.id&&r&&!a&&r.recordSelection(t),a&&r?.last){let s=r.last;r?.recordSwitch(s);let n=um(s)?"video":"audio",o=um(s)?s.quality:s.bitrate;return e({message:`
7
+ [last ${n} selected] ${o}
8
+ `}),s}return r?.recordSwitch(t),t},lt=(i,{container:e,throughput:t,tuning:r,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:c,history:u,visible:d,droppedVideoMaxQualityLimit:l,abrLogger:p})=>{lm(i,pm);let h=r.usePixelRatio?window.devicePixelRatio??1:1,m=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*h*r.containerSizeFactor,height:e.height*h*r.containerSizeFactor},b=m&&GP(m),g=r.considerPlaybackRate&&ce(o)?o:1,v=i.filter(k=>!nm(k.quality)).sort((k,w)=>Ho(k.quality,w.quality)?-1:1),A=(0,$t.default)(v,-1)?.quality,y=(0,$t.default)(v,0)?.quality,S=Uo(a)||ce(a.min)&&ce(a.max)&&jo(a.max,a.min)||ce(a.min)&&y&&Ho(a.min,y)||ce(a.max)&&A&&jo(a.max,A),T=g*dm(n??.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),E={},O=v.filter(k=>{if(!(b?jo(k.quality,b):!0))return E[k.quality]="FitsContainer",!1;if(!(ce(t)&&isFinite(t)&&ce(k.bitrate)?t-s>=k.bitrate*T:!0))return E[k.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&ce(r.minBufferToSwitchUp)&&c&&!nm(c.quality)&&(n??0)<r.minBufferToSwitchUp&&Ho(k.quality,c.quality))return E[k.quality]="Buffer",!1;if(!!l&&sm(k.quality,l))return E[k.quality]="DroppedFramesLimit",!1;let te=S||(Uo(a.max)||om(k.quality,a.max))&&(Uo(a.min)||sm(k.quality,a.min)),x=ce(d)&&!d?om(k.quality,r.backgroundVideoQualityLimit):!0;return!te||!x?(E[k.quality]="FitsQualityLimits",!1):!0})[0];O&&O.bitrate&&YP.next(O.bitrate);let N=O??v[Math.ceil((v.length-1)/2)]??i[0];return N.quality!==u?.last?.quality&&p({message:`
9
+ [VIDEO TRACKS ABR]
10
+ [available video tracks]
11
+ ${i.map(k=>`{ id: ${k.id}, quality: ${k.quality}, bitrate: ${k.bitrate} }`).join(`
9
12
  `)}
10
13
 
11
14
  [tuning]
12
- ${Object.entries(r??{}).map(([P,B])=>`${P}: ${B}`).join(`
15
+ ${Object.entries(r??{}).map(([k,w])=>`${k}: ${w}`).join(`
13
16
  `)}
14
17
 
15
18
  [limit params]
16
- containerQualityLimit: ${m},
19
+ containerQualityLimit: ${b},
17
20
  throughput: ${t},
18
21
  reserve: ${s},
19
22
  playbackRate: ${o},
20
- playbackRateFactor: ${b},
23
+ playbackRateFactor: ${g},
21
24
  forwardBufferHealth: ${n},
22
- bitrateFactor: ${g},
25
+ bitrateFactor: ${T},
23
26
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
24
- droppedVideoMaxQualityLimit: ${c},
25
- limitsAreInvalid: ${T},
27
+ droppedVideoMaxQualityLimit: ${l},
28
+ limitsAreInvalid: ${S},
26
29
  maxQualityLimit: ${a?.max},
27
30
  minQualityLimit: ${a?.min},
28
31
 
29
- [limited tracks]
30
- ${Object.entries(y).map(([P,B])=>`${P}: ${B}`).join(`
32
+ [limited video tracks]
33
+ ${Object.entries(E).map(([k,w])=>`${k}: ${w}`).join(`
31
34
  `)||"All tracks are available"}
32
35
 
33
- [best track] ${E?.quality}
34
- [selected track] ${k?.quality}
35
- `});let D=k&&u&&u.history[k.id]&&tm()-u.history[k.id]<=r.trackCooldown&&(!u.last||k.id!==u.last.id);if(k?.id&&u&&!D&&u.recordSelection(k),D&&u?.last){let P=u.last;return u?.recordSwitch(P),d({message:`
36
- [last selected] ${P?.quality}
37
- `}),P}return u?.recordSwitch(k),k},ut=VP;var Y=i=>new URL(i).hostname;import{assertNever as om,assertNonNullable as um,combine as iA,debounce as aA,ErrorCategory as lm,filter as cm,filterChanged as sA,isNonNullable as jo,map as Qa,merge as dm,observableFrom as nA,once as oA,Subscription as uA,ValueSubject as Go,videoQualityToHeight as lA,videoSizeToQuality as cA}from"@vkontakte/videoplayer-shared";var rm=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"))},ne=async i=>{let e=i.muted;try{await i.play()}catch(t){if(!rm(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{await i.play()}catch(r){return rm(r)&&(i.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as Ga,isNullable as FP,assertNonNullable as ti}from"@vkontakte/videoplayer-shared";import{isNonNullable as im,assertNonNullable as ja,now as _P}from"@vkontakte/videoplayer-shared";function W(){return _P()}function Fo(i){return W()-i}function qo(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 am(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function ur(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,l=!1,u=0,c,d,p=!1,h="arraybuffer",m=7e3,b=2e3,S=()=>{if(l)return;ja(c);let O=Fo(c),G;if(O<b){G=b-O,setTimeout(S,G);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new a,$()},v=O=>(s=O,B),w=O=>(d=O,B),T=()=>(h="json",B),g=()=>{if(!l){if(--u>=0){S(),r&&r();return}l=!0,d&&d(),t&&t()}},y=O=>(p=O,B),$=()=>{c=W(),n=new a,n.open("get",i);let O=0,G,Pe=0,le=()=>(ja(c),Math.max(c,Math.max(G||0,Pe||0)));if(s&&n.addEventListener("progress",A=>{let R=W();s.updateChunk&&A.loaded>O&&(s.updateChunk(le(),A.loaded-O),O=A.loaded,G=R)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>g())),n.addEventListener("load",()=>{if(l)return;ja(n);let A=n.status;if(A>=200&&A<300){if(n.response.byteLength&&s){let R=n.response.byteLength-O;R&&s.updateChunk&&s.updateChunk(le(),R)}n.responseType==="json"&&!Object.values(n.response).length?g():(d&&d(),e(n.response))}else g()}),n.addEventListener("error",()=>{g()}),p){let A=()=>{ja(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Pe=W(),n.removeEventListener("readystatechange",A))};n.addEventListener("readystatechange",A)}return n.responseType=h,n.send(),B},B={withBitrateReporting:v,withParallel:y,withJSONResponse:T,withRetryCount:O=>(u=O,B),withRetryInterval:(O,G)=>(im(O)&&(b=O),im(G)&&(m=G),B),withTimeout:O=>(o=O,B),withFinally:w,send:$,abort:()=>{n&&(n.abort(),n=void 0),l=!0,d&&d()}};return B}var Zr=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 ei=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=W(),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=W()-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=ur(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=W()}_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=W();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 Ya=1e4,Uo=3;var qP=6e4,UP=10,HP=1,jP=500,ri=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 Zr(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=qo(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=qo(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||Ga(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=()=>{am(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 ei(Uo,Ya,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:a}=this.params,s=!1,n=null,o=null,l=null,u=null,c=!1,d=()=>{let g=s&&(!c||c===this.rep);return g||t("Not running!"),g},p=(g,y,$)=>{l&&l.abort(),l=ur(this.urlResolver.resolve(g,!1),y,$,()=>this._retryCallback()).withTimeout(Ya).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Uo).withFinally(()=>{l=null}).send()},h=(g,y,$)=>{ti(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(g,!1),y,$,()=>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 $=W()-1e4,E=0;for(let D=0;D<this.bufferStates.length;D++){let P=this.bufferStates[D];g=Math.min(g,P.buf),P.ts<$&&E++}this.bufferStates.splice(0,E),t(`update playback rate; minBuffer=${g} drop=${E} jitter=${this.sourceJitter}`);let k=g-HP;this.sourceJitter>=0?k-=this.sourceJitter/2:this.sourceJitter-=1,k>3?m(1.15):k>1?m(1.1):k>.3?m(1.05):m(1)}},v=g=>{let y,$=()=>y&&y.start?y.start.length:0,E=A=>y.start[A]/1e3,k=A=>y.dur[A]/1e3,D=A=>y.fragIndex+A,P=(A,R)=>({chunkIdx:D(A),startTS:E(A),dur:k(A),discontinuity:R}),B=()=>{let A=0;if(y&&y.dur){let R=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,H=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Q=R;this.sourceJitter>1&&(Q+=this.sourceJitter-1);let ce=y.dur.length-1;for(;ce>=0&&(Q-=y.dur[ce],!(Q<=0));--ce);A=Math.min(ce,y.dur.length-1-H),A=Math.max(A,0)}return P(A,!0)},O=A=>{let R=$();if(!(R<=0)){if(Ga(A)){for(let H=0;H<R;H++)if(E(H)>A)return P(H)}return B()}},G=A=>{let R=$(),H=A?A.chunkIdx+1:0,Q=H-y.fragIndex;if(!(R<=0)){if(!A||Q<0||Q-R>UP)return t(`Resync: offset=${Q} bChunks=${R} chunk=`+JSON.stringify(A)),B();if(!(Q>=R))return P(H-y.fragIndex,!1)}},Pe=(A,R,H)=>{u&&u.abort(),u=ur(this.urlResolver.resolve(A,!0,this.lowLatency),R,H,()=>this._retryCallback()).withTimeout(Ya).withRetryCount(Uo).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(A,R)=>{Pe(g,H=>{if(!d())return;y=H;let Q=!!y.lowLatency;Q!==this.lowLatency&&b(Q);let ce=0;for(let De=0;De<y.dur.length;++De)ce+=y.dur[De];ce>0&&(ti(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ce/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,A(O(R))},()=>this._handleNetworkError())},nextChunk:G}},w=()=>{s=!1,o&&o.abort(),l&&l.abort(),u&&u.abort(),ti(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:g=>{let{videoElement:y,logger:$}=this.params,E=v(e.jidxUrl),k,D,P,B,O=0,G,Pe,le,A=()=>{G&&(clearTimeout(G),G=void 0);let V=Math.max(jP,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),j=O+V,Z=W(),Ae=Math.min(1e4,j-Z);O=Z;let Xe=()=>{u||d()&&E.seek(()=>{d()&&(O=W(),R(),A())})};Ae>0?G=window.setTimeout(()=>{this.paused?A():Xe()},Ae):Xe()},R=()=>{let V;for(;V=E.nextChunk(B);)B=V,_t(V);let j=E.nextChunk(P);if(j){if(P&&j.discontinuity){$("Detected discontinuity; restarting playback"),this.paused?A():(w(),this._initPlayerWith(e));return}De(j)}else A()},H=(V,j)=>{if(!d()||!this.sourceBuffer)return;let Z,Ae,Xe,Nt=Ze=>{window.setTimeout(()=>{d()&&H(V,j)},Ze)};if(this.sourceBuffer.updating)$("Source buffer is updating; delaying appendBuffer"),Nt(100);else{let Ze=W(),Ft=y.currentTime;!this.paused&&y.buffered.length>1&&Pe===Ft&&Ze-le>500&&($("Stall suspected; trying to fix"),this._fixupStall()),Pe!==Ft&&(Pe=Ft,le=Ze);let Tr=this._getBufferSizeSec();if(Tr>30)$(`Buffered ${Tr} seconds; delaying appendBuffer`),Nt(2e3);else try{this.sourceBuffer.appendBuffer(V),this.videoPlayStarted?(this.bufferStates.push({ts:Ze,buf:Tr}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),j&&j()}catch(Xi){if(Xi.name==="QuotaExceededError")$("QuotaExceededError; delaying appendBuffer"),Xe=this.sourceBuffer.buffered.length,Xe!==0&&(Z=this.sourceBuffer.buffered.start(0),Ae=Ft,Ae-Z>4&&this.sourceBuffer.remove(Z,Ae-3)),Nt(1e3);else throw Xi}}},Q=()=>{D&&k&&($([`Appending chunk, sz=${D.byteLength}:`,JSON.stringify(P)]),H(D,function(){D=null,R()}))},ce=V=>e.fragUrlTemplate.replace("%%id%%",V.chunkIdx),De=V=>{d()&&h(ce(V),(j,Z)=>{if(d()){if(Z/=1e3,D=j,P=V,n=V.startTS,Z){let Ae=Math.min(10,V.dur/Z);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ae:Ae}Q()}},()=>this._handleNetworkError())},_t=V=>{d()&&(ti(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ce(V),!1)))},ht=V=>{d()&&(e.cachedHeader=V,H(V,()=>{k=!0,Q()}))};s=!0,E.seek(V=>{if(d()){if(O=W(),!V){A();return}B=V,!FP(g)||V.startTS>g?De(V):(P=V,R())}},g),e.cachedHeader?ht(e.cachedHeader):p(e.headerUrl,ht,()=>this._handleNetworkError())},stop:w,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),Ga(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,ti(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Ga(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),m=d/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(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let m=W();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 d=s.get();if(d&&o&&this.autoQuality){if(l&&d>o&&Fo(n)<3e4)return;r(d)}l=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&u(),h},notifySwitch:d=>{let p=W();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=ur(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Ya).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;ne(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))},qP))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as GP,filter as sm,fromEvent as YP,interval as WP,isHigher as QP,isInvariantQuality as zP,isLower as KP,merge as JP,Subject as nm,Subscription as XP}from"@vkontakte/videoplayer-shared";var Ho=class{constructor(){this.onDroopedVideoFramesLimit$=new nm;this.subscription=new XP;this.playing=!1;this.tracks=[];this.forceChecker$=new nm;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&&!zP(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&&QP(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(YP(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=WP(this.droppedFramesChecker.checkTime).pipe(sm(()=>this.playing),sm(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(GP(this.droppedFramesChecker.checkTime)),r=JP(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])=>KP(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}},Wa=Ho;import{map as ZP,Observable as eA}from"@vkontakte/videoplayer-shared";import{fromEvent as tA}from"@vkontakte/videoplayer-shared";var ii=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var rA=(i,e)=>new eA(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(l=>t.next(l.isIntersecting||ii()))},{...r,...e});a.observe(i);let s=tA(document,"visibilitychange").pipe(ZP(n=>!document.hidden||ii())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),Ie=rA;var dA=["paused","playing","ready"],pA=["paused","playing","ready"],ai=class{constructor(e){this.subscription=new uA;this.videoState=new L("stopped");this.representations$=new Go([]);this.textTracksManager=new ye;this.droppedFramesManager=new Wa;this.maxSeekBackTime$=new Go(1/0);this.zeroTime$=new Go(void 0);this.liveOffset=new Ge;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:lm.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=nt(a.name)??cA(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),jo(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(pA.includes(e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&dA.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(z(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(z(this.params.source.url,l))}return;default:return om(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:lm.WTF,message:"DashLiveProvider internal logic error",thrown:a})};dm(this.videoState.stateChangeStarted$.pipe(Qa(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Qa(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=re(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Y(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=se(this.video);this.subscription.add(this.representations$.pipe(Qa(a=>a.map(({track:s})=>s)),cm(a=>!!a.length),oA()).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(sA(),Qa(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(iA({zeroTime:this.zeroTime$.pipe(cm(jo)),position:r.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(_e(this.video,this.params.desiredState.isLooped,t)).add(ae(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(ve(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(Ie(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&lA(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 om(a.to)}},t)).add(dm(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,nA(["init"])).pipe(aA(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),ie(this.video)}createLiveDashPlayer(){let e=new ri({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&&jo(t)?t:ut(e.map(({track:u})=>u),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=a?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),l&&this.setAutoQuality(r),n||l||s!==o){let u=e.find(({track:c})=>c.id===s)?.representation;um(u,"Representations missing"),this.dash.startPlay(u,r)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:r})=>r.id===e.id)?.representation;um(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(z(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var pm=ai;var We=(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 Bw,assertNonNullable as Ow,debounce as Vw,ErrorCategory as yu,filter as kb,filterChanged as Tu,fromEvent as _w,isLowerOrEqual as Rb,isNonNullable as Nw,isInvariantQuality as Fw,map as Lb,merge as fs,observableFrom as qw,observeElementSize as Uw,once as $b,Subscription as Hw,ValueSubject as jw}from"@vkontakte/videoplayer-shared";var za=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}},lr=class extends za{constructor(){super(),this.listeners||za.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)}},si=class{constructor(){Object.defineProperty(this,"signal",{value:new lr,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&&(si.prototype[Symbol.toStringTag]="AbortController",lr.prototype[Symbol.toStringTag]="AbortSignal");function Ka(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 Yo(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!Ka({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||a)&&(s=function(u,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(u,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(l,u)=>{let c=s&&s.prototype.isPrototypeOf(l)?l.signal:u?u.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch{d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,m)=>{c.addEventListener("abort",()=>m(d),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([p,n(l,u)])}return n(l,u)},Request:s}}var ni=Ka({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),hm=ni?Yo({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Qe=ni?hm.fetch:window.fetch,GD=ni?hm.Request:window.Request,ze=ni?si:window.AbortController,YD=ni?lr:window.AbortSignal;var bm=Oe(Jr(),1);var Ke=()=>window.ManagedMediaSource||window.MediaSource,Ja=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),fm=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),mm=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as ts,clientChecker as Za}from"@vkontakte/videoplayer-shared";var es=document.createElement("video"),mA='video/mp4; codecs="avc1.42000a,mp4a.40.2"',bA='video/mp4; codecs="hev1.1.6.L93.B0"',Sm='video/webm; codecs="vp09.00.10.08"',gm='video/webm; codecs="av01.0.00M.08"',SA='audio/mp4; codecs="mp4a.40.2"',gA='audio/webm; codecs="opus"',At={mms:Ja(),mse:fm(),hls:!!(es.canPlayType?.("application/x-mpegurl")||es.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},oe={mp4:!!es.canPlayType?.("video/mp4"),webm:!!es.canPlayType?.("video/webm"),cmaf:!0},ue={h264:!!Ke()?.isTypeSupported?.(mA),h265:!!Ke()?.isTypeSupported?.(bA),vp9:!!Ke()?.isTypeSupported?.(Sm),av1:!!Ke()?.isTypeSupported?.(gm),aac:!!Ke()?.isTypeSupported?.(SA),opus:!!Ke()?.isTypeSupported?.(gA)},cr=(ue.h264||ue.h265)&&ue.aac,wt,vA=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:gm}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:Sm}})]);wt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{vA()}catch(i){console.error(i)}var dr=At.hls&&oe.mp4,vm=()=>Object.keys(ue).filter(i=>ue[i]),ym=(i,e=!1,t=!1)=>{let r=At.mse||At.mms&&t;return i.filter(a=>{switch(a){case"DASH_SEP":return r&&oe.mp4&&cr;case"DASH_WEBM":return r&&oe.webm&&ue.vp9&&ue.opus;case"DASH_WEBM_AV1":return r&&oe.webm&&ue.av1&&ue.opus;case"DASH_STREAMS":return r&&(oe.mp4&&cr||oe.webm&&(ue.vp9||ue.av1)&&(ue.opus||ue.aac));case"DASH_LIVE":return At.mse&&oe.mp4&&cr;case"DASH_LIVE_CMAF":return r&&oe.mp4&&cr&&oe.cmaf;case"DASH_ONDEMAND":return r&&oe.mp4&&cr;case"HLS":case"HLS_ONDEMAND":return dr||e&&At.mse&&oe.mp4&&cr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return dr;case"MPEG":return oe.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return At.webrtc&&At.ws&&ue.h264&&(oe.mp4||oe.webm);default:return ts(a)}})},Xa=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 wt?wt[t].smooth?[t,e]:wt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return wt?wt[t].powerEfficient?[t,e]:wt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:ts(i)}return[e,t]},Tm=({webmCodec:i,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...Xa(i),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],a=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Za.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",...Xa(i),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Xa(i),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Xa(i),...a,"HLS","HLS_ONDEMAND"];default:ts(e)}return dr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Im=({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=Za.isMac&&Za.isSafari;if(Za.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:ts(i)}else dr&&!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"]},Wo=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Em=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,bm.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return i.values().next().value.split(".").at(0)}};import{ErrorCategory as oi}from"@vkontakte/videoplayer-shared";var xm=i=>{if(!i)return{id:"EmptyResponse",category:oi.PARSER,message:"Empty response"};if(i.length<=2&&i.match(/^\d+$/))return{id:`UVError#${i}`,category:oi.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:oi.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:oi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:oi.PARSER,message:"Response is valid XML, but parser failed"}};var ui=(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 Su,assertNonNullable as Ot,combine as us,ErrorCategory as ct,filter as ls,filterChanged as Tb,fromEvent as gr,interval as gu,isNonNullable as Ib,map as vu,merge as vr,Subject as Eb,Subscription as xb,tap as kw,throttle as Rw,clientChecker as Lw,ValueSubject as X}from"@vkontakte/videoplayer-shared";var Sr=Oe(Jr(),1);var yA=(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)},TA=i=>window.clearTimeout(i),Pm=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Qo=Pm?yA:window.requestIdleCallback,n0=Pm?TA:window.cancelIdleCallback;var fb=Oe(Fa(),1);import{assertNever as IA,ErrorCategory as Am,clientChecker as zo,Subject as wm}from"@vkontakte/videoplayer-shared";var EA=16,km=!1;try{km=zo.isSafari&&!!zo.macVersion&&zo.macVersion<=EA}catch(i){console.error(i)}var Ko=class{constructor(e){this.bufferFull$=new wm;this.error$=new wm;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:Am.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;km&&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:Am.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:IA(t)}}},Rm=Ko;var Jo=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 br,assertNonNullable as Fe,ErrorCategory as Ct,fromEvent as cu,getExponentialDelay as du,isNonNullable as pu,isNullable as Ee,once as yw,Subject as Tw,Subscription as Iw,ValueSubject as $i}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 li=class extends _{};var ci=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 di=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var pi=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var hi=class extends _{constructor(e,t){super(e,t),this.data=this.content}};var U=class extends _{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var kt=class extends U{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let a=this.readUint32(),s=a>>>31,n=a<<1>>>1,o=this.readUint32();a=this.readUint32();let l=a>>>28,u=a<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:l,SAPDeltaTime:u})}}};var fi=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var mi=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var bi=class extends U{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Si=class extends U{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var gi=class extends U{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var vi=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var yi=class extends U{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var Ti=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ii=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ei=class extends U{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var xi=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Pi=class extends U{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Ai=class extends U{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var wi=class extends U{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let a=0;a<this.sampleCount;a++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var PA={ftyp:ci,moov:di,moof:pi,mdat:hi,sidx:kt,trak:fi,mdia:vi,mfhd:Ei,tkhd:yi,traf:xi,tfhd:Pi,tfdt:Ai,trun:wi,minf:Ti,sv3d:mi,st3d:bi,prhd:Si,proj:Ii,equi:gi,uuid:li,unknown:pr},Rt=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=PA[e];return r?new r(t,new i):new pr(t,new i)}};var hr=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 wA=new TextDecoder("ascii"),kA=i=>wA.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",RA=i=>{let e=new kt(i,new Rt),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})},LA=(i,e)=>{let r=new Rt().parse(i),a=new hr(r),s=a.findAll("moof"),n=e?a.findAll("uuid"):a.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],l=n[n.length-1],u=o.source.byteOffset,d=l.source.byteOffset-o.source.byteOffset+l.size;return new DataView(i.buffer,u,d)},$A=(i,e)=>{let r=new Rt().parse(i),s=new hr(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),l=s[s.length-1].children.find(d=>d.type==="trun"),u=0;return l.sampleDuration.length?u=l.sampleDuration.reduce((d,p)=>d+p,0):u=n.defaultSampleDuration*l.sampleCount,(Number(o.baseMediaDecodeTime)+u)/e*1e3},MA=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 Rt().parse(i),a=new hr(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},Lm={validateData:kA,parseInit:MA,getIndexRange:()=>{},parseSegments:RA,parseFeedableSegmentChunk:LA,getSegmentEndTime:$A};import{assertNonNullable as Zo,isNonNullable as Dm,isNullable as DA}from"@vkontakte/videoplayer-shared";import{assertNever as CA}from"@vkontakte/videoplayer-shared";var $m={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"}},Mm=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=ki(i,t),a=r in $m,s=a?$m[r].type:"binary",n=i.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let l=new DataView(i.buffer,i.byteOffset+t+1,o-1),u=n&255>>o,c=ki(l),d=u*2**((o-1)*8)+c,p=t+o,h;return p+d>i.byteLength?h=new DataView(i.buffer,i.byteOffset+p):h=new DataView(i.buffer,i.byteOffset+p,d),{tag:a?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},ki=(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 ki(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:CA(e)}},Lt=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=Mm(r);if(!e(a))return;a.type==="master"&&Lt(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},Cm=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=Mm(i);return Lt(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 Bm=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],BA=[231,22612,22743,167,171,163,160,175],OA=i=>{let e,t,r,a,s=!1,n=!1,o=!1,l,u,c=!1,d=0;return Lt(i,({tag:p,type:h,value:m,valueSize:b})=>{if(p===21419){let S=Me(m,h);u=ki(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?Lt(m,({tag:S,type:v,value:w})=>S===30321?(c=Me(w,v)===1,!1):!0):s&&n&&Bm.includes(p)&&(o=!0),!o}),Zo(e,"Failed to parse webm Segment start"),Zo(t,"Failed to parse webm Segment end"),Zo(a,"Failed to parse webm Segment duration"),r=r??1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(a/1e9*r*1e3),cuesSeekPosition:l,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},VA=i=>{if(DA(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},_A=(i,e)=>{let t=!1,r=!1,a=o=>Dm(o.time)&&Dm(o.position),s=[],n;return Lt(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&&Bm.includes(o)&&(r=!0)}return!(t&&r)}),n&&a(n)&&s.push(n),s.map((o,l)=>{let{time:u,position:c}=o,d=s[l+1];return{status:"none",time:{from:u,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},NA=i=>{let e=0,t=!1;try{Lt(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):BA.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},Om={validateData:Cm,parseInit:OA,getIndexRange:VA,parseSegments:_A,parseFeedableSegmentChunk:NA};var fr=i=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(i);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return Om;case"mp4":return Lm}}throw new ReferenceError(`Unsupported mime type ${i}`)};var nu=Oe(ab(),1);var su=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 nb,isNullable as ob}from"@vkontakte/videoplayer-shared";var sb=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var ub=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},$t=(i,e)=>{let t=i;t=(0,nu.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,nu.default)(t,n,(o,l)=>ob(s)?o:ob(l)?s:s.padStart(parseInt(l,10),"0"))}return t},cb=(i,e)=>{let r=new DOMParser().parseFromString(i,"application/xml"),a={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=s.querySelector("BaseURL")?.textContent?.trim()??"",l=n.children,u=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),d=c?new Date(c).getTime():void 0,p,h=s.getAttribute("mediaPresentationDuration"),m=n.getAttribute("duration"),S=s.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=ub(h);else if(m){let g=ub(m);nb(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),$=g.getAttribute("mimeType")??"",E=g.getAttribute("codecs")??"",k=g.getAttribute("contentType")??$?.split("/")[0],D=g.getAttribute("profiles")?.split(",")??[],P=g.getAttribute("lang")??void 0,B=g.querySelector("Label")?.textContent?.trim()??void 0,O=g.querySelectorAll("Representation"),G=g.querySelector("SegmentTemplate"),Pe=g.querySelector("Role")?.getAttribute("value")??void 0,le=k,A={id:y,language:P,isDefault:Pe==="main",label:B,codecs:E,hdr:le==="video"&&su(E),mime:$,representations:[]};for(let R of O){let H=R.getAttribute("lang")??void 0,Q=R.getAttribute("label")??void 0,ce=R.querySelector("BaseURL")?.textContent?.trim()??"",De=new URL(ce||o,e).toString(),_t=R.getAttribute("mimeType")??$,ht=R.getAttribute("codecs")??E??"",V;if(k==="text"){let j=R.getAttribute("id")||"",Z=j.includes("_auto");V={id:j,isAuto:Z,kind:"text",url:De}}else{let j=R.getAttribute("contentType")??_t?.split("/")[0]??k,Z=g.getAttribute("profiles")?.split(",")??[],Ae=parseInt(R.getAttribute("width")??"",10),Xe=parseInt(R.getAttribute("height")??"",10),Nt=parseInt(R.getAttribute("bandwidth")??"",10)/1e3,Ze=R.getAttribute("frameRate")??"",Ft=R.getAttribute("quality")??void 0,Tr=Ze?sb(Ze):void 0,Xi=R.getAttribute("id")??"id"+(v++).toString(10),yS=j==="video"?`${Xe}p`:j==="audio"?`${Nt}Kbps`:ht,TS=`${Xi}@${yS}`,IS=[...w,...D,...Z],Ls,ES=R.querySelector("SegmentBase"),ft=R.querySelector("SegmentTemplate")??G;if(ES){let mt=R.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[bt,Ms]=mt.split("-").map(qt=>parseInt(qt,10)),et={from:bt,to:Ms},Ir=R.querySelector("SegmentBase")?.getAttribute("indexRange"),[Cs,Zi]=Ir?Ir.split("-").map(qt=>parseInt(qt,10)):[],Er=Ir?{from:Cs,to:Zi}:void 0;Ls={type:"byteRange",url:De,initRange:et,indexRange:Er}}else if(ft){let mt={representationId:R.getAttribute("id")??void 0,bandwidth:R.getAttribute("bandwidth")??void 0},bt=parseInt(ft.getAttribute("timescale")??"",10),Ms=ft.getAttribute("initialization")??"",et=ft.getAttribute("media"),Ir=parseInt(ft.getAttribute("startNumber")??"",10)??1,Cs=$t(Ms,mt);if(!et)throw new ReferenceError("No media attribute in SegmentTemplate");let Zi=ft.querySelectorAll("SegmentTimeline S")??[],Er=[],qt=0,Ds="",Bs=0;if(Zi.length){let ea=Ir,we=0;for(let Ut of Zi){let Be=parseInt(Ut.getAttribute("d")??"",10),St=parseInt(Ut.getAttribute("r")??"",10)||0,ta=parseInt(Ut.getAttribute("t")??"",10);we=Number.isFinite(ta)?ta:we;let Os=Be/bt*1e3,PS=we/bt*1e3;for(let ra=0;ra<St+1;ra++){let AS=$t(et,{...mt,segmentNumber:ea.toString(10),segmentTime:(we+ra*Be).toString(10)}),Ou=(PS??0)+ra*Os,wS=Ou+Os;ea++,Er.push({time:{from:Ou,to:wS},url:AS})}we+=(St+1)*Be,qt+=(St+1)*Os}Bs=we/bt*1e3,Ds=$t(et,{...mt,segmentNumber:ea.toString(10),segmentTime:we.toString(10)})}else if(nb(p)){let we=parseInt(ft.getAttribute("duration")??"",10)/bt*1e3,Ut=Math.ceil(p/we),Be=0;for(let St=1;St<Ut;St++){let ta=$t(et,{...mt,segmentNumber:St.toString(10),segmentTime:Be.toString(10)});Er.push({time:{from:Be,to:Be+we},url:ta}),Be+=we}Bs=Be,Ds=$t(et,{...mt,segmentNumber:Ut.toString(10),segmentTime:Be.toString(10)})}let xS={time:{from:Bs,to:1/0},url:Ds};Ls={type:"template",baseUrl:De,segmentTemplateUrl:et,initUrl:Cs,totalSegmentsDurationMs:qt,segments:Er,nextSegmentBeyondManifest:xS,timescale:bt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!j||!_t)continue;let $s={video:"video",audio:"audio",text:"text"}[j];if(!$s)continue;le||=$s,V={id:TS,kind:$s,segmentReference:Ls,profiles:IS,duration:p,bitrate:Nt,mime:_t,codecs:ht,width:Ae,height:Xe,fps:Tr,quality:Ft}}A.language||=H,A.label||=Q,A.mime||=_t,A.codecs||=ht,A.hdr||=le==="video"&&su(ht),A.representations.push(V)}le&&a[le].push(A)}return{dynamic:u,liveAvailabilityStartTime:d,duration:p,streams:a}};var Ri=Oe(Jr(),1);import{videoSizeToQuality as vw}from"@vkontakte/videoplayer-shared";var db=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s})=>{let n=(s?nt(s):void 0)??vw({width:e,height:t});return n&&{id:i,quality:n,bitrate:r,size:{width:e,height:t},fps:a}},pb=({id:i,bitrate:e})=>({id:i,bitrate:e}),rs=(i,e,t)=>{let r=e.indexOf(i);return(0,Ri.default)(t,Math.round(t.length*r/e.length))??(0,Ri.default)(t,-1)},hb=({language:i,label:e},{id:t,url:r,isAuto:a})=>({id:t,url:r,isAuto:a,type:"internal",language:i,label:e}),uu=({id:i,language:e,label:t,codecs:r,isDefault:a})=>({id:i,language:e,label:t,codec:(0,Ri.default)(r.split("."),0),isDefault:a}),lu=({id:i,language:e,label:t,hdr:r,codecs:a})=>({id:i,language:e,hdr:r,label:t,codec:(0,Ri.default)(a.split("."),0)}),is=i=>"url"in i,Mt=i=>i.type==="template",Li=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var Mi=class{constructor(e,t,r,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:l=!1,manifest:u}){this.currentSegmentLength$=new $i(0);this.onLastSegment$=new $i(!1);this.fullyBuffered$=new $i(!1);this.playingRepresentation$=new $i(void 0);this.playingRepresentationInit$=new $i(void 0);this.error$=new Tw;this.gaps=[];this.subscription=new Iw;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ze;this.destroyAbortController=new ze;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=br(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Fe(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Rm(this.sourceBuffer),this.subscription.add(cu(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,l=this.mediaSource.readyState;l!=="open"&&(o={id:`SegmentEjection_source_${l}`,category:Ct.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:Ct.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add(cu(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Ct.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let l=Math.min(this.bufferLimit,Jo(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=l,this.tuning.useNewPruneBufferStrategy){let u=We(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,n*2,u<c)}else this.pruneBufferOld(o,n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),a=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Fe(r,"No init buffer for starting representation"),Fe(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=br(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);Fe(r,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if(Ee(s)||Ee(a)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),Fe(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=br(this.destroyAbortController.signal,async function*(e){let t=e?.flatMap(l=>l.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let l of this.representations.keys()){let u=t.find(p=>p.id===l);u&&this.representations.set(l,u);let c=this.representations.get(l);if(!c||!Mt(c.segmentReference))return;let d=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,d)}let r=this.switchingToRepresentationId??this.downloadingRepresentationId,a=this.representations.get(r);Fe(a);let s=this.segments.get(r);Fe(s,"No segments for starting representation");let n=this.initData.get(r);if(Fe(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.resetAccumulateBufferAfterStall(),this.initData=new Map(r.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ze,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Ee(e)||Ee(this.downloadingRepresentationId)||Ee(this.playingRepresentationId)||Ee(this.sourceBuffer)||!Ee(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(Fe(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let a=r.find(u=>e>=u.time.from&&e<u.time.to);this.currentSegmentLength$.next((a?.time.to??0)-(a?.time.from??0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=We(this.sourceBuffer.buffered,e),d=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=a.time.to-e+100&&(s=d)}if(isFinite(this.bufferLimit)&&Jo(this.sourceBuffer.buffered)>=this.bufferLimit){let u=We(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<c);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(o.includes(a))u="high";else{let c=(0,Sr.default)(o,0);c&&c.time.from-a.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(o,t,u)}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!o.length&&We(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Sr.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;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||!Mt(r.segmentReference))return;let a=r.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=this.segments.get(r.id)??[],n=(0,Sr.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;Fe(e);let t=this.segments.get(e);if(t?.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}startAccumulateBufferAfterStall(){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(!Mt(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=$t(r.segmentTemplateUrl,{segmentTime:o});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);return r?r.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(a=>t>=a.time.from&&t<a.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let a=e.findIndex(({status:d,time:{from:p,to:h}},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(d==="none"||d==="partially_ejected"&&S&&w&&this.sourceBuffer&&!ui(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,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<s.length&&(n<=u||o<=c);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}async loadSegments(e,t,r="auto"){t.segmentReference.type==="template"?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){e.status="downloading";let a={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(a);let{range:s,url:n,signal:o,onProgress:l,onProgressTasks:u}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await br(o,async function*(){let c=du(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:l,priority:r,isLowLatency:this.isActiveLowLatency()});if(!c)return;let d=new DataView(c);if(!isFinite(a.segment.time.to)){let p=t.segmentReference.timescale,h=fr(t.mime);a.segment.time.to=h.getSegmentEndTime(d,p)}l&&a.feedingBytes&&u?await Promise.all(u):await this.sourceBufferTaskQueue.append(d,o),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Li(c)||this.failedDownloads++}}async loadByteRangeSegments(e,t,r="auto"){if(!e.length)return;for(let l of e)l.status="downloading",this.activeSegments.add({segment:l,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:a,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await br(n,async function*(){let l=du(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(u,l),cu(window,"online").pipe(yw()).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),Li(l)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(Mt(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,Sr.default)(e,0).byte.from,to:(0,Sr.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:Ct.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Mt(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let a=r.toString(),{signal:s}=this.downloadAbortController,n=[],l=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(u,c)=>{if(!s.aborted)try{let d=this.onSomeTemplateDataLoaded({dataView:u,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Ct.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:a,signal:s,onProgress:l,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:a,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:l}=o;if(o.representationId===t){if(s.aborted){a();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let u=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=fr(n.mime).parseFeedableSegmentChunk(u,this.isLive);c?.byteLength&&(l.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){let o={dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let l=o.segmentReference.type,u=e.byteLength;for(let c of this.activeSegments){let{segment:d}=c,p=l==="byteRange",h=p?d.byte.to-d.byte.from+1:u;if(c.representationId!==t||!(!p||d.byte.from>=r&&d.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let b=p?d.byte.from-r:0,S=p?d.byte.to-r:e.byteLength,v=b<a,w=S<=a;if(d.status==="downloading"&&v&&w){d.status="downloaded";let T=new DataView(e.buffer,e.byteOffset+b,h),g=this.getCurrentPosition();pu(g)&&(this.bufferAccumulation.accumulatedBufferSizeMs=d.time.to-g,this.bufferAccumulation.accumulated.push({segmentView:T,segmentProgress:c}),this.activeSegments.delete(c));let y=({segmentView:$,segmentProgress:E})=>this.sourceBufferTaskQueue.append($,s).then(k=>k&&!s.aborted?this.onSegmentFullyAppended(E,t):n());this.bufferAccumulation.enabled&&this.bufferAccumulation.targetBufferSizeMs<this.bufferAccumulation.accumulatedBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(y),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||Ee(g))&&(y({segmentView:T,segmentProgress:c}),this.resetAccumulateBufferAfterStall())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&v&&!w&&(c.loadedBytes=Math.min(h,a-b),c.loadedBytes>c.feedingBytes)){let T=new DataView(e.buffer,e.byteOffset+b+c.feedingBytes,c.loadedBytes-c.feedingBytes),g=c.loadedBytes===h?T:fr(o.mime).parseFeedableSegmentChunk(T);g?.byteLength&&(d.status="partially_fed",c.feedingBytes+=g.byteLength,this.sourceBufferTaskQueue.append(g,s).then(y=>{if(s.aborted)n();else if(y)c.fedBytes+=g.byteLength,c.fedBytes===h&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<h)return;n()}}))}}}async onSomeByteRangesDataLoadedNew({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let l of this.activeSegments){let{segment:u}=l;if(l.representationId!==t)continue;if(s.aborted){n();continue}let c=u.byte.from-r,d=u.byte.to-r,p=d-c+1,h=c<a,m=d<=a;if(h){if(u.status==="downloading"&&m){u.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+c,p);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(l,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(u.status==="downloading"||u.status==="partially_fed")&&(l.loadedBytes=Math.min(p,a-c),l.loadedBytes>l.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+c+l.feedingBytes,l.loadedBytes-l.feedingBytes),S=l.loadedBytes===p?b:fr(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",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=Qo(()=>(0,fb.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?br(this.destroyAbortController.signal,async function*(){let o=du(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,fr(e.mime),a)).then(async o=>{if(!o)return;let{init:l,dataView:u,segments:c}=o,d=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&Mt(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:Ct.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,r=!1){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||Ee(e)||this.sourceBuffer.updating)return!1;let a=[],s=0,n=l=>{l.sort((c,d)=>c.from-d.from);let u=[l[0]];for(let c=1;c<l.length;c++){let{from:d,to:p}=l[c],h=u[u.length-1];h.to>=d?h.to=Math.max(h.to,p):u.push(l[c])}return u},o=l=>{if(s>=t)return a;a.push(l.time),a=n(a);let u=is(l)?l.size??0:l.byte.to-l.byte.from;s+=u};for(let l of this.segments.values())for(let u of l){let c=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&u.status==="fed"&&o(u)}for(let l=0;l<this.sourceBuffer.buffered.length;l++){let u=this.sourceBuffer.buffered.start(l)*1e3,c=this.sourceBuffer.buffered.end(l)*1e3,d=0;for(let p of this.segments.values())for(let h of p)h.status==="none"&&Math.round(h.time.from)<=Math.round(u)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:u,to:c},url:"",status:"none"};o(p)}}if(a.length&&r){let l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let c of u)c.time.from>=e+l&&c.status==="fed"&&o(c)}return a.length?(await Promise.all(a.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,c)=>u||c,!1):!1}async pruneBufferOld(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Ee(e)||this.sourceBuffer.updating)return!1;let a=0,s=1/0,n=-1/0,o=!1,l=u=>{s=Math.min(s,u.time.from),n=Math.max(n,u.time.to);let c=is(u)?u.size??0:u.byte.to-u.byte.from;a+=c};for(let u of this.segments.values())for(let c of u){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;c.status==="fed"&&l(c)}if(o=isFinite(s)&&isFinite(n),!o){a=0,s=1/0,n=-1/0;for(let u of this.segments.values())for(let c of u){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||a>t)break;c.status==="fed"&&l(c)}}if(o=isFinite(s)&&isFinite(n),!o)for(let u=0;u<this.sourceBuffer.buffered.length;u++){let c=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3;for(let p of this.segments.values())for(let h of p)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(d)){s=c,n=d;break}}if(o=isFinite(s)&&isFinite(n),!o&&r){a=0,s=1/0,n=-1/0;let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let d of c)d.time.from>e+u&&d.status==="fed"&&l(d)}return o=isFinite(s)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(s,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let a={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){a=void 0;break}o>r.time.from&&o<r.time.to&&(a.from=o),n<r.time.to&&n>r.time.from&&(a.to=n)}}a&&a.to-a.from>1&&!this.gaps.some(s=>a&&s.from===a.from&&s.to===a.to)&&this.gaps.push(a)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Qo(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Ct.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(Ee(this.sourceBuffer)||Ee(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let a=Math.round(this.sourceBuffer.buffered.start(r)*1e3),s=Math.round(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:a,to:s})}let t=1;for(let r of this.segments.values())for(let a of r){let{status:s}=a;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(a.time.from),o=Math.ceil(a.time.to),l=e.some(c=>c.from-t<=n&&c.to+t>=o),u=e.filter(c=>n>=c.from-t&&n<=c.to+t||o>=c.from-t&&o<=c.to+t);l||(u.length===1?a.status="partially_ejected":this.gaps.some(c=>c.from===a.time.from||c.to===a.time.to)?a.status="partially_ejected":a.status="none")}}};var Ci=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var mb=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 Di,assertNever as bb,fromEvent as Sb,merge as Ew,now as hu,Subscription as xw,ValueSubject as fu}from"@vkontakte/videoplayer-shared";var as=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new fu(void 0);this.lastConnectionReused$=new fu(void 0);this.lastRequestFirstBytes$=new fu(void 0);this.abortAllController=new ze;this.subscription=new xw;this.fetchManifest=Di(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=Ci(t));let r=yield Qe(t,{signal:this.abortAllController.signal}).catch(Bi);return r?(this.onHeadersReceived(r.headers),r.text()):null}.bind(this));this.fetch=Di(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:a,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:l=!1}={}){let u=e,c=new Headers;if(r)switch(t){case 0:{c.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let k=new URL(u,location.href);k.searchParams.append("bytes",`${r.from}-${r.to}`),u=k.toString();break}default:bb(t)}this.requestQuic&&(u=Ci(u));let d=this.abortAllController.signal,p;if(n){let k=new ze;if(p=Ew(Sb(this.abortAllController.signal,"abort"),Sb(n,"abort")).subscribe(()=>{try{k.abort()}catch(D){Bi(D)}}),this.abortAllController.signal.aborted||n.aborted)try{k.abort()}catch(D){Bi(D)}d=k.signal}let h=hu(),m=yield Qe(u,{priority:s,headers:c,signal:d}).catch(Bi),b=hu();if(!m)return p?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(b-h),!m.ok||!m.body)return p?.unsubscribe(),Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`));if(this.onHeadersReceived(m.headers),!a&&!o)return p?.unsubscribe(),m.arrayBuffer();let[S,v]=m.body.tee(),w=S.getReader();o&&this.throughputEstimator?.trackStream(v,l);let T=0,g=new Uint8Array(0),y=!1,$=k=>{p?.unsubscribe(),y=!0,Bi(k)},E=Di(d,async function*({done:k,value:D}){if(T===0&&this.lastRequestFirstBytes$.next(hu()-h),d.aborted){p?.unsubscribe();return}if(!k&&D){let P=new Uint8Array(g.length+D.length);P.set(g),P.set(D,g.length),g=P,T+=D.byteLength,a?.(new DataView(g.buffer),T),yield w?.read().then(E,$)}}.bind(this));return yield w?.read().then(E,$),p?.unsubscribe(),y?null:g.buffer}.bind(this));this.fetchByteRangeRepresentation=Di(this.abortAllController.signal,async function*(e,t,r){if(e.type!=="byteRange")return null;let{from:a,to:s}=e.initRange,n=a,o=s,l=!1,u,c;e.indexRange&&(u=e.indexRange.from,c=e.indexRange.to,l=s+1===u,l&&(n=Math.min(u,a),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,a-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let b;if(l)b=new DataView(d,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(d),segments:S}}.bind(this));this.fetchTemplateRepresentation=Di(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),a=yield this.fetch(r,{priority:t,measureThroughput:!1});return a?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(a)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r}onHeadersReceived(e){let{type:t,reused:r}=mb(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:bb(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},Bi=i=>{if(!Li(i))throw i};var Dt=(i,e,t)=>t*e+(1-t)*i,mu=(i,e)=>i.reduce((t,r)=>t+r,0)/e,gb=(i,e,t,r)=>{let a=0,s=t,n=mu(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 Pw,ValueSubject as vb}from"@vkontakte/videoplayer-shared";var lt=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 vb(e.initial),this.debounced$=new vb(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new J(`raw_${t}`),this.smoothedSeries$=new J(`smoothed_${t}`),this.reportedSeries$=new J(`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)&&(Pw(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var ss=class extends lt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Dt(this.slow,e,this.params.emaAlphaSlow),this.fast=Dt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var ns=class extends lt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=mu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Dt(this.emaSmoothed,e,this.params.emaAlpha);let r=gb(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var os=class extends lt{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?Dt(this.smoothed,t,this.params.emaAlpha):t}};var Bt=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new ss({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new ns({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 os({initial:e,label:"liveEdgeDelay",...t})}};var bu=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};var Pb=["timeupdate","progress","play","seeked","stalled","waiting"];var cs=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new xb;this.representationSubscription=new xb;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 Eb;this.lastConnectionType$=new X(void 0);this.lastConnectionReused$=new X(void 0);this.lastRequestFirstBytes$=new X(void 0);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 Eb;this.gapWatchdogActive=!1;this.destroyController=new ze;this.initManifest=Su(this.destroyController.signal,async function*(e,t,r){this.element=e,this.manifestUrlString=z(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:ct.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Su(this.destroyController.signal,async function*(){let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(s=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ct.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return null;let t;try{t=cb(e??"",this.manifestUrlString)}catch(s){let n=xm(e)??{id:"ManifestParsing",category:ct.PARSER,message:"Failed to parse MPD manifest",thrown:s};this.error$.next(n)}if(!t)return null;let r=(s,n,o)=>!!(this.element?.canPlayType?.(n)&&Ke()?.isTypeSupported?.(`${n}; codecs="${o}"`)||s==="text");t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let a={text:t.streams.text,video:[],audio:[]};for(let s of["video","audio"]){let o=t.streams[s].filter(({mime:c,codecs:d})=>r(s,c,d)),l=new Set(o.map(({codecs:c})=>c)),u=Em(l);if(u&&(a[s]=o.filter(({codecs:c})=>c.startsWith(u))),s==="video"){let c=this.tuning.preferHDR,d=a.video.some(h=>h.hdr),p=a.video.some(h=>!h.hdr);Lw.isHDR&&c&&d?a.video=a.video.filter(h=>h.hdr):p&&(a.video=a.video.filter(h=>!h.hdr))}}return{...t,streams:a}}.bind(this));this.initRepresentations=Su(this.destroyController.signal,async function*(e,t,r){Ot(this.manifest),Ot(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=d=>{this.representationSubscription.add(gr(d,"error").pipe(ls(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:ct.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=this.tuning.useManagedMediaSource?mm():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Ja())if(r){let d=document.createElement("source");a(d),d.type="application/x-mpegurl",d.src=r.url,this.element.appendChild(d)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((d,p)=>[...d,...p.representations],[]);if(this.videoBufferManager=new Mi("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Ib(t)){let d=this.manifest.streams.audio.reduce((p,h)=>[...p,...h.representations],[]);this.audioBufferManager=new Mi("audio",this.source,d,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(gu(1e3).subscribe(d=>{if(this.element?.paused){let p=wo(this.manifestUrlString,2);this.manifestUrlString=z(this.manifestUrlString,p+1e3,2)}})),this.representationSubscription.add(vr(...Pb.filter(d=>d!=="waiting").map(d=>gr(this.element,d))).pipe(vu(d=>this.element?We(this.element.buffered,this.element.currentTime*1e3):0),Tb(),ls(d=>!!d),kw(d=>{this.stallWatchdogSubscription?.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Tb()).subscribe(p=>bu(this.element,1))),this.representationSubscription.add(us({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(ls(({bufferLength:p,isActiveLowLatency:h})=>h&&!!p)).subscribe(({bufferLength:p})=>this.liveEstimatedDelay.next(p))),this.representationSubscription.add(us({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),bu(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 d=0;this.representationSubscription.add(us({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Rw(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:h})=>{if(Ot(this.element),this.isUpdatingLive)return;let m=this.element.playbackRate,b=wo(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(),$=S<=this.tuning.live.activeLiveDelay&&b===0;this.isActiveLowLatency$.next(y&&$);let E="none";if(y?E="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&$?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(k=>k.proceedLowLatencyLive()),E="active_low_latency"):b!==0&&g<v?E="live_forward_buffering":g<v+T&&(E="live_with_target_offset"),isFinite(p)&&(d=p>d?p:d),E==="live_forward_buffering"||E==="live_with_target_offset"){let k=d-(v+w),D=this.normolizeLiveOffset(Math.trunc(b+k/m)),P=Math.abs(D-b),B;!p||P<=this.tuning.dashCmafLive.offsetCalculationError?B=b:D>0&&P>this.tuning.dashCmafLive.offsetCalculationError?B=D:B=0,this.manifestUrlString=z(this.manifestUrlString,B,2)}E!=="none"&&E!=="active_low_latency"&&(d=0,this.updateLive())}))}let l=vr(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe(vu(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),u=vr(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe(vu(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue())));this.representationSubscription.add(vr(this.forceEnded$,us({allBuffersFull:l,someBufferEnded:u}).pipe(ls(({allBuffersFull:d,someBufferEnded:p})=>d&&p))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{this.source?.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:ct.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add(vr(...this.bufferManagers.map(d=>d.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.source.readyState!=="open"&&(yield new Promise(d=>this.source?.addEventListener("sourceopen",d)));let c=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(d=>d.representations).flatMap(d=>d.duration??0)];this.source.duration=Math.max(...c)/1e3,this.audioBufferManager&&Ib(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=gu(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:ct.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new as({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Bt.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){Ot(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=z(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(){Ot(this.element),this.state$.setState("running"),this.subscription.add(vr(...Pb.map(e=>gr(this.element,e)),gr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ct.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(gr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(gr(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&ui(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(this.element){if(this.timeInWaiting+=1e3,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset);else{let t=this.element.currentTime*1e3;this.videoBufferManager?.maintain(t),this.audioBufferManager?.maintain(t)}}};this.videoBufferManager?.startAccumulateBufferAfterStall(),this.audioBufferManager?.startAccumulateBufferAfterStall(),this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=gu(1e3).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:ct.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){Ot(this.element),Ot(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),ui(this.element.buffered,r)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(r),this.audioBufferManager?.maintain(r),this.element.currentTime=r/1e3}stop(){this.element?.querySelectorAll("source").forEach(e=>e.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let t=this.element.currentTime*1e3,r=[],a=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let s of this.bufferManagers)for(let n of s.gaps)s.playingRepresentation$.getValue()===n.representation&&n.from-a<=t&&n.to+a>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?r.push(1/0):r.push(n.to));if(r.length){let s=Math.max(...r)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,s===1/0?this.forceEnded$.next():this.element.currentTime=s/1e3}}};var ds=class{constructor(e,t){this.fov=e,this.orientation=t}};var ps=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 Ab=`attribute vec2 a_vertex;
36
+ [best video track] ${O?.quality}
37
+ [selected video track] ${N?.quality}
38
+ `}),hm(r,p,N,u)},fm=(i,e,t,{throughput:r,tuning:a,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:c})=>{lm(t,pm);let u=a.considerPlaybackRate&&ce(s)?s:1,d=[...t].sort(Go(-1)),l=i.bitrate;WP(l);let p=u*dm(n??.5,a.bitrateAudioFactorAtEmptyBuffer,a.bitrateAudioFactorAtFullBuffer),h;return ce(r)&&isFinite(r)&&(h=d.find(m=>ce(m.bitrate)?r-l>=m.bitrate*p:!0)),h||(h=Ka(i,e,t,a.minVideoAudioRatio)),h?.bitrate!==o?.last?.bitrate&&c({message:`
39
+ [AUDIO TRACKS ABR]
40
+ [available audio tracks]
41
+ ${t.map(m=>`{ id: ${m.id}, bitrate: ${m.bitrate} }`).join(`
42
+ `)}
43
+
44
+ [tuning]
45
+ ${Object.entries(a??{}).map(([m,b])=>`${m}: ${b}`).join(`
46
+ `)}
47
+
48
+ [limit params]
49
+ throughput: ${r},
50
+ reserve: ${l},
51
+ playbackRate: ${s},
52
+ playbackRateFactor: ${u},
53
+ forwardBufferHealth: ${n},
54
+ bitrateFactor: ${p},
55
+ minBufferToSwitchUp: ${a.minBufferToSwitchUp},
56
+
57
+ [selected audio track] ${h?.id}
58
+ `}),h&&hm(a,c,h,o)};var Y=i=>new URL(i).hostname;import{assertNever as ym,assertNonNullable as Tm,combine as hA,debounce as fA,ErrorCategory as Im,filter as Em,filterChanged as mA,isNonNullable as Ko,map as ts,merge as xm,observableFrom as bA,once as gA,Subscription as SA,ValueSubject as Jo,videoQualityToHeight as vA,videoSizeToQuality as yA}from"@vkontakte/videoplayer-shared";var mm=i=>{if(i instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(i.message))throw i;return!(i instanceof DOMException&&(i.code===20||i.name==="AbortError"))},le=async i=>{let e=i.muted;try{await i.play()}catch(t){if(!mm(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{await i.play()}catch(r){return mm(r)&&(i.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as Xa,isNullable as KP,assertNonNullable as oi}from"@vkontakte/videoplayer-shared";import{isNonNullable as bm,assertNonNullable as Ja,now as QP}from"@vkontakte/videoplayer-shared";function Q(){return QP()}function Wo(i){return Q()-i}function Yo(i){let e=i.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,a=n=>r.test(n);return{resolve:(n,o,c=!1)=>{a(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let u=n.indexOf("?")>-1?"&":"?";return c&&(n+=u+"lowLat=1",u="&"),o&&(n+=u+"_rnd="+Math.floor(999999999*Math.random())),n}}}function gm(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function pr(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,c=!1,u=0,d,l,p=!1,h="arraybuffer",m=7e3,b=2e3,g=()=>{if(c)return;Ja(d);let $=Wo(d),q;if($<b){q=b-$,setTimeout(g,q);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new a,E()},v=$=>(s=$,w),A=$=>(l=$,w),y=()=>(h="json",w),S=()=>{if(!c){if(--u>=0){g(),r&&r();return}c=!0,l&&l(),t&&t()}},T=$=>(p=$,w),E=()=>{d=Q(),n=new a,n.open("get",i);let $=0,q,ke=0,te=()=>(Ja(d),Math.max(d,Math.max(q||0,ke||0)));if(s&&n.addEventListener("progress",x=>{let R=Q();s.updateChunk&&x.loaded>$&&(s.updateChunk(te(),x.loaded-$),$=x.loaded,q=R)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>S())),n.addEventListener("load",()=>{if(c)return;Ja(n);let x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&s){let R=n.response.byteLength-$;R&&s.updateChunk&&s.updateChunk(te(),R)}n.responseType==="json"&&!Object.values(n.response).length?S():(l&&l(),e(n.response))}else S()}),n.addEventListener("error",()=>{S()}),p){let x=()=>{Ja(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ke=Q(),n.removeEventListener("readystatechange",x))};n.addEventListener("readystatechange",x)}return n.responseType=h,n.send(),w},w={withBitrateReporting:v,withParallel:T,withJSONResponse:y,withRetryCount:$=>(u=$,w),withRetryInterval:($,q)=>(bm($)&&(b=$),bm(q)&&(m=q),w),withTimeout:$=>(o=$,w),withFinally:A,send:E,abort:()=>{n&&(n.abort(),n=void 0),c=!0,l&&l()}};return w}var si=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,a=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,a+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let c=s.bytes*n/o;a+=c,s.start=t,s.bytes-=c}}}if(a>0&&r>0){let s=a*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(a)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var ni=class{constructor(e,t,r,a,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=a,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=Q(),a=c=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=c,e._errorCB?e._errorCB(c):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=c=>{e._complete=1,e._responseData=c,e._downloadTime=Q()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(c,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=pr(t,s,()=>a("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Q()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=Q();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,a){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=a,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=a,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var Za=1e4,Qo=3;var JP=6e4,XP=10,ZP=1,eA=500,ui=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.chunkRateEstimator=new si(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Yo(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Yo(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,a;r!==0&&(a=t.buffered.start(r-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){let{videoElement:t}=this.params,r,a,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!a||s.bitrate>a.bitrate)&&(a=s):(!r||r.bitrate>s.bitrate)&&(r=s));return a||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Xa(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:a,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),a.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,a.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{gm(a,"progress",()=>{a.buffered.length?(a.currentTime=a.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new ni(Qo,Za,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:a}=this.params,s=!1,n=null,o=null,c=null,u=null,d=!1,l=()=>{let S=s&&(!d||d===this.rep);return S||t("Not running!"),S},p=(S,T,E)=>{c&&c.abort(),c=pr(this.urlResolver.resolve(S,!1),T,E,()=>this._retryCallback()).withTimeout(Za).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Qo).withFinally(()=>{c=null}).send()},h=(S,T,E)=>{oi(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(S,!1),T,E,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=S=>{let T=r.playbackRate;r.playbackRate!==S&&(t(`Playback rate switch: ${T}=>${S}`),r.playbackRate=S)},b=S=>{this.lowLatency=S,t(`lowLatency changed to ${S}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let S=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let E=Q()-1e4,D=0;for(let N=0;N<this.bufferStates.length;N++){let k=this.bufferStates[N];S=Math.min(S,k.buf),k.ts<E&&D++}this.bufferStates.splice(0,D),t(`update playback rate; minBuffer=${S} drop=${D} jitter=${this.sourceJitter}`);let O=S-ZP;this.sourceJitter>=0?O-=this.sourceJitter/2:this.sourceJitter-=1,O>3?m(1.15):O>1?m(1.1):O>.3?m(1.05):m(1)}},v=S=>{let T,E=()=>T&&T.start?T.start.length:0,D=x=>T.start[x]/1e3,O=x=>T.dur[x]/1e3,N=x=>T.fragIndex+x,k=(x,R)=>({chunkIdx:N(x),startTS:D(x),dur:O(x),discontinuity:R}),w=()=>{let x=0;if(T&&T.dur){let R=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,G=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,z=R;this.sourceJitter>1&&(z+=this.sourceJitter-1);let he=T.dur.length-1;for(;he>=0&&(z-=T.dur[he],!(z<=0));--he);x=Math.min(he,T.dur.length-1-G),x=Math.max(x,0)}return k(x,!0)},$=x=>{let R=E();if(!(R<=0)){if(Xa(x)){for(let G=0;G<R;G++)if(D(G)>x)return k(G)}return w()}},q=x=>{let R=E(),G=x?x.chunkIdx+1:0,z=G-T.fragIndex;if(!(R<=0)){if(!x||z<0||z-R>XP)return t(`Resync: offset=${z} bChunks=${R} chunk=`+JSON.stringify(x)),w();if(!(z>=R))return k(G-T.fragIndex,!1)}},ke=(x,R,G)=>{u&&u.abort(),u=pr(this.urlResolver.resolve(x,!0,this.lowLatency),R,G,()=>this._retryCallback()).withTimeout(Za).withRetryCount(Qo).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(x,R)=>{ke(S,G=>{if(!l())return;T=G;let z=!!T.lowLatency;z!==this.lowLatency&&b(z);let he=0;for(let Ve=0;Ve<T.dur.length;++Ve)he+=T.dur[Ve];he>0&&(oi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(he/T.dur.length)),a({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,x($(R))},()=>this._handleNetworkError())},nextChunk:q}},A=()=>{s=!1,o&&o.abort(),c&&c.abort(),u&&u.abort(),oi(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:S=>{let{videoElement:T,logger:E}=this.params,D=v(e.jidxUrl),O,N,k,w,$=0,q,ke,te,x=()=>{q&&(clearTimeout(q),q=void 0);let B=Math.max(eA,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),W=$+B,re=Q(),we=Math.min(1e4,W-re);$=re;let tt=()=>{u||l()&&D.seek(()=>{l()&&($=Q(),R(),x())})};we>0?q=window.setTimeout(()=>{this.paused?x():tt()},we):tt()},R=()=>{let B;for(;B=D.nextChunk(w);)w=B,Ut(B);let W=D.nextChunk(k);if(W){if(k&&W.discontinuity){E("Detected discontinuity; restarting playback"),this.paused?x():(A(),this._initPlayerWith(e));return}Ve(W)}else x()},G=(B,W)=>{if(!l()||!this.sourceBuffer)return;let re,we,tt,Ht=rt=>{window.setTimeout(()=>{l()&&G(B,W)},rt)};if(this.sourceBuffer.updating)E("Source buffer is updating; delaying appendBuffer"),Ht(100);else{let rt=Q(),jt=T.currentTime;!this.paused&&T.buffered.length>1&&ke===jt&&rt-te>500&&(E("Stall suspected; trying to fix"),this._fixupStall()),ke!==jt&&(ke=jt,te=rt);let Ar=this._getBufferSizeSec();if(Ar>30)E(`Buffered ${Ar} seconds; delaying appendBuffer`),Ht(2e3);else try{this.sourceBuffer.appendBuffer(B),this.videoPlayStarted?(this.bufferStates.push({ts:rt,buf:Ar}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),W&&W()}catch(sa){if(sa.name==="QuotaExceededError")E("QuotaExceededError; delaying appendBuffer"),tt=this.sourceBuffer.buffered.length,tt!==0&&(re=this.sourceBuffer.buffered.start(0),we=jt,we-re>4&&this.sourceBuffer.remove(re,we-3)),Ht(1e3);else throw sa}}},z=()=>{N&&O&&(E([`Appending chunk, sz=${N.byteLength}:`,JSON.stringify(k)]),G(N,function(){N=null,R()}))},he=B=>e.fragUrlTemplate.replace("%%id%%",B.chunkIdx),Ve=B=>{l()&&h(he(B),(W,re)=>{if(l()){if(re/=1e3,N=W,k=B,n=B.startTS,re){let we=Math.min(10,B.dur/re);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*we:we}z()}},()=>this._handleNetworkError())},Ut=B=>{l()&&(oi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(he(B),!1)))},gt=B=>{l()&&(e.cachedHeader=B,G(B,()=>{O=!0,z()}))};s=!0,D.seek(B=>{if(l()){if($=Q(),!B){x();return}w=B,!KP(S)||B.startTS>S?Ve(B):(k=B,R())}},S),e.cachedHeader?gt(e.cachedHeader):p(e.headerUrl,gt,()=>this._handleNetworkError())},stop:A,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),Xa(a)&&(a+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,oi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Xa(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=l=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&l<this.bitrate&&(h=this._getBufferSizeSec(),m=l/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(l)}`);return}p=this._selectQuality(l),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${l}`)},s={updateChunk:(p,h)=>{let m=Q();if(this.chunkRateEstimator.addInterval(p,m,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,c=!0,u=()=>{let l=s.get();if(l&&o&&this.autoQuality){if(c&&l>o&&Wo(n)<3e4)return;r(l)}c=this.autoQuality};return{updateChunk:(l,p)=>{let h=s.updateChunk(l,p);return h&&u(),h},notifySwitch:l=>{let p=Q();l<o&&(n=p),o=l}}}_fetchManifest(e,t,r){this.manifestRequest=pr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Za).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;le(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:a}=this.params,s=n=>{let o=[];return n?.length?(n.forEach((c,u)=>{c.video&&a.canPlayType(c.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(c.codecs)&&(c.index=u,o.push(c))}),o.sort(function(c,u){return c.video&&u.video?u.video.height-c.video.height:u.bitrate-c.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},JP))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as tA,filter as Sm,fromEvent as rA,interval as iA,isHigher as aA,isInvariantQuality as sA,isLower as nA,merge as oA,Subject as vm,Subscription as uA}from"@vkontakte/videoplayer-shared";var zo=class{constructor(){this.onDroopedVideoFramesLimit$=new vm;this.subscription=new uA;this.playing=!1;this.tracks=[];this.forceChecker$=new vm;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!sA(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,a=t-this.prevDroppedVideoFrames,s=1-(r-a)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&aA(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(rA(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=iA(this.droppedFramesChecker.checkTime).pipe(Sm(()=>this.playing),Sm(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(tA(this.droppedFramesChecker.checkTime)),r=oA(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){let t=Object.entries(this.limitCounts).filter(([,r])=>r>=this.droppedFramesChecker.countLimit).sort(([r],[a])=>nA(r,a)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},es=zo;import{map as cA,Observable as lA}from"@vkontakte/videoplayer-shared";import{fromEvent as dA}from"@vkontakte/videoplayer-shared";var ci=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var pA=(i,e)=>new lA(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(c=>t.next(c.isIntersecting||ci()))},{...r,...e});a.observe(i);let s=dA(document,"visibilitychange").pipe(cA(n=>!document.hidden||ci())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),Pe=pA;var TA=["paused","playing","ready"],IA=["paused","playing","ready"],li=class{constructor(e){this.subscription=new SA;this.videoState=new L("stopped");this.representations$=new Jo([]);this.textTracksManager=new Ee;this.droppedFramesManager=new es;this.maxSeekBackTime$=new Jo(1/0);this.zeroTime$=new Jo(void 0);this.liveOffset=new Ye;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Im.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,r=[];for(let a of t){let s=a.name??a.index.toString(10),n=ct(a.name)??yA(a.video),o=a.bitrate/1e3,c={...a.video};if(!n)continue;let u={id:s,quality:n,bitrate:o,size:c};r.push({track:u,representation:a})}this.representations$.next(r),this.params.output.availableVideoTracks$.next(r.map(({track:a})=>a)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,r=this.representations$.getValue().find(({representation:a})=>a===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),Ko(r)&&this.params.output.currentVideoTrack$.next(r);break}case"bandwidth":{let{size:t,duration:r}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,r);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(IA.includes(e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&TA.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(K(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let c=a?.from;c&&c==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.dash.reinit(K(this.params.source.url,c))}return;default:return ym(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:Im.WTF,message:"DashLiveProvider internal logic error",thrown:a})};xm(this.videoState.stateChangeStarted$.pipe(ts(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ts(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=se(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Y(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=ue(this.video);this.subscription.add(this.representations$.pipe(ts(a=>a.map(({track:s})=>s)),Em(a=>!!a.length),gA()).subscribe(a=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:a}))),this.subscription.add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(mA(),ts(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(hA({zeroTime:this.zeroTime$.pipe(Em(Ko)),position:r.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(Fe(this.video,this.params.desiredState.isLooped,t)).add(oe(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Ie(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Pe(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&vA(a);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:a})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return ym(a.to)}},t)).add(xm(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,bA(["init"])).pipe(fA(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),ne(this.video)}createLiveDashPlayer(){let e=new ui({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),a=!r&&Ko(t)?t:lt(e.map(({track:u})=>u),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=a?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),c&&this.setAutoQuality(r),n||c||s!==o){let u=e.find(({track:d})=>d.id===s)?.representation;Tm(u,"Representations missing"),this.dash.startPlay(u,r)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:r})=>r.id===e.id)?.representation;Tm(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),a=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(K(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var Pm=li;var ze=(i,e)=>{let t=0;for(let r=0;r<i.length;r++){let a=i.start(r)*1e3,s=i.end(r)*1e3;a<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as Wk,assertNonNullable as Yk,debounce as Qk,ErrorCategory as Pu,filter as qb,filterChanged as Au,fromEvent as zk,isNonNullable as Kk,map as Ub,merge as Ts,observableFrom as Jk,observeElementSize as Xk,once as Hb,Subscription as Zk,ValueSubject as ew}from"@vkontakte/videoplayer-shared";var rs=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let a=0,s=r.length;a<s;a++)if(r[a].callback===t){r.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let a=0,s=r.length;a<s;a++){let n=r[a];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},hr=class extends rs{constructor(){super(),this.listeners||rs.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},di=class{constructor(){Object.defineProperty(this,"signal",{value:new hr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document>"u")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch{r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(di.prototype[Symbol.toStringTag]="AbortController",hr.prototype[Symbol.toStringTag]="AbortSignal");function is(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function Xo(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!is({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||a)&&(s=function(u,d){let l;d&&d.signal&&(l=d.signal,delete d.signal);let p=new t(u,d);return l&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:l}),p},s.prototype=t.prototype);let n=e;return{fetch:(c,u)=>{let d=s&&s.prototype.isPrototypeOf(c)?c.signal:u?u.signal:void 0;if(d){let l;try{l=new DOMException("Aborted","AbortError")}catch{l=new Error("Aborted"),l.name="AbortError"}if(d.aborted)return Promise.reject(l);let p=new Promise((h,m)=>{d.addEventListener("abort",()=>m(l),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([p,n(c,u)])}return n(c,u)},Request:s}}var pi=is({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Am=pi?Xo({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ke=pi?Am.fetch:window.fetch,t0=pi?Am.Request:window.Request,Je=pi?di:window.AbortController,r0=pi?hr:window.AbortSignal;var Rm=_e(ri(),1);var Xe=()=>window.ManagedMediaSource||window.MediaSource,as=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),km=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),wm=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as us,clientChecker as ns}from"@vkontakte/videoplayer-shared";var os=document.createElement("video"),PA='video/mp4; codecs="avc1.42000a,mp4a.40.2"',AA='video/mp4; codecs="hev1.1.6.L93.B0"',$m='video/webm; codecs="vp09.00.10.08"',Lm='video/webm; codecs="av01.0.00M.08"',kA='audio/mp4; codecs="mp4a.40.2"',wA='audio/webm; codecs="opus"',Lt={mms:as(),mse:km(),hls:!!(os.canPlayType?.("application/x-mpegurl")||os.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},de={mp4:!!os.canPlayType?.("video/mp4"),webm:!!os.canPlayType?.("video/webm"),cmaf:!0},pe={h264:!!Xe()?.isTypeSupported?.(PA),h265:!!Xe()?.isTypeSupported?.(AA),vp9:!!Xe()?.isTypeSupported?.($m),av1:!!Xe()?.isTypeSupported?.(Lm),aac:!!Xe()?.isTypeSupported?.(kA),opus:!!Xe()?.isTypeSupported?.(wA)},fr=(pe.h264||pe.h265)&&pe.aac,Mt,RA=async()=>{if(!window.navigator.mediaCapabilities)return;let i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:Lm}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:$m}})]);Mt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{RA()}catch(i){console.error(i)}var mr=Lt.hls&&de.mp4,Mm=()=>Object.keys(pe).filter(i=>pe[i]),Cm=(i,e=!1,t=!1)=>{let r=Lt.mse||Lt.mms&&t;return i.filter(a=>{switch(a){case"DASH_SEP":return r&&de.mp4&&fr;case"DASH_WEBM":return r&&de.webm&&pe.vp9&&pe.opus;case"DASH_WEBM_AV1":return r&&de.webm&&pe.av1&&pe.opus;case"DASH_STREAMS":return r&&(de.mp4&&fr||de.webm&&(pe.vp9||pe.av1)&&(pe.opus||pe.aac));case"DASH_LIVE":return Lt.mse&&de.mp4&&fr;case"DASH_LIVE_CMAF":return r&&de.mp4&&fr&&de.cmaf;case"DASH_ONDEMAND":return r&&de.mp4&&fr;case"HLS":case"HLS_ONDEMAND":return mr||e&&Lt.mse&&de.mp4&&fr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return mr;case"MPEG":return de.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Lt.webrtc&&Lt.ws&&pe.h264&&(de.mp4||de.webm);default:return us(a)}})},ss=i=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(i){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return Mt?Mt[t].smooth?[t,e]:Mt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Mt?Mt[t].powerEfficient?[t,e]:Mt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:us(i)}return[e,t]},Dm=({webmCodec:i,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...ss(i),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],a=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(ns.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...a,"MPEG",...ss(i),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...ss(i),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...ss(i),...a,"HLS","HLS_ONDEMAND"];default:us(e)}return mr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Bm=({androidPreferredFormat:i,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],a=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...a],n=[...a,...r],o,c=ns.isMac&&ns.isSafari;if(ns.isAndroid)switch(i){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:us(i)}else mr&&!c?o=n:c?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Zo=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Vm=i=>{if(i.size!==0){if(i.size===1)return i.values().next().value.split(".").at(0);for(let e of i){let t=(0,Rm.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return i.values().next().value.split(".").at(0)}};import{ErrorCategory as hi}from"@vkontakte/videoplayer-shared";var Om=i=>{if(!i)return{id:"EmptyResponse",category:hi.PARSER,message:"Empty response"};if(i.length<=2&&i.match(/^\d+$/))return{id:`UVError#${i}`,category:hi.NETWORK,message:`UV Error ${i}`};let e=i.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:hi.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(i,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:hi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:hi.PARSER,message:"Response is valid XML, but parser failed"}};var fi=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};import{abortable as Iu,assertNonNullable as Ft,combine as ms,ErrorCategory as pt,filter as bs,filterChanged as Db,fromEvent as Er,interval as Eu,isNonNullable as Bb,map as xu,merge as xr,Subject as Vb,Subscription as Ob,tap as _k,throttle as Nk,clientChecker as Fk,ValueSubject as Z,flattenObject as Hi,getTraceSubscriptionMethod as qk}from"@vkontakte/videoplayer-shared";var Tr=_e(ri(),1);var $A=(i,e={})=>{let r=e.timeout||1,a=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-a-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-a))}})},1)},LA=i=>window.clearTimeout(i),_m=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",eu=_m?$A:window.requestIdleCallback,b0=_m?LA:window.cancelIdleCallback;var kb=_e(Ya(),1);import{assertNever as MA,ErrorCategory as Nm,clientChecker as tu,Subject as Fm}from"@vkontakte/videoplayer-shared";var CA=16,qm=!1;try{qm=tu.isSafari&&!!tu.macVersion&&tu.macVersion<=CA}catch(i){console.error(i)}var ru=class{constructor(e){this.bufferFull$=new Fm;this.error$=new Fm;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:Nm.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let a={operation:"append",data:e,signal:t,callback:r};this.queue.push(a),this.pull()})}async remove(e,t,r){return r&&r.aborted?!1:new Promise(a=>{let s={operation:"remove",from:e,to:t,signal:r,callback:a};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let r;qm&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:a}of this.queue)a(!1);r&&(this.queue=[r]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Nm.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:MA(t)}}},Um=ru;var iu=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};import{abortable as yr,assertNonNullable as Ue,ErrorCategory as Ot,fromEvent as bu,getExponentialDelay as gu,isNonNullable as Su,isNullable as Ae,once as $k,Subject as Lk,Subscription as Mk,ValueSubject as Oi}from"@vkontakte/videoplayer-shared";var _=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let a=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,a),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let a=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,a}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var br=class extends _{};var mi=class extends _{};var bi=class extends _{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let a=this.readString(4);this.compatibleBrands.push(a),r-=4}}};var gi=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Si=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var vi=class extends _{constructor(e,t){super(e,t),this.data=this.content}};var j=class extends _{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Ct=class extends j{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let a=this.readUint32(),s=a>>>31,n=a<<1>>>1,o=this.readUint32();a=this.readUint32();let c=a>>>28,u=a<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:c,SAPDeltaTime:u})}}};var yi=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ti=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ii=class extends j{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Ei=class extends j{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var xi=class extends j{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Pi=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ai=class extends j{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var ki=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var wi=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ri=class extends j{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var $i=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Li=class extends j{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Mi=class extends j{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Ci=class extends j{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let a=0;a<this.sampleCount;a++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var BA={ftyp:bi,moov:gi,moof:Si,mdat:vi,sidx:Ct,trak:yi,mdia:Pi,mfhd:Ri,tkhd:Ai,traf:$i,tfhd:Li,tfdt:Mi,trun:Ci,minf:ki,sv3d:Ti,st3d:Ii,prhd:Ei,proj:wi,equi:xi,uuid:mi,unknown:br},Dt=class i{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch{break}return t}createBox(e,t){let r=BA[e];return r?new r(t,new i):new br(t,new i)}};var gr=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var OA=new TextDecoder("ascii"),_A=i=>OA.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",NA=i=>{let e=new Ct(i,new Dt),t=e.earliestPresentationTime/e.timescale*1e3,r=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},FA=(i,e)=>{let r=new Dt().parse(i),a=new gr(r),s=a.findAll("moof"),n=e?a.findAll("uuid"):a.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],c=n[n.length-1],u=o.source.byteOffset,l=c.source.byteOffset-o.source.byteOffset+c.size;return new DataView(i.buffer,u,l)},qA=(i,e)=>{let r=new Dt().parse(i),s=new gr(r).findAll("traf"),n=s[s.length-1].children.find(l=>l.type==="tfhd"),o=s[s.length-1].children.find(l=>l.type==="tfdt"),c=s[s.length-1].children.find(l=>l.type==="trun"),u=0;return c.sampleDuration.length?u=c.sampleDuration.reduce((l,p)=>l+p,0):u=n.defaultSampleDuration*c.sampleCount,(Number(o.baseMediaDecodeTime)+u)/e*1e3},UA=i=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new Dt().parse(i),a=new gr(r);if(a.find("sv3d")){e.is3dVideo=!0;let n=a.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=a.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let c=a.find("equi");c&&(e.projectionData.bounds.top=c.projectionBoundsTop,e.projectionData.bounds.right=c.projectionBoundsRight,e.projectionData.bounds.bottom=c.projectionBoundsBottom,e.projectionData.bounds.left=c.projectionBoundsLeft)}return e},Hm={validateData:_A,parseInit:UA,getIndexRange:()=>{},parseSegments:NA,parseFeedableSegmentChunk:FA,getSegmentEndTime:qA};import{assertNonNullable as su,isNonNullable as Ym,isNullable as jA}from"@vkontakte/videoplayer-shared";import{assertNever as HA}from"@vkontakte/videoplayer-shared";var jm={440786851:{type:"master"},17030:{type:"uint"},17143:{type:"uint"},17138:{type:"uint"},17139:{type:"uint"},17026:{type:"string"},17031:{type:"uint"},17029:{type:"uint"},236:{type:"binary"},408125543:{type:"master"},290298740:{type:"master"},19899:{type:"master"},21419:{type:"binary"},21420:{type:"uint"},357149030:{type:"master"},2807729:{type:"uint"},17545:{type:"float"},374648427:{type:"master"},174:{type:"master"},224:{type:"master"},30320:{type:"master"},30321:{type:"uint"},30322:{type:"master"},272869232:{type:"master"},524531317:{type:"master"},231:{type:"uint"},22612:{type:"master"},22743:{type:"uint"},167:{type:"uint"},171:{type:"uint"},163:{type:"binary"},160:{type:"master"},175:{type:"binary"},423732329:{type:"master"},307544935:{type:"master"},475249515:{type:"master"},187:{type:"master"},179:{type:"uint"},183:{type:"master"},247:{type:"uint"},241:{type:"uint"},240:{type:"uint"},178:{type:"uint"},21368:{type:"uint"},234:{type:"uint"},219:{type:"master"},150:{type:"uint"}},Gm=i=>{let e=i.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=Di(i,t),a=r in jm,s=a?jm[r].type:"binary",n=i.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let c=new DataView(i.buffer,i.byteOffset+t+1,o-1),u=n&255>>o,d=Di(c),l=u*2**((o-1)*8)+d,p=t+o,h;return p+l>i.byteLength?h=new DataView(i.buffer,i.byteOffset+p):h=new DataView(i.buffer,i.byteOffset+p,l),{tag:a?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+l,value:h,valueSize:l}},Di=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*2**16+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*2**32+i.getUint32(1);case 6:return i.getUint16(0)*2**32+i.getUint32(2);case 7:{let t=i.getUint8(0)*281474976710656+i.getUint16(1)*4294967296+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},De=(i,e)=>{switch(e){case"int":return i.getInt8(0);case"uint":return Di(i);case"float":return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case"string":return new TextDecoder("ascii").decode(i);case"utf8":return new TextDecoder("utf-8").decode(i);case"date":return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case"master":return i;case"binary":return i;default:HA(e)}},Bt=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=Gm(r);if(!e(a))return;a.type==="master"&&Bt(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},Wm=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=Gm(i);return Bt(a.value,({tag:s,type:n,value:o})=>(s===17143?e=De(o,n):s===17026?t=De(o,n):s===17029&&(r=De(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Qm=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],GA=[231,22612,22743,167,171,163,160,175],WA=i=>{let e,t,r,a,s=!1,n=!1,o=!1,c,u,d=!1,l=0;return Bt(i,({tag:p,type:h,value:m,valueSize:b})=>{if(p===21419){let g=De(m,h);u=Di(g)}else p!==21420&&(u=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=De(m,h):p===17545?a=De(m,h):p===21420&&u===475249515?c=De(m,h):p===374648427?Bt(m,({tag:g,type:v,value:A})=>g===30321?(d=De(A,v)===1,!1):!0):s&&n&&Qm.includes(p)&&(o=!0),!o}),su(e,"Failed to parse webm Segment start"),su(t,"Failed to parse webm Segment end"),su(a,"Failed to parse webm Segment duration"),r=r??1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(a/1e9*r*1e3),cuesSeekPosition:c,is3dVideo:d,stereoMode:l,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},YA=i=>{if(jA(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},QA=(i,e)=>{let t=!1,r=!1,a=o=>Ym(o.time)&&Ym(o.position),s=[],n;return Bt(i,({tag:o,type:c,value:u})=>{switch(o){case 475249515:t=!0;break;case 187:n&&a(n)&&s.push(n),n={};break;case 179:n&&(n.time=De(u,c));break;case 183:break;case 241:n&&(n.position=De(u,c));break;default:t&&Qm.includes(o)&&(r=!0)}return!(t&&r)}),n&&a(n)&&s.push(n),s.map((o,c)=>{let{time:u,position:d}=o,l=s[c+1];return{status:"none",time:{from:u,to:l?l.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:l?e.segmentStart+l.position-1:e.segmentEnd-1}}})},zA=i=>{let e=0,t=!1;try{Bt(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):GA.includes(r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||=[163,160,175].includes(r.tag)),!0):!1)}catch{}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},zm={validateData:Wm,parseInit:WA,getIndexRange:YA,parseSegments:QA,parseFeedableSegmentChunk:zA};var Sr=i=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(i);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return zm;case"mp4":return Hm}}throw new ReferenceError(`Unsupported mime type ${i}`)};var pu=_e(gb(),1);var du=i=>{let e=i.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[a,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[a,s,n]=r;return!!(a&&parseInt(a,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let a=r[0];if(!a||a.length!==6)return!1;let[s,n]=a.toUpperCase(),o=s+n;return["6E","7A","F4"].includes(o)}}return!1};import{isNonNullable as vb,isNullable as yb}from"@vkontakte/videoplayer-shared";var Sb=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var Tb=i=>{if(!i.startsWith("P"))return;let e=(n,o)=>{let c=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(c)?0:c)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),a=r?.[1]==="-"?-1:1,s={days:e(r?.[5],a),hours:e(r?.[6],a),minutes:e(r?.[7],a),seconds:e(r?.[8],a)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},Vt=(i,e)=>{let t=i;t=(0,pu.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[a,s]of Object.entries(r)){let n=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=(0,pu.default)(t,n,(o,c)=>yb(s)?o:yb(c)?s:s.padStart(parseInt(c,10),"0"))}return t},Eb=(i,e)=>{let r=new DOMParser().parseFromString(i,"application/xml"),a={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=s.querySelector("BaseURL")?.textContent?.trim()??"",c=n.children,u=s.getAttribute("type")==="dynamic",d=s.getAttribute("availabilityStartTime"),l=d?new Date(d).getTime():void 0,p,h=s.getAttribute("mediaPresentationDuration"),m=n.getAttribute("duration"),g=s.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=Tb(h);else if(m){let S=Tb(m);vb(S)&&(p=S)}else g&&(p=parseInt(g,10));let v=0,A=s.getAttribute("profiles")?.split(",")??[];for(let S of c){let T=S.getAttribute("id")??"id"+(v++).toString(10),E=S.getAttribute("mimeType")??"",D=S.getAttribute("codecs")??"",O=S.getAttribute("contentType")??E?.split("/")[0],N=S.getAttribute("profiles")?.split(",")??[],k=S.getAttribute("lang")??void 0,w=S.querySelector("Label")?.textContent?.trim()??void 0,$=S.querySelectorAll("Representation"),q=S.querySelector("SegmentTemplate"),ke=S.querySelector("Role")?.getAttribute("value")??void 0,te=O,x={id:T,language:k,isDefault:ke==="main",label:w,codecs:D,hdr:te==="video"&&du(D),mime:E,representations:[]};for(let R of $){let G=R.getAttribute("lang")??void 0,z=R.getAttribute("label")??void 0,he=R.querySelector("BaseURL")?.textContent?.trim()??"",Ve=new URL(he||o,e).toString(),Ut=R.getAttribute("mimeType")??E,gt=R.getAttribute("codecs")??D??"",B;if(O==="text"){let W=R.getAttribute("id")||"",re=W.includes("_auto");B={id:W,isAuto:re,kind:"text",url:Ve}}else{let W=R.getAttribute("contentType")??Ut?.split("/")[0]??O,re=S.getAttribute("profiles")?.split(",")??[],we=parseInt(R.getAttribute("width")??"",10),tt=parseInt(R.getAttribute("height")??"",10),Ht=parseInt(R.getAttribute("bandwidth")??"",10)/1e3,rt=R.getAttribute("frameRate")??"",jt=R.getAttribute("quality")??void 0,Ar=rt?Sb(rt):void 0,sa=R.getAttribute("id")??"id"+(v++).toString(10),Dg=W==="video"?`${tt}p`:W==="audio"?`${Ht}Kbps`:gt,Bg=`${sa}@${Dg}`,Vg=[...A,...N,...re],Vs,Og=R.querySelector("SegmentBase"),St=R.querySelector("SegmentTemplate")??q;if(Og){let vt=R.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[yt,_s]=vt.split("-").map(Gt=>parseInt(Gt,10)),it={from:yt,to:_s},kr=R.querySelector("SegmentBase")?.getAttribute("indexRange"),[Ns,na]=kr?kr.split("-").map(Gt=>parseInt(Gt,10)):[],wr=kr?{from:Ns,to:na}:void 0;Vs={type:"byteRange",url:Ve,initRange:it,indexRange:wr}}else if(St){let vt={representationId:R.getAttribute("id")??void 0,bandwidth:R.getAttribute("bandwidth")??void 0},yt=parseInt(St.getAttribute("timescale")??"",10),_s=St.getAttribute("initialization")??"",it=St.getAttribute("media"),kr=parseInt(St.getAttribute("startNumber")??"",10)??1,Ns=Vt(_s,vt);if(!it)throw new ReferenceError("No media attribute in SegmentTemplate");let na=St.querySelectorAll("SegmentTimeline S")??[],wr=[],Gt=0,Fs="",qs=0;if(na.length){let oa=kr,Re=0;for(let Wt of na){let Oe=parseInt(Wt.getAttribute("d")??"",10),Tt=parseInt(Wt.getAttribute("r")??"",10)||0,ua=parseInt(Wt.getAttribute("t")??"",10);Re=Number.isFinite(ua)?ua:Re;let Us=Oe/yt*1e3,Ng=Re/yt*1e3;for(let ca=0;ca<Tt+1;ca++){let Fg=Vt(it,{...vt,segmentNumber:oa.toString(10),segmentTime:(Re+ca*Oe).toString(10)}),Uu=(Ng??0)+ca*Us,qg=Uu+Us;oa++,wr.push({time:{from:Uu,to:qg},url:Fg})}Re+=(Tt+1)*Oe,Gt+=(Tt+1)*Us}qs=Re/yt*1e3,Fs=Vt(it,{...vt,segmentNumber:oa.toString(10),segmentTime:Re.toString(10)})}else if(vb(p)){let Re=parseInt(St.getAttribute("duration")??"",10)/yt*1e3,Wt=Math.ceil(p/Re),Oe=0;for(let Tt=1;Tt<Wt;Tt++){let ua=Vt(it,{...vt,segmentNumber:Tt.toString(10),segmentTime:Oe.toString(10)});wr.push({time:{from:Oe,to:Oe+Re},url:ua}),Oe+=Re}qs=Oe,Fs=Vt(it,{...vt,segmentNumber:Wt.toString(10),segmentTime:Oe.toString(10)})}let _g={time:{from:qs,to:1/0},url:Fs};Vs={type:"template",baseUrl:Ve,segmentTemplateUrl:it,initUrl:Ns,totalSegmentsDurationMs:Gt,segments:wr,nextSegmentBeyondManifest:_g,timescale:yt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!W||!Ut)continue;let Os={video:"video",audio:"audio",text:"text"}[W];if(!Os)continue;te||=Os,B={id:Bg,kind:Os,segmentReference:Vs,profiles:Vg,duration:p,bitrate:Ht,mime:Ut,codecs:gt,width:we,height:tt,fps:Ar,quality:jt}}x.language||=G,x.label||=z,x.mime||=Ut,x.codecs||=gt,x.hdr||=te==="video"&&du(gt),x.representations.push(B)}te&&a[te].push(x)}return{dynamic:u,liveAvailabilityStartTime:l,duration:p,streams:a}};var Bi=_e(ri(),1);import{videoSizeToQuality as Rk}from"@vkontakte/videoplayer-shared";var xb=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s})=>{let n=(s?ct(s):void 0)??Rk({width:e,height:t});return n&&{id:i,quality:n,bitrate:r,size:{width:e,height:t},fps:a}},Pb=({id:i,bitrate:e})=>({id:i,bitrate:e}),cs=(i,e,t)=>{let r=e.indexOf(i);return(0,Bi.default)(t,Math.round(t.length*r/e.length))??(0,Bi.default)(t,-1)},Ab=({language:i,label:e},{id:t,url:r,isAuto:a})=>({id:t,url:r,isAuto:a,type:"internal",language:i,label:e}),fu=({id:i,language:e,label:t,codecs:r,isDefault:a})=>({id:i,language:e,label:t,codec:(0,Bi.default)(r.split("."),0),isDefault:a}),mu=({id:i,language:e,label:t,hdr:r,codecs:a})=>({id:i,language:e,hdr:r,label:t,codec:(0,Bi.default)(a.split("."),0)}),ls=i=>"url"in i,Ze=i=>i.type==="template",Vi=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var _i=class{constructor(e,t,r,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:c=!1,manifest:u}){this.currentSegmentLength$=new Oi(0);this.onLastSegment$=new Oi(!1);this.fullyBuffered$=new Oi(!1);this.playingRepresentation$=new Oi(void 0);this.playingRepresentationInit$=new Oi(void 0);this.error$=new Lk;this.gaps=[];this.subscription=new Mk;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Je;this.destroyAbortController=new Je;this.bufferLimit=1/0;this.failedDownloads=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=yr(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Ue(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Um(this.sourceBuffer),this.subscription.add(bu(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,c=this.mediaSource.readyState;c!=="open"&&(o={id:`SegmentEjection_source_${c}`,category:Ot.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:Ot.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add(bu(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Ot.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let c=Math.min(this.bufferLimit,iu(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=c,this.tuning.useNewPruneBufferStrategy){let u=ze(this.sourceBuffer.buffered,o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,n*2,u<d)}else this.pruneBufferOld(o,n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),a=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Ue(r,"No init buffer for starting representation"),Ue(a,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(a,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=yr(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);Ue(r,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if(Ae(s)||Ae(a)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),Ue(a,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();Su(n)&&(this.isLive||(a.forEach(o=>o.status="none"),this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=yr(this.destroyAbortController.signal,async function*(e){let t=e?.flatMap(c=>c.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let u=t.find(p=>p.id===c);u&&this.representations.set(c,u);let d=this.representations.get(c);if(!d||!Ze(d.segmentReference))return;let l=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,l)}let r=this.switchingToRepresentationId??this.downloadingRepresentationId,a=this.representations.get(r);Ue(a);let s=this.segments.get(r);Ue(s,"No segments for starting representation");let n=this.initData.get(r);if(Ue(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,a),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=a,this.tuning=s,this.compatibilityMode=c,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!u?.dynamic,this.resetAccumulateBufferAfterStall(),this.startAccumulateBuffer(),this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Je,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Ae(e)||Ae(this.downloadingRepresentationId)||Ae(this.playingRepresentationId)||Ae(this.sourceBuffer)||!Ae(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(Ue(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let a=r.find(u=>e>=u.time.from&&e<u.time.to);this.currentSegmentLength$.next((a?.time.to??0)-(a?.time.from??0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=ze(this.sourceBuffer.buffered,e),l=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=a.time.to-e+100&&(s=l)}if(isFinite(this.bufferLimit)&&iu(this.sourceBuffer.buffered)>=this.bufferLimit){let u=ze(this.sourceBuffer.buffered,e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<d);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(o.includes(a))u="high";else{let d=(0,Tr.default)(o,0);d&&d.time.from-a.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(o,t,u)}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!o.length&&ze(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let c=(0,Tr.default)(r,-1);c&&c.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===c))}searchGaps(e,t){this.gaps=[];let r=0,a=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+a}),r=s.time.to;Su(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,a=[],s=0,n=t.length-1;do a.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[a[0]]:a}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind].flatMap(a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){let t=e?.streams[this.kind].flatMap(r=>r.representations)??[];for(let r of t){if(!r||!Ze(r.segmentReference))return;let a=r.segmentReference.segments.map(c=>({...c,status:"none",size:void 0})),s=this.segments.get(r.id)??[],n=(0,Tr.default)(s,-1)?.time.to??0,o=a?.findIndex(c=>Math.floor(n)>=Math.floor(c.time.from)&&Math.floor(n)<=Math.floor(c.time.to));if(o===-1){this.liveUpdateSegmentIndex=0;let c=this.getActualLiveStartingSegments(r.segmentReference);this.segments.set(r.id,c)}else{let c=a.slice(o+1);this.segments.set(r.id,[...s,...c])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Ue(e);let t=this.segments.get(e);if(t?.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}startAccumulateBuffer(){this.bufferAccumulation.enabled=!0}resetAccumulateBufferAfterStall(){this.bufferAccumulation={enabled:!1,targetBufferSizeMs:this.tuning.accumulationBufferStallSizeMs,accumulatedBufferSizeMs:0,accumulated:[]}}updateLowLatencyLiveIfNeeded(e){for(let t of this.representations.values()){let r=t.segmentReference;if(!Ze(r))return;let a=this.segments.get(t.id)??[],s=a.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(s&&!isFinite(s.time.to)&&(s.time.to=e.time.to),!!!a.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),c=Vt(r.segmentTemplateUrl,{segmentTime:o});a.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);return r?r.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(a=>t>=a.time.from&&t<a.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let a=e.findIndex(({status:l,time:{from:p,to:h}},m)=>{let b=p<=r&&h>=r,g=p>r||b||m===0&&r===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),A=this.preloadOnly&&p<=r+v||h<=r+v;return(l==="none"||l==="partially_ejected"&&g&&A&&this.sourceBuffer&&!fi(this.sourceBuffer.buffered,r))&&g&&A});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let s=e,n=0,o=0,c=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let l=a;l<s.length&&(n<=u||o<=d);l++){let p=s[l];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")c.push(p);else break}return c}async loadSegments(e,t,r="auto"){t.segmentReference.type==="template"?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){e.status="downloading";let a={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(a);let{range:s,url:n,signal:o,onProgress:c,onProgressTasks:u}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await yr(o,async function*(){let d=gu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:c,priority:r,isLowLatency:this.isActiveLowLatency()});if(!d)return;let l=new DataView(d);if(!isFinite(a.segment.time.to)){let p=t.segmentReference.timescale,h=Sr(t.mime);a.segment.time.to=h.getSegmentEndTime(l,p)}c&&a.feedingBytes&&u?await Promise.all(u):await this.sourceBufferTaskQueue.append(l,o),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Vi(d)||this.failedDownloads++}}async loadByteRangeSegments(e,t,r="auto"){if(!e.length)return;for(let c of e)c.status="downloading",this.activeSegments.add({segment:c,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:a,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await yr(n,async function*(){let c=gu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(u,c),bu(window,"online").pipe($k()).subscribe(()=>{u(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:a,onProgress:o,signal:n,priority:r}),this.failedDownloads=0}catch(c){this.abortActiveSegments(e),Vi(c)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(Ze(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,Tr.default)(e,0).byte.from,to:(0,Tr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:a,signal:s,onProgress:(o,c)=>{if(!s.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:a?a.from:0,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:Ot.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ze(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let a=r.toString(),{signal:s}=this.downloadAbortController,n=[],c=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(u,d)=>{if(!s.aborted)try{let l=this.onSomeTemplateDataLoaded({dataView:u,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(l)}catch(l){this.error$.next({id:"SegmentFeeding",category:Ot.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}:void 0;return{url:a,signal:s,onProgress:c,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:a,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:c}=o;if(o.representationId===t){if(s.aborted){a();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let u=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=Sr(n.mime).parseFeedableSegmentChunk(u,this.isLive);d?.byteLength&&(c.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){let o={dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let c=o.segmentReference.type,u=e.byteLength;for(let d of this.activeSegments){let{segment:l}=d,p=c==="byteRange",h=p?l.byte.to-l.byte.from+1:u;if(d.representationId!==t||!(!p||l.byte.from>=r&&l.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let b=p?l.byte.from-r:0,g=p?l.byte.to-r:e.byteLength,v=b<a,A=g<=a;if(l.status==="downloading"&&v&&A){l.status="downloaded";let y=new DataView(e.buffer,e.byteOffset+b,h),S=this.getCurrentPosition();Su(S)&&(this.bufferAccumulation.accumulatedBufferSizeMs=l.time.to-S,this.bufferAccumulation.accumulated.push({segmentView:y,segmentProgress:d}),this.activeSegments.delete(d));let T=({segmentView:E,segmentProgress:D})=>this.sourceBufferTaskQueue.append(E,s).then(O=>O&&!s.aborted?this.onSegmentFullyAppended(D,t):n());this.bufferAccumulation.enabled&&this.bufferAccumulation.targetBufferSizeMs<this.bufferAccumulation.accumulatedBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(T),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||Ae(S))&&(T({segmentView:y,segmentProgress:d}),this.resetAccumulateBufferAfterStall())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&v&&!A&&(d.loadedBytes=Math.min(h,a-b),d.loadedBytes>d.feedingBytes)){let y=new DataView(e.buffer,e.byteOffset+b+d.feedingBytes,d.loadedBytes-d.feedingBytes),S=d.loadedBytes===h?y:Sr(o.mime).parseFeedableSegmentChunk(y);S?.byteLength&&(l.status="partially_fed",d.feedingBytes+=S.byteLength,this.sourceBufferTaskQueue.append(S,s).then(T=>{if(s.aborted)n();else if(T)d.fedBytes+=S.byteLength,d.fedBytes===h&&this.onSegmentFullyAppended(d,t);else{if(d.feedingBytes<h)return;n()}}))}}}async onSomeByteRangesDataLoadedNew({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let c of this.activeSegments){let{segment:u}=c;if(c.representationId!==t)continue;if(s.aborted){n();continue}let d=u.byte.from-r,l=u.byte.to-r,p=l-d+1,h=d<a,m=l<=a;if(h){if(u.status==="downloading"&&m){u.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+d,p);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(c,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(u.status==="downloading"||u.status==="partially_fed")&&(c.loadedBytes=Math.min(p,a-d),c.loadedBytes>c.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+d+c.feedingBytes,c.loadedBytes-c.feedingBytes),g=c.loadedBytes===p?b:Sr(o.mime).parseFeedableSegmentChunk(b);g?.byteLength&&(u.status="partially_fed",c.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(c.fedBytes+=g.byteLength,c.fedBytes===p&&this.onSegmentFullyAppended(c,t)):n())}}}}onSegmentFullyAppended(e,t){this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",ls(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let a of this.segments.get(r.id)??[])a.status==="fed"&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){(this.tuning.useDashAbortPartiallyFedSegment?e.status==="partially_fed"||e.status==="partially_ejected":e.status==="partially_ejected")?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status="none"),e.status="partially_ejected"):e.status="none";for(let r of this.activeSegments.values())if(r.segment===e){this.activeSegments.delete(r);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[a,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=eu(()=>(0,kb.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",r=!1){let a=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?yr(this.destroyAbortController.signal,async function*(){let o=gu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Sr(e.mime),a)).then(async o=>{if(!o)return;let{init:c,dataView:u,segments:d}=o,l=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,l);let p=d;this.isLive&&Ze(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),c&&this.parsedInitData.set(e.id,c)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:Ot.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,r=!1){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,r):this.pruneBufferOld(e,t,r)}async pruneBufferNew(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Ae(e)||this.sourceBuffer.updating)return!1;let a=[],s=0,n=c=>{c.sort((d,l)=>d.from-l.from);let u=[c[0]];for(let d=1;d<c.length;d++){let{from:l,to:p}=c[d],h=u[u.length-1];h.to>=l?h.to=Math.max(h.to,p):u.push(c[d])}return u},o=c=>{if(s>=t)return a;a.push(c.time),a=n(a);let u=ls(c)?c.size??0:c.byte.to-c.byte.from;s+=u};for(let c of this.segments.values())for(let u of c){let d=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,l=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||l)&&u.status==="fed"&&o(u)}for(let c=0;c<this.sourceBuffer.buffered.length;c++){let u=this.sourceBuffer.buffered.start(c)*1e3,d=this.sourceBuffer.buffered.end(c)*1e3,l=0;for(let p of this.segments.values())for(let h of p)h.status==="none"&&Math.round(h.time.from)<=Math.round(u)&&Math.round(h.time.to)>=Math.round(d)&&l++;if(l===this.segments.size){let p={time:{from:u,to:d},url:"",status:"none"};o(p)}}if(a.length&&r){let c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let d of u)d.time.from>=e+c&&d.status==="fed"&&o(d)}return a.length?(await Promise.all(a.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,d)=>u||d,!1):!1}async pruneBufferOld(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Ae(e)||this.sourceBuffer.updating)return!1;let a=0,s=1/0,n=-1/0,o=!1,c=u=>{s=Math.min(s,u.time.from),n=Math.max(n,u.time.to);let d=ls(u)?u.size??0:u.byte.to-u.byte.from;a+=d};for(let u of this.segments.values())for(let d of u){if(d.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;d.status==="fed"&&c(d)}if(o=isFinite(s)&&isFinite(n),!o){a=0,s=1/0,n=-1/0;for(let u of this.segments.values())for(let d of u){if(d.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||a>t)break;d.status==="fed"&&c(d)}}if(o=isFinite(s)&&isFinite(n),!o)for(let u=0;u<this.sourceBuffer.buffered.length;u++){let d=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3;for(let p of this.segments.values())for(let h of p)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(d)&&Math.round(h.time.to)>=Math.round(l)){s=d,n=l;break}}if(o=isFinite(s)&&isFinite(n),!o&&r){a=0,s=1/0,n=-1/0;let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let d of this.segments.values())for(let l of d)l.time.from>e+u&&l.status==="fed"&&c(l)}return o=isFinite(s)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(s,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let a={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){a=void 0;break}o>r.time.from&&o<r.time.to&&(a.from=o),n<r.time.to&&n>r.time.from&&(a.to=n)}}a&&a.to-a.from>1&&!this.gaps.some(s=>a&&s.from===a.from&&s.to===a.to)&&this.gaps.push(a)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=eu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Ot.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(Ae(this.sourceBuffer)||Ae(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let a=Math.round(this.sourceBuffer.buffered.start(r)*1e3),s=Math.round(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:a,to:s})}let t=1;for(let r of this.segments.values())for(let a of r){let{status:s}=a;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(a.time.from),o=Math.ceil(a.time.to),c=e.some(d=>d.from-t<=n&&d.to+t>=o),u=e.filter(d=>n>=d.from-t&&n<=d.to+t||o>=d.from-t&&o<=d.to+t);c||(u.length===1?a.status="partially_ejected":this.gaps.some(d=>d.from===a.time.from||d.to===a.time.to)?a.status="partially_ejected":a.status="none")}}};var Ni=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var wb=i=>{let e=i.get("X-Delivery-Type"),t=i.get("X-Reused"),r=e===null?"http1":e??void 0,a=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:r,reused:a}};import{abortable as Fi,assertNever as Rb,fromEvent as $b,merge as Ck,now as qi,Subscription as Dk,ValueSubject as vu,flattenObject as Ir}from"@vkontakte/videoplayer-shared";var ds=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:a=!1}){this.lastConnectionType$=new vu(void 0);this.lastConnectionReused$=new vu(void 0);this.lastRequestFirstBytes$=new vu(void 0);this.abortAllController=new Je;this.subscription=new Dk;this.fetchManifest=Fi(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Ni(r));let a=yield Ke(r,{signal:this.abortAllController.signal}).catch(Ui);return a?(t.log("success",Ir({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(a.headers),a.text()):(t.error("error",Ir({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Fi(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:a,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:c=!1}={}){let u=e,d=new Headers,l=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let w=new URL(u,location.href);w.searchParams.append("bytes",`${r.from}-${r.to}`),u=w.toString();break}default:Rb(t)}this.requestQuic&&(u=Ni(u));let p=this.abortAllController.signal,h;if(n){let w=new Je;if(h=Ck($b(this.abortAllController.signal,"abort"),$b(n,"abort")).subscribe(()=>{try{w.abort()}catch($){Ui($)}}),this.abortAllController.signal.aborted||n.aborted)try{w.abort()}catch($){Ui($)}p=w.signal}let m=qi();l.log("startRequest",Ir({url:u,priority:s,rangeMethod:t,range:r,isLowLatency:c,requestStartedAt:m}));let b=yield Ke(u,{priority:s,headers:d,signal:p}).catch(Ui),g=qi();if(!b)return l.error("error",{message:"No response in request"}),l.end(),h?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(g-m),!b.ok||!b.body){h?.unsubscribe();let w=`Fetch error ${b.status}: ${b.statusText}`;return l.error("error",{message:w}),l.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!a&&!o){h?.unsubscribe();let w=qi(),$={requestStartedAt:m,requestEndedAt:w,duration:w-m};return l.log("endRequest",Ir($)),l.end(),b.arrayBuffer()}let[v,A]=b.body.tee(),y=v.getReader();o&&this.throughputEstimator?.trackStream(A,c);let S=0,T=new Uint8Array(0),E=!1,D=w=>{h?.unsubscribe(),E=!0,Ui(w)},O=Fi(p,async function*({done:w,value:$}){if(S===0&&this.lastRequestFirstBytes$.next(qi()-m),p.aborted){h?.unsubscribe();return}if(!w&&$){let q=new Uint8Array(T.length+$.length);q.set(T),q.set($,T.length),T=q,S+=$.byteLength,a?.(new DataView(T.buffer),S),yield y?.read().then(O,D)}}.bind(this));yield y?.read().then(O,D),h?.unsubscribe();let N=qi(),k={failed:E,requestStartedAt:m,requestEndedAt:N,duration:N-m};return E?(l.error("endRequest",Ir(k)),l.end(),null):(l.log("endRequest",Ir(k)),l.end(),T.buffer)}.bind(this));this.fetchByteRangeRepresentation=Fi(this.abortAllController.signal,async function*(e,t,r){if(e.type!=="byteRange")return null;let{from:a,to:s}=e.initRange,n=a,o=s,c=!1,u,d;e.indexRange&&(u=e.indexRange.from,d=e.indexRange.to,c=s+1===u,c&&(n=Math.min(u,a),o=Math.max(d,s))),n=Math.min(n,0);let l=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!l)return null;let p=new DataView(l,a-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let b;if(c)b=new DataView(l,m.from-n,m.to-m.from+1);else{let v=yield this.fetch(e.url,{range:m,priority:r,measureThroughput:!1});if(!v)return null;b=new DataView(v)}let g=t.parseSegments(b,h,m);return{init:h,dataView:new DataView(l),segments:g}}.bind(this));this.fetchTemplateRepresentation=Fi(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),a=yield this.fetch(r,{priority:t,measureThroughput:!1});return a?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(a)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=a,this.tracer=r.createComponentTracer("Fetcher")}onHeadersReceived(e){let{type:t,reused:r}=wb(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){let{type:a}=e;switch(a){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,r)??null;case"template":return await this.fetchTemplateRepresentation(e,r)??null;default:Rb(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Ui=i=>{if(!Vi(i))throw i};var _t=(i,e,t)=>t*e+(1-t)*i,yu=(i,e)=>i.reduce((t,r)=>t+r,0)/e,Lb=(i,e,t,r)=>{let a=0,s=t,n=yu(i,e),o=e<r?e:r;for(let c=0;c<o;c++)i[s]>n?a++:a--,s=(i.length+s-1)%i.length;return Math.abs(a)===o};import{isNullable as Bk,ValueSubject as Mb}from"@vkontakte/videoplayer-shared";var dt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Mb(e.initial),this.debounced$=new Mb(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new X(`raw_${t}`),this.smoothedSeries$=new X(`smoothed_${t}`),this.reportedSeries$=new X(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,r++);this.takenMeasures=r,t/=r;let a=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*a,n=this.smoothed-this.params.deviationFactor*a;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(Bk(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var ps=class extends dt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=_t(this.slow,e,this.params.emaAlphaSlow),this.fast=_t(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var hs=class extends dt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=yu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=_t(this.emaSmoothed,e,this.params.emaAlpha);let r=Lb(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var fs=class extends dt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?_t(this.smoothed,t,this.params.emaAlpha):t}};var Nt=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new ps({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new hs({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new fs({initial:e,label:"liveEdgeDelay",...t})}};var Tu=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};var _b=["timeupdate","progress","play","seeked","stalled","waiting"];var gs=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Ob;this.representationSubscription=new Ob;this.state$=new L("none");this.currentVideoRepresentation$=new Z(void 0);this.currentVideoRepresentationInit$=new Z(void 0);this.currentAudioRepresentation$=new Z(void 0);this.currentVideoSegmentLength$=new Z(0);this.currentAudioSegmentLength$=new Z(0);this.error$=new Vb;this.lastConnectionType$=new Z(void 0);this.lastConnectionReused$=new Z(void 0);this.lastRequestFirstBytes$=new Z(void 0);this.isLive$=new Z(!1);this.liveDuration$=new Z(0);this.liveAvailabilityStartTime$=new Z(void 0);this.bufferLength$=new Z(0);this.liveLoadBufferLength$=new Z(0);this.livePositionFromPlayer$=new Z(0);this.timeInWaiting=0;this.isActiveLowLatency$=new Z(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new Vb;this.gapWatchdogActive=!1;this.destroyController=new Je;this.initManifest=Iu(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=K(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:pt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Iu(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:pt.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t;try{t=Eb(e??"",this.manifestUrlString)}catch(n){let o=Om(e)??{id:"ManifestParsing",category:pt.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(o)}if(!t)return null;let r=(n,o,c)=>!!(this.element?.canPlayType?.(o)&&Xe()?.isTypeSupported?.(`${o}; codecs="${c}"`)||n==="text");t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let a={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let c=t.streams[n].filter(({mime:l,codecs:p})=>r(n,l,p)),u=new Set(c.map(({codecs:l})=>l)),d=Vm(u);if(d&&(a[n]=c.filter(({codecs:l})=>l.startsWith(d))),n==="video"){let l=this.tuning.preferHDR,p=a.video.some(m=>m.hdr),h=a.video.some(m=>!m.hdr);Fk.isHDR&&l&&p?a.video=a.video.filter(m=>m.hdr):h&&(a.video=a.video.filter(m=>!m.hdr))}}let s={...t,streams:a};return this.tracer.log("updateManifestEnd",Hi(s)),s}.bind(this));this.initRepresentations=Iu(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initRepresentationsStart",Hi({initialVideo:e,initialAudio:t,sourceHls:r})),Ft(this.manifest),Ft(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=l=>{this.representationSubscription.add(Er(l,"error").pipe(bs(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:pt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=this.tuning.useManagedMediaSource?wm():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&as())if(r){let l=document.createElement("source");a(l),l.type="application/x-mpegurl",l.src=r.url,this.element.appendChild(l)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((l,p)=>[...l,...p.representations],[]);if(this.videoBufferManager=new _i("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Bb(t)){let l=this.manifest.streams.audio.reduce((p,h)=>[...p,...h.representations],[]);this.audioBufferManager=new _i("audio",this.source,l,n),this.bufferManagers.push(this.audioBufferManager)}if(this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Eu(1e3).subscribe(l=>{if(this.element?.paused){let p=Co(this.manifestUrlString,2);this.manifestUrlString=K(this.manifestUrlString,p+1e3,2)}})),this.representationSubscription.add(xr(..._b.filter(l=>l!=="waiting").map(l=>Er(this.element,l))).pipe(xu(l=>this.element?ze(this.element.buffered,this.element.currentTime*1e3):0),Db(),bs(l=>!!l),_k(l=>{this.stallWatchdogSubscription?.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Db()).subscribe(p=>Tu(this.element,1))),this.representationSubscription.add(ms({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(bs(({bufferLength:p,isActiveLowLatency:h})=>h&&!!p)).subscribe(({bufferLength:p})=>this.liveEstimatedDelay.next(p))),this.representationSubscription.add(ms({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:p,isActiveLowLatency:h})=>{if(!h)return;let m=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,b=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,g=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,v=p-m,A=1;Math.abs(v)>b&&(A=1+Math.sign(v)*g),Tu(this.element,A)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let h=0;if(p){let m=(this.element?.currentTime??0)*1e3;h=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??m))-m}this.liveLoadBufferLength$.getValue()!==h&&this.liveLoadBufferLength$.next(h)}));let l=0;this.representationSubscription.add(ms({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Nk(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:h})=>{if(Ft(this.element),this.isUpdatingLive)return;let m=this.element.playbackRate,b=Co(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*m),A=this.tuning.dashCmafLive.normalizedActualBufferOffset*m,y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*m,S=isFinite(p)?p:h,T=this.isActiveLowLatency$.getValue(),E=g<=this.tuning.live.activeLiveDelay&&b===0;this.isActiveLowLatency$.next(T&&E);let D="none";if(T?D="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&E?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(O=>O.proceedLowLatencyLive()),D="active_low_latency"):b!==0&&S<v?D="live_forward_buffering":S<v+y&&(D="live_with_target_offset"),isFinite(p)&&(l=p>l?p:l),D==="live_forward_buffering"||D==="live_with_target_offset"){let O=l-(v+A),N=this.normolizeLiveOffset(Math.trunc(b+O/m)),k=Math.abs(N-b),w;!p||k<=this.tuning.dashCmafLive.offsetCalculationError?w=b:N>0&&k>this.tuning.dashCmafLive.offsetCalculationError?w=N:w=0,this.manifestUrlString=K(this.manifestUrlString,w,2)}D!=="none"&&D!=="active_low_latency"&&(l=0,this.updateLive())}))}let c=xr(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe(xu(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),u=xr(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe(xu(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue())));this.representationSubscription.add(xr(this.forceEnded$,ms({allBuffersFull:c,someBufferEnded:u}).pipe(bs(({allBuffersFull:l,someBufferEnded:p})=>l&&p))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(l=>!l.updating))try{this.source?.endOfStream()}catch(l){this.error$.next({id:"EndOfStream",category:pt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:l})}})),this.representationSubscription.add(xr(...this.bufferManagers.map(l=>l.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.source.readyState!=="open"&&(yield new Promise(l=>this.source?.addEventListener("sourceopen",l)));let d=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(l=>l.representations).flatMap(l=>{let p=[];return l.duration&&p.push(l.duration),Ze(l.segmentReference)&&l.segmentReference.totalSegmentsDurationMs&&p.push(l.segmentReference.totalSegmentsDurationMs),p})];this.source.duration=Math.max(...d)/1e3,this.audioBufferManager&&Bb(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Eu(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:pt.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new ds({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=Nt.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator}),this.initTracerSubscription()}async seekLive(e){Ft(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=K(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest?.streams.video),await this.audioBufferManager?.seekLive(this.manifest?.streams.audio))}initBuffer(){Ft(this.element),this.state$.setState("running"),this.subscription.add(xr(..._b.map(e=>Er(this.element,e)),Er(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:pt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Er(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Er(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&fi(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element)return;this.timeInWaiting+=1e3;let t={timeInWaiting:this.timeInWaiting};if(this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset),t={...t,liveLastSeekOffset:this.liveLastSeekOffset};else{let r=this.element.currentTime*1e3;this.videoBufferManager?.maintain(r),this.audioBufferManager?.maintain(r),t={...t,position:r}}this.tracer.log("stallIntervalCallback",Hi(t))};this.videoBufferManager?.startAccumulateBuffer(),this.audioBufferManager?.startAccumulateBuffer(),this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=Eu(1e3).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:pt.FATAL,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,r)}seek(e,t){Ft(this.element),Ft(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),fi(this.element.buffered,r)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.startAccumulateBuffer(),this.videoBufferManager.maintain(r),this.audioBufferManager?.startAccumulateBuffer(),this.audioBufferManager?.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",Hi({requestedPosition:e,forcePrecise:t,position:r}))}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>e.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=qk(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,a=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?a.push(1/0):a.push(o.to));if(a.length){let n=Math.max(...a)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t={...t,gapEnds:a,jumpTo:n,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Hi(t)))}}};var Ss=class{constructor(e,t){this.fov=e,this.orientation=t}};var vs=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let a=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:a,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=r??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let a=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*a,this.fadeStartSpeed.y*a,this.fadeStartSpeed.z*a),a>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Nb=`attribute vec2 a_vertex;
38
59
  attribute vec2 a_texel;
39
60
 
40
61
  varying vec2 v_texel;
@@ -45,7 +66,7 @@ void main(void) {
45
66
  // save texel vector to pass to fragment shader
46
67
  v_texel = a_texel;
47
68
  }
48
- `;var wb=`#ifdef GL_ES
69
+ `;var Fb=`#ifdef GL_ES
49
70
  precision highp float;
50
71
  precision highp int;
51
72
  #else
@@ -88,5 +109,5 @@ void main(void) {
88
109
  // sample using new coordinates
89
110
  gl_FragColor = texture2D(u_texture, tc);
90
111
  }
91
- `;var hs=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 ds(this.params.fov,this.params.orientation),this.cameraRotationManager=new ps(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(Ab,this.gl.VERTEX_SHADER),r=this.createShader(wb,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,a=this.frameHeight/(this.frameWidth/this.viewportWidth);return a>this.viewportHeight?t=this.viewportHeight/a:r=a/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,a=this.camera.fov.y/180/2,s=e-r,n=t-a,o=e+r,l=t-a,u=e+r,c=t+a,d=e-r,p=t+a;return[s,n,o,l,u,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var Vt=class{constructor(e){this.subscription=new Hw;this.videoState=new L("stopped");this.elementSize$=new jw(void 0);this.textTracksManager=new ye;this.droppedFramesManager=new Wa;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ha;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 Bw(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new hs(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=re(e.container,e.tuning),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Y(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new cs({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=se(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:yu.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(kb(u=>!!u.length),$b()).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(kb(Nw),$b()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(Lb(u=>u.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(_e(this.video,t.isLooped,a)),this.subscription.add(ae(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(ve(this.video,t.playbackRate,r.playbackRateState$,a)),s(Uw(this.video),this.elementSize$),s(Ie(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},a)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{if(u==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if(Ow(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(uu(h));let m=[];for(let b of h.representations){let S=pb(b);m.push(S),this.audioTracksMap.set(S,{stream:h,representation:b})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(p)}let d=[];for(let p of c.video){d.push(lu(p));let h=[];for(let m of p.representations){let b=db(m);b&&(h.push(b),this.videoTracksMap.set(b,{stream:p,representation:m}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(d);for(let p of c.text)for(let h of p.representations){let m=hb(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:yu.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(fs(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$,_w(this.video,"progress")).subscribe(()=>{let u=this.player.state$.getState(),c=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(u)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[p,h]=d,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(Tu()).subscribe(u=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===u);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(lu(p))},a)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Tu()).subscribe(u=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===u);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(uu(p))},a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{if(u?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch(c){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${c}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},a)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,a)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,a)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(Lb(({to:u})=>u==="ready"),Tu());this.subscription.add(fs(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let u=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add(fs(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=fs(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,qw(["init"])).pipe(Vw(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:E})=>E===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:E})=>E===l.id),c=u&&this.videoStreamsMap.get(u);if(!c)return;let d=We(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(d/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),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,S=0;if(b){if(n&&!r){let E=rs(n,c,this.audioStreamsMap.get(b)??[]);S=Math.max(S,E?.bitrate??-1/0)}if(o){let E=rs(o,c,this.audioStreamsMap.get(b)??[]);S=Math.max(S,E?.bitrate??-1/0)}}let v=ut(c,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:S,forwardBufferHealth:h,current:o,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),{backgroundVideoQualityLimit:w}=this.params.tuning.autoTrackSelection;!this.params.output.elementVisible$.getValue()&&r&&(v=c.filter(E=>!Fw(E.quality)).sort((E,k)=>(k.bitrate??0)-(E.bitrate??0)).filter(E=>Rb(E.quality,v.quality)&&Rb(E.quality,w))[0]??v);let T=r?v??n:n??v,g=b&&rs(T,c,this.audioStreamsMap.get(b)??[]),y=this.videoTracksMap.get(T)?.representation,$=g&&this.audioTracksMap.get(g)?.representation;if(y&&$)return[y,$];if(y&&!$&&this.audioTracksMap.size===0)return[y,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ne(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:yu.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),ie(this.video)}};var Vi=class extends Vt{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 Mb,interval as Gw,map as Yw}from"@vkontakte/videoplayer-shared";var _i=class extends Vt{constructor(e){super(e),this.liveOffset=new Ge}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(Mb({interval:Gw(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(Mb({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Yw(({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 Db=Oe(Fa(),1);import{assertNever as Ni,assertNonNullable as Cb,debounce as Ww,ErrorCategory as ms,filter as Qw,isNonNullable as zw,isNullable as Kw,map as bs,merge as Jw,Observable as Xw,observableFrom as Zw,Subscription as ek,videoSizeToQuality as tk}from"@vkontakte/videoplayer-shared";var Ce={};var yr=(i,e)=>new Xw(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),Fi=class{constructor(e){this.subscription=new ek;this.videoState=new L("initializing");this.textTracksManager=new ye;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:Ni(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Ni(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Ni(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:Ni(e)}break;default:Ni(t)}};this.video=re(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Y(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),ie(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:ms.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Db.default)(import("hls.js").then(a=>{e||(Ce.Hls=a.default,Ce.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){Cb(Ce.Hls,"hls.js not loaded"),this.hls=new Ce.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Cb(Ce.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=u=>{t.error$.next({id:"HlsJsProvider",category:ms.WTF,message:"HlsJsProvider internal logic error",thrown:u})},a=se(this.video),s=(u,c)=>this.subscription.add(u.subscribe(c,r));s(a.timeUpdate$,t.position$),s(a.durationChange$,t.duration$),s(a.ended$,t.endedEvent$),s(a.looped$,t.loopedEvent$),s(a.error$,t.error$),s(a.isBuffering$,t.isBuffering$),s(a.currentBuffer$,t.currentBuffer$),s(a.loadStart$,t.firstBytesEvent$),s(a.loadedMetadata$,t.loadedMetadataEvent$),s(a.playing$,t.firstFrameEvent$),s(a.canplay$,t.canplay$),s(a.seeked$,t.seekedEvent$),s(a.inPiP$,t.inPiP$),s(a.inFullscreen$,t.inFullscreen$),this.subscription.add(_e(this.video,e.isLooped,r)),this.subscription.add(ae(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ve(this.video,e.playbackRate,a.playbackRateState$,r)),s(Ie(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(bs(u=>u.to)),this.params.output.playbackState$),this.subscription.add(yr(this.hls,Ce.Events.ERROR).subscribe(u=>{u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:ms.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(yr(this.hls,Ce.Events.MANIFEST_PARSED).pipe(bs(({levels:u})=>u.reduce((c,d)=>{let p=d.name||d.height.toString(10),{width:h,height:m}=d,b=nt(d.attrs.QUALITY??"")??tk({width:h,height:m});if(!b)return c;let S=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:m},fps:S};return this.trackLevels.set(p,{track:v,level:d}),c.push(v),c},[]))),t.availableVideoTracks$),s(yr(this.hls,Ce.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){let c=[];for(let d of u.subtitleTracks){let p=d.name,h=d.attrs.URI||"",m=d.lang;c.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(yr(this.hls,Ce.Events.LEVEL_LOADING).pipe(bs(({url:u})=>Y(u))),t.hostname$),s(yr(this.hls,Ce.Events.FRAG_CHANGED),u=>{let{video:c,audio:d}=u.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3)}),this.subscription.add(it(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:r}));let n=u=>Array.from(this.trackLevels.values()).find(({level:c})=>c===u)?.track,o=yr(this.hls,Ce.Events.LEVEL_SWITCHED).pipe(bs(({level:u})=>n(this.hls.levels[u])));o.pipe(Qw(zw)).subscribe(t.currentVideoTrack$,r),this.subscription.add(it(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),u=>{if(Kw(u))return;let c=this.trackLevels.get(u.id)?.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let l=Jw(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Zw(["init"])).pipe(Ww(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 ne(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ms.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 Bb="X-Playback-Duration",Iu=async i=>{let e=await Qe(i),t=await e.text(),r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return r?parseInt(r,10):e.headers.has(Bb)?parseInt(e.headers.get(Bb),10):void 0};import{assertNever as ok,combine as uk,debounce as lk,ErrorCategory as gs,filter as ck,filterChanged as dk,isNonNullable as Vb,isNullable as vs,map as _b,merge as pk,observableFrom as hk,Subscription as fk,ValueSubject as Pu,VideoQuality as mk}from"@vkontakte/videoplayer-shared";var xu=Oe(qn(),1);import{videoSizeToQuality as rk,getExponentialDelay as ik}from"@vkontakte/videoplayer-shared";var ak=i=>{let e=null;if(i.QUALITY&&(e=nt(i.QUALITY)),!e&&i.RESOLUTION){let[t,r]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=rk({width:t,height:r})}return e??null},sk=(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,xu.default)(o[1].split(",").map(S=>S.split("="))),c=u.QUALITY??`stream-${u.BANDWIDTH}`,d=ak(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();d&&r.push({id:c,quality:d,url:b,bandwidth:p,size:m,fps:h})}if(l){let u=(0,xu.default)(l[1].split(",").map(h=>h.split("=")).map(([h,m])=>[h,m.replace(/^"|"$/g,"")])),c=u.URI?.replace(/playlist$/,"subtitles.vtt"),d=u.LANGUAGE,p=u.NAME;c&&d&&a.push({type:"internal",id:d,label:p,language:d,url:c,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:a}},nk=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),Eu=0,Ob=async(i,e=i,t)=>{let a=await(await Qe(i)).text();Eu+=1;try{let{qualityManifests:s,textTracks:n}=sk(a,e);return{qualityManifests:s,textTracks:n}}catch{if(Eu<=t.manifestRetryMaxCount)return await nk(ik(Eu-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Ob(i,e,t)}return{qualityManifests:[],textTracks:[]}},Ss=Ob;var qi=class{constructor(e){this.subscription=new fk;this.videoState=new L("stopped");this.textTracksManager=new ye;this.manifests$=new Pu([]);this.liveOffset=new Ge;this.manifestStartTime$=new Pu(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let u=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(a?.to!=="paused"&&u.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(u.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?I(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),I(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):a?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else a?.to==="paused"&&(I(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return ok(t)}};this.params=e,this.video=re(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:mk.INVARIANT,url:this.params.source.url},Ss(z(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:gs.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:gs.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Y(this.params.source.url)),this.maxSeekBackTime$=new Pu(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:gs.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=se(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(ae(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ve(this.video,t.playbackRate,a.playbackRateState$,r)),s(Ie(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(dk(),_b(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),l=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&Vb(u.to)){let d=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Y(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),l&&l.from==="changing_manifest"&&this.videoState.setState(l.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(a.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(uk({startTime:this.manifestStartTime$.pipe(ck(Vb)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:l})=>this.params.output.liveTime$.next(o+l*1e3),r)),this.subscription.add(this.manifests$.pipe(_b(o=>o.map(({id:l,quality:u,size:c,bandwidth:d,fps:p})=>({id:l,quality:u,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=pk(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,hk(["init"])).pipe(lk(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ie(this.video)}prepare(){let e=this.selectManifest();if(vs(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:l}=t?.to??r??{};for(let[u,c]of[[o,"mq"],[l,"lq"]]){let d=String(parseFloat(u||""));c&&u&&a.searchParams.set(c,d)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=z(a.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),Iu(n).then(o=>{if(!vs(o))this.maxSeekBackTime$.next(o);else{let l=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(vs(l)||!isFinite(l))try{Qe(n).then(u=>u.text()).then(u=>{let c=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(u)?.[1];if(c){let d=new URL(c,n).toString();Iu(d).then(p=>{vs(p)||this.maxSeekBackTime$.next(p)})}})}catch{}}})}playIfAllowed(){ne(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:gs.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 bk,debounce as Sk,ErrorCategory as Au,fromEvent as wu,isNonNullable as gk,isNullable as vk,map as Nb,merge as Fb,observableFrom as qb,Subscription as yk,ValueSubject as Tk,VideoQuality as Ik,clientChecker as Ek}from"@vkontakte/videoplayer-shared";var Ui=class{constructor(e){this.subscription=new yk;this.videoState=new L("stopped");this.textTracksManager=new ye;this.manifests$=new Tk([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let u=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch(a?.to!=="paused"&&u.state==="requested"&&this.seek(u.position),t){case"ready":r==="ready"?I(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):a?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):a?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return bk(t)}};this.params=e,this.video=re(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Ik.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Y(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Ss(z(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:Au.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:Au.WTF,message:"HlsProvider internal logic error",thrown:o})},a=se(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(Nb(o=>o.to)),this.params.output.playbackState$),this.subscription.add(_e(this.video,t.isLooped,r)),this.subscription.add(ae(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ve(this.video,t.playbackRate,a.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),l=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&gk(u.to)){let d=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let p=this.manifests$.getValue().find(h=>h.id===d);if(p){this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Y(p.url));let h=this.params.desiredState.playbackRate.getState(),m=this.params.output.element$.getValue()?.playbackRate;if(h!==m){let b=this.params.output.element$.getValue();b&&(this.params.desiredState.playbackRate.setState(h),b.playbackRate=h)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),l&&l.from==="changing_manifest"&&this.videoState.setState(l.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(Nb(o=>o.map(({id:l,quality:u,size:c,bandwidth:d,fps:p})=>({id:l,quality:u,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!Ek.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Fb(wu(o,"addtrack"),wu(o,"removetrack"),wu(o,"change"),qb(["init"])).subscribe(()=>{for(let l=0;l<o.length;l++)o[l].mode="hidden"},r))}let n=Fb(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,qb(["init"])).pipe(Sk(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ie(this.video)}prepare(){let e=this.selectManifest();if(vk(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(){ne(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:Au.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as xk,assertNonNullable as Ub,debounce as Pk,ErrorCategory as Hb,isHigher as Ak,isHigherOrEqual as wk,isInvariantQuality as jb,isLowerOrEqual as kk,isNonNullable as Rk,merge as Lk,observableFrom as $k,Subscription as Mk,map as Ck}from"@vkontakte/videoplayer-shared";var Hi=class{constructor(e){this.subscription=new Mk;this.videoState=new L("stopped");this.trackUrls={};this.textTracksManager=new ye;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 xk(e)}};this.params=e,this.video=re(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:Hb.WTF,message:"MpegProvider internal logic error",thrown:o})},a=se(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(Ck(o=>o.to)),this.params.output.playbackState$),this.subscription.add(_e(this.video,t.isLooped,r)),this.subscription.add(ae(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ve(this.video,t.playbackRate,a.playbackRateState$,r)),s(Ie(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&&Rk(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let l=this.params.desiredState.playbackRate.getState(),u=this.params.output.element$.getValue()?.playbackRate;if(l!==u){let c=this.params.output.element$.getValue();c&&(this.params.desiredState.playbackRate.setState(l),c.playbackRate=l)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=Lk(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,$k(["init"])).pipe(Pk(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),ie(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;Ub(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Ub(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ci(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Y(t))}playIfAllowed(){ne(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:Hb.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=>!jb(o.track.quality)&&kk(o.track.quality,e))?.track,s=this.params.desiredState.videoTrack.getState()?.id,n=this.trackUrls[s??"0"]?.track;if(a&&n&&wk(n.quality,a.quality)&&(t=a),!t){let o=Object.values(this.trackUrls).filter(u=>!jb(u.track.quality)&&Ak(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=ut(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 Yb,debounce as Vk,merge as Wb,observableFrom as _k,Subscription as Nk,map as Qb,ValueSubject as Fk,ErrorCategory as Ru,VideoQuality as qk}from"@vkontakte/videoplayer-shared";import{ErrorCategory as Dk}from"@vkontakte/videoplayer-shared";var Gb=["stun:videostun.mycdn.me:80"],Bk=1e3,Ok=3,ku=()=>null,ys=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=ku;this.externalStopCallback=ku;this.externalErrorCallback=ku;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:Gb}]};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:Dk.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),Bk)}normalizeOptions(e={}){let t={stunServerList:Gb,maxRetryNumber:Ok,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var ji=class{constructor(e){this.videoState=new L("stopped");this.maxSeekBackTime$=new Fk(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 Yb(e)}};this.subscription=new Nk,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=re(e.container,e.tuning),this.liveStreamClient=new ys(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),ie(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Ru.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};Wb(this.videoState.stateChangeStarted$.pipe(Qb(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Qb(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=se(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(Ie(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(ae(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 Yb(n.to)}},r)).add(Wb(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,_k(["init"])).pipe(Vk(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Y(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:qk.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:Ru.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ne(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:Ru.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Gi=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 Qi,assertNonNullable as dt,ErrorCategory as Is,filter as Qk,isNonNullable as eS,isNullable as zk,map as Kk,merge as Jk,once as Xk,Subject as fe,Subscription as tS,ValueSubject as M}from"@vkontakte/videoplayer-shared";import{Observable as Uk,map as zb,Subscription as Hk,Subject as jk}from"@vkontakte/videoplayer-shared";var Kb=i=>new Uk(e=>{let t=new Hk,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(zb(({from:u,to:c})=>`${u}-${c}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe(zb(({type:u})=>u!==void 0)),n=new jk,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 Jb,Subscription as Gk,combine as Yk,filter as Xb,once as Zb}from"@vkontakte/videoplayer-shared";var Yi=null,Ts=null;function Lu(){return Yi||(Yi=new(window.AudioContext||window.webkitAudioContext)),Ts||(Ts=new GainNode(Yi,{gain:1}),Ts.connect(Yi.destination)),{audioCtx:Yi,gainNode:Ts}}import{clientChecker as Wk}from"@vkontakte/videoplayer-shared";var Wi=class i{constructor(e,t,r,a,s){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=a;this.subscriptions=new Gk;this.lastAudioContextResumeId=0;!s||!this.isSupported()||a===1||this.subscriptions.add(this.provider$.pipe(Xb(n=>!!n.type),Zb()).subscribe(({type:n})=>this.subscribe(n)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){Wk.isSafari&&e!=="MPEG"||this.subscriptions.add(Yk({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(Xb(({playbackState:t,video:r,volume:{muted:a,volume:s}})=>t==="playing"&&!!r&&!a&&!!s),Zb()).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}=Lu(),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:Jb.VIDEO_PIPELINE,message:n?.message??"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:n})}}).catch(n=>{this.volumeMultiplierError$.next({id:i.errorId,category:Jb.VIDEO_PIPELINE,message:n?.message??"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){let{gainNode:e}=Lu();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};var Zk={chunkDuration:5e3,maxParallelRequests:5},zi=class{constructor(e){this.current$=new M({type:void 0});this.providerError$=new fe;this.noAvailableProvidersError$=new fe;this.volumeMultiplierError$=new fe;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 fe,warning$:new fe,willSeekEvent$:new fe,seekedEvent$:new fe,loopedEvent$:new fe,endedEvent$:new fe,firstBytesEvent$:new fe,loadedMetadataEvent$:new fe,firstFrameEvent$:new fe,canplay$:new fe,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 tS;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=ym([...Im(this.params.tuning),...Tm(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>eS(e.sources[o])),{forceFormat:r,formatsToAvoid:a}=this.params.tuning,s=[];r?s=[r]:a.length?s=[...t.filter(o=>!a.includes(o)),...t.filter(o=>a.includes(o))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.screenFormatsIterator=new Gi(s);let n=[...Wo(!0),...Wo(!1)];this.chromecastFormatsIterator=new Gi(n.filter(o=>eS(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new Wi(this.providerOutput,this.current$,this.volumeMultiplierError$,this.params.volumeMultiplier??1,this.params.tuning.useVolumeMultiplier)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager.destroy()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(zk(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:Is.WTF,message:"Failed to create provider",thrown:a})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),a=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:a?r.position:t,forcePrecise:a?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Qi(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 dt(o),new Vi({...n,source:o,sourceHls:l})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return dt(o),new _i({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return dt(o),dr||!this.params.tuning.useHlsJs?new Ui({...n,source:o}):new Fi({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return dt(o),new qi({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return dt(o),new Hi({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return dt(o),new pm({...n,source:o,config:{...Zk,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return dt(o),new ji({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 Qi(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 dt(o),new Qr({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 Qi(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Qi(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 Qi(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,rS.default)(Object.entries(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new tS,t=!1,r=0;return e.add(Jk(this.providerOutput.error$,Kb({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(Kk(a=>({id:`ProviderHangup:${a}`,category:Is.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(Qk(({to:s})=>s==="playing"),Xk()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{let s=this.current$.getValue().destination;if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let n=a.category===Is.NETWORK,o=a.category===Is.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),u=r<this.params.tuning.providerErrorLimit&&!o;l&&!o&&(n&&t||!u)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):u?(r++,this.reinitProvider()):this.switchToNextProvider(s??"SCREEN")}})),e}};import{fromEvent as Es,once as eR,combine as tR,Subscription as iS,ValueSubject as $u,map as rR,filter as iR,isNonNullable as xs,now as me,safeStorage as Mu}from"@vkontakte/videoplayer-shared";var aR=5e3,aS="one_video_throughput",sS="one_video_rtt",Ki=window.navigator.connection,nS=()=>{let i=Ki?.downlink;if(xs(i)&&i!==10)return i*1e3},oS=()=>{let i=Ki?.rtt;if(xs(i)&&i!==3e3)return i},uS=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},Cu=class i{constructor(e){this.subscription=new iS;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=i.load(aS)||(e.useBrowserEstimation?nS():void 0)||aR,r=i.load(sS)??(e.useBrowserEstimation?oS():void 0)??0;if(this.throughput$=new $u(t),this.rtt$=new $u(r),this.rttAdjustedThroughput$=new $u(uS(t,r,e.rttPenaltyRequestSize)),this.throughput=Bt.getSmoothedValue(t,-1,e),this.rtt=Bt.getSmoothedValue(r,1,e),e.useBrowserEstimation){let a=()=>{let n=nS();n&&this.throughput.next(n);let o=oS();xs(o)&&this.rtt.next(o)};Ki&&"onchange"in Ki&&this.subscription.add(Es(Ki,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{Mu.set(aS,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{Mu.set(sS,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(tR({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(rR(({throughput:a,rtt:s})=>uS(a,s,e.rttPenaltyRequestSize)),iR(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=me(),a=new iS;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(Es(e,"progress").pipe(eR()).subscribe(s=>{t=s.loaded,r=me()}));break;case 1:case 0:a.add(Es(e,"loadstart").subscribe(()=>{t=0,r=me()}));break}a.add(Es(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=me(),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=me(),n=0,o=me(),l=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},u=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(a,me()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=me();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=d.byteLength,s=me()}else n+=d.byteLength;o=me()}else a+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&me()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,me()-o,this.concurrentDownloads.size),n=0,o=me());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=Mu.get(e);if(xs(t))return parseInt(t,10)??void 0}},lS=Cu;import{fillWithDefault as sR,VideoQuality as cS}from"@vkontakte/videoplayer-shared";var dS={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:cS.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:cS.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,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},pS=i=>({...sR(i,dS),configName:[...i.configName??[],...dS.configName]});import{assertNonNullable as Ps,combine as As,ErrorCategory as ws,filter as Ji,filterChanged as xe,fromEvent as Bu,isNonNullable as pR,isNullable as hR,Logger as fR,map as C,mapTo as bS,merge as pt,now as ks,once as Je,Subject as N,Subscription as SS,tap as gS,ValueSubject as x,isHigher as mR,isInvariantQuality as vS}from"@vkontakte/videoplayer-shared";import{merge as nR,map as oR,filter as hS,isNonNullable as uR}from"@vkontakte/videoplayer-shared";var Du=({seekState:i,position$:e})=>nR(i.stateChangeEnded$.pipe(oR(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),hS(uR)),e.pipe(hS(()=>i.getState().state==="none")));import{assertNonNullable as lR}from"@vkontakte/videoplayer-shared";var fS=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return lR(e,`Wrong container or containerId {${i.container}}`),e};import{filter as cR,once as dR}from"@vkontakte/videoplayer-shared";var mS=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(cR(a=>a.length>0),dR()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t?.getValue().find(r))&&e.startTransitionTo(i)};var Rs=class{constructor(e={configName:[]}){this.subscription=new SS;this.logger=new fR;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new x(!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 x("stopped"),position$:new x(0),duration$:new x(1/0),muted$:new x(!1),volume$:new x(1),availableVideoStreams$:new x([]),currentVideoStream$:new x(void 0),availableQualities$:new x([]),availableQualitiesFps$:new x({}),currentQuality$:new x(void 0),isAutoQualityEnabled$:new x(!0),autoQualityLimitingAvailable$:new x(!1),autoQualityLimits$:new x({}),availableAudioStreams$:new x([]),currentAudioStream$:new x(void 0),availableAudioTracks$:new x([]),isAudioAvailable$:new x(!0),currentPlaybackRate$:new x(1),currentBuffer$:new x({start:0,end:0}),isBuffering$:new x(!0),isStalled$:new x(!1),isEnded$:new x(!1),isLooped$:new x(!1),isLive$:new x(void 0),canChangePlaybackSpeed$:new x(void 0),atLiveEdge$:new x(void 0),atLiveDurationEdge$:new x(void 0),liveTime$:new x(void 0),liveBufferTime$:new x(void 0),currentFormat$:new x(void 0),availableTextTracks$:new x([]),currentTextTrack$:new x(void 0),throughputEstimation$:new x(void 0),rttEstimation$:new x(void 0),videoBitrate$:new x(void 0),hostname$:new x(void 0),httpConnectionType$:new x(void 0),httpConnectionReused$:new x(void 0),surface$:new x("none"),chromecastState$:new x("NOT_AVAILABLE"),chromecastDeviceName$:new x(void 0),intrinsicVideoSize$:new x(void 0),availableSources$:new x(void 0),is3DVideo$:new x(!1),currentVideoSegmentLength$:new x(0),currentAudioSegmentLength$:new x(0)};this.events={inited$:new N,ready$:new N,started$:new N,playing$:new N,paused$:new N,stopped$:new N,willStart$:new N,willResume$:new N,willPause$:new N,willStop$:new N,willDestruct$:new N,watchCoverageRecord$:new N,watchCoverageLive$:new N,managedError$:new N,fatalError$:new N,ended$:new N,looped$:new N,seeked$:new N,willSeek$:new N,firstBytes$:new N,loadedMetadata$:new N,firstFrame$:new N,canplay$:new N,log$:new N};this.experimental={element$:new x(void 0),tuningConfigName$:new x([]),enableDebugTelemetry$:new x(!1),dumpTelemetry:Xf};if(this.initLogs(),this.tuning=pS(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new sa({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new lS(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,r,a)=>{let s=Reflect.get(t,r,a);return typeof s!="function"?s:(...n)=>{try{return s.apply(t,n)}catch(o){let l=n.map(d=>JSON.stringify(d,(p,h)=>{let m=typeof h;return["number","string","boolean"].includes(m)?h:h===null?null:`<${m}>`})),u=`Player.${String(r)}`,c=`Exception calling ${u} (${l.join(", ")})`;throw this.events.fatalError$.next({id:u,category:ws.WTF,message:c,thrown:o}),o}}}})}initVideo(e){return this.config=e,this.domContainer=fS(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new zi({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){let e=this.desiredState.playbackState;return e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!ii()?Bu(document,"visibilitychange").pipe(Je()).subscribe(e):e(),this}pause(){let e=this.desiredState.playbackState;return e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),a=this.info.isLive$.getValue();return e>=r&&!a&&(e=r-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:"requested",position:e*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){Ps(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(Ji(r=>r.length>0),Je()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){Ps(this.providerContainer);let t=this.providerContainer?.providerOutput.element$.getValue();return t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return mS(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(r){let a=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:a.x+s.x,y:a.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(hR(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(Ji(({from:e})=>e==="stopped"),Je()).subscribe(()=>{this.initedAt=ks(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:ws.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(C(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(C(n=>n.destination),xe()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(C(n=>n.map(({quality:o})=>o).sort((o,l)=>vS(o)?1:vS(l)?-1:mR(l,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let l of n)l.fps&&(o[l.quality]=l.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(xe()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(xe()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(xe()).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(As({hasLiveOffsetByPaused:pt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(C(n=>n.to),xe(),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(As({atLiveEdge:As({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Du({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(C(({isLive:n,position:o,isLowLatency:l})=>{let u=this.getActiveLiveDelay(l);return n&&Math.abs(o)<u/1e3}),xe(),gS(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(C(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(As({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(C(({isLive:n,position:o,duration:l})=>n&&(Math.abs(l)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),xe(),gS(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(C(n=>n.muted),xe()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(C(n=>n.volume),xe()).subscribe(this.info.volume$)).add(Du({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(pt(e.providerOutput.endedEvent$.pipe(bS(!0)),e.providerOutput.seekedEvent$.pipe(bS(!1))).pipe(xe()).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:ws.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(Je(),C(n=>n??ks()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(Je(),C(()=>ks()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Je(),C(()=>ks()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new x(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new x(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(Ji(({to:n})=>n==="playing"),Je()).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}),xe());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(),l=e.providerOutput.element$.getValue(),u=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":l?u?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(C(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new SS;this.subscription.add(t),this.subscription.add(e.current$.pipe(xe((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(Ji(r=>r.length>0),Je()).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=ut(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;Ps(this.providerContainer),Ps(e),Jf(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Kf(t)),this.providerContainer.current$.subscribe(({type:t})=>Xr("provider",t)),e.duration$.subscribe(t=>Xr("duration",t)),e.availableVideoTracks$.pipe(Ji(t=>!!t.length),Je()).subscribe(t=>Xr("tracks",t)),this.events.fatalError$.subscribe(new J("fatalError")),this.events.managedError$.subscribe(new J("managedError")),e.position$.subscribe(new J("position")),e.currentVideoTrack$.pipe(C(t=>t?.quality)).subscribe(new J("quality")),this.info.currentBuffer$.subscribe(new J("buffer")),e.isBuffering$.subscribe(new J("isBuffering"))].forEach(t=>this.subscription.add(t)),Xr("codecs",vm())}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:ws.DOM,message:String(a)})})};this.subscription.add(pt(Bu(document,"visibilitychange"),Bu(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let a=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!e?.released;a&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(a=>a.quality===t);r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as YH,Observable as WH,Subject as QH,ValueSubject as zH,VideoQuality as KH}from"@vkontakte/videoplayer-shared";var JH=`@vkontakte/videoplayer-core@${_u}`;export{ia as ChromecastState,Vs as HttpConnectionType,WH as Observable,ee as PlaybackState,Rs as Player,JH as SDK_VERSION,QH as Subject,YH as Subscription,_s as Surface,_u as VERSION,zH as ValueSubject,tt as VideoFormat,KH as VideoQuality};
112
+ `;var ys=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let a=this.canvas.getContext("webgl");if(!a)throw new Error("Could not initialize WebGL context");this.gl=a,this.container.appendChild(this.canvas),this.camera=new Ss(this.params.fov,this.params.orientation),this.cameraRotationManager=new vs(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),a=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(a,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Nb,this.gl.VERTEX_SHADER),r=this.createShader(Fb,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,a=this.frameHeight/(this.frameWidth/this.viewportWidth);return a>this.viewportHeight?t=this.viewportHeight/a:r=a/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,a=this.camera.fov.y/180/2,s=e-r,n=t-a,o=e+r,c=t-a,u=e+r,d=t+a,l=e-r,p=t+a;return[s,n,o,c,u,d,l,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var qt=class{constructor(e){this.subscription=new Zk;this.videoState=new L("stopped");this.elementSize$=new ew(void 0);this.textTracksManager=new Ee;this.droppedFramesManager=new es;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new ai;this.audioTrackSwitchHistory=new ai;this.textTracks=[];this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state==="requested"&&r?.to!=="paused"&&e!=="stopped"&&t!=="stopped"){let n=this.liveOffset?.getTotalPausedTime()??0;this.seek(a.position-n,a.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="ready"&&I(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset?.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):r?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;default:return Wk(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new ys(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=se(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Y(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new gs({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=ue(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:Pu.WTF,message:`${a} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,c)=>this.subscription.add(o.subscribe(c,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:a,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(qb(u=>!!u.length),Hb()).subscribe(u=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:u})})),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(qb(Kk),Hb()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(Ub(u=>u.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(Fe(this.video,t.isLooped,a)),this.subscription.add(oe(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Ie(this.video,t.playbackRate,r.playbackRateState$,a)),s(Xk(this.video),this.elementSize$),s(Pe(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},a)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{if(u==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(Yk(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of d.audio){p.push(fu(h));let m=[];for(let b of h.representations){let g=Pb(b);m.push(g),this.audioTracksMap.set(g,{stream:h,representation:b})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(p)}let l=[];for(let p of d.video){l.push(mu(p));let h=[];for(let m of p.representations){let b=xb(m);b&&(h.push(b),this.videoTracksMap.set(b,{stream:p,representation:m}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(l);for(let p of d.text)for(let h of p.representations){let m=Ab(p,h);this.textTracksMap.set(m,{stream:p,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size>0&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else u==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a));let n=u=>e.error$.next({id:"RepresentationSwitch",category:Pu.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(Ts(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,zk(this.video,"progress")).subscribe(()=>{let u=this.player.state$.getState(),d=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(u)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let l=this.selectVideoAudioRepresentations();if(!l)return;let[p,h]=l,m=this.params.desiredState.autoVideoTrackLimits.getTransition();if(m&&this.params.output.autoVideoTrackLimits$.next(m.to),u==="manifest_ready")this.player.initRepresentations(p.id,h?.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(n),h){let b=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",h.id,b).catch(n)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:u})=>{this.scene3D&&u&&this.scene3D.pointCameraTo(u.x,u.y)})),this.subscription.add(this.elementSize$.subscribe(u=>{this.scene3D&&u&&this.scene3D.setViewportSize(u.width,u.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Au()).subscribe(u=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===u);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[l,{stream:p}]=d,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(l),e.currentVideoStream$.next(mu(p))},a)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Au()).subscribe(u=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===u);if(!d){e.currentAudioStream$.next(void 0);return}let[l,{stream:p}]=d,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(fu(p))},a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{if(u?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},a)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,a)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,a)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(Ub(({to:u})=>u==="ready"),Au());this.subscription.add(Ts(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let u=t.autoVideoTrackSwitching.getState(),l=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(l)})),this.subscription.add(Ts(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let c=Ts(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Jk(["init"])).pipe(Qk(0));this.subscription.add(c.subscribe(this.syncPlayback,a))}selectVideoAudioRepresentations(){let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),a=e.videoTrack.getState()?.id,n=[...this.videoTracksMap.keys()].find(({id:E})=>E===a),o=t.currentVideoTrack$.getValue(),c=e.videoStream.getState()??(n&&this.videoTracksMap.get(n)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let u=[...this.videoStreamsMap.keys()].find(({id:E})=>E===c.id),d=u&&this.videoStreamsMap.get(u);if(!d)return;let l=ze(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(l/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),b=[...this.audioStreamsMap.keys()].find(({id:E})=>E===m?.id)??this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r)if(this.params.tuning.useSeparateAudioVideoABR){let E=Ka(n,d,this.audioStreamsMap.get(b)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,E?.bitrate??-1/0)}else{let E=cs(n,d,this.audioStreamsMap.get(b)??[]);g=Math.max(g,E?.bitrate??-1/0)}if(o)if(this.params.tuning.useSeparateAudioVideoABR){let E=Ka(o,d,this.audioStreamsMap.get(b)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,E?.bitrate??-1/0)}else{let E=cs(o,d,this.audioStreamsMap.get(b)??[]);g=Math.max(g,E?.bitrate??-1/0)}}let v=lt(d,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:g,forwardBufferHealth:h,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),A=r?v??n:n??v,y;this.params.tuning.useSeparateAudioVideoABR?y=b&&fm(A,d,this.audioStreamsMap.get(b)??[],{throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}):y=b&&cs(A,d,this.audioStreamsMap.get(b)??[]);let S=this.videoTracksMap.get(A)?.representation,T=y&&this.audioTracksMap.get(y)?.representation;if(S&&T)return[S,T];if(S&&!T&&this.audioTracksMap.size===0)return[S,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){le(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Pu.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),ne(this.video),this.tracer.end()}};var Gi=class extends qt{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as jb,interval as tw,map as rw}from"@vkontakte/videoplayer-shared";var Wi=class extends qt{constructor(e){super(e),this.liveOffset=new Ye}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(jb({interval:tw(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:a})=>{if(this.videoState.getState()==="playing"){let s=e.position$.getValue()+(a-1);s<=0&&e.position$.next(s),this.liveOffset?.resetTo(-s*1e3)}})).add(jb({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(rw(({liveBufferTime:a,liveAvailabilityStartTime:s})=>a&&s?a+s:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),a=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(n,a)})}};var Wb=_e(Ya(),1);import{assertNever as Yi,assertNonNullable as Gb,debounce as iw,ErrorCategory as Is,filter as aw,isNonNullable as sw,isNullable as nw,map as Es,merge as ow,Observable as uw,observableFrom as cw,Subscription as lw,videoSizeToQuality as dw}from"@vkontakte/videoplayer-shared";var Be={};var Pr=(i,e)=>new uw(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),Qi=class{constructor(e){this.subscription=new lw;this.videoState=new L("initializing");this.textTracksManager=new Ee;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(e!=="initializing")switch(r?.to!=="paused"&&a.state==="requested"&&this.seek(a.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:Yi(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Yi(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Yi(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Yi(e)}break;default:Yi(t)}};this.video=se(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Y(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),ne(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Is.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Wb.default)(import("hls.js").then(a=>{e||(Be.Hls=a.default,Be.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){Gb(Be.Hls,"hls.js not loaded"),this.hls=new Be.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Gb(Be.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=u=>{t.error$.next({id:"HlsJsProvider",category:Is.WTF,message:"HlsJsProvider internal logic error",thrown:u})},a=ue(this.video),s=(u,d)=>this.subscription.add(u.subscribe(d,r));s(a.timeUpdate$,t.position$),s(a.durationChange$,t.duration$),s(a.ended$,t.endedEvent$),s(a.looped$,t.loopedEvent$),s(a.error$,t.error$),s(a.isBuffering$,t.isBuffering$),s(a.currentBuffer$,t.currentBuffer$),s(a.loadStart$,t.firstBytesEvent$),s(a.loadedMetadata$,t.loadedMetadataEvent$),s(a.playing$,t.firstFrameEvent$),s(a.canplay$,t.canplay$),s(a.seeked$,t.seekedEvent$),s(a.inPiP$,t.inPiP$),s(a.inFullscreen$,t.inFullscreen$),this.subscription.add(Fe(this.video,e.isLooped,r)),this.subscription.add(oe(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ie(this.video,e.playbackRate,a.playbackRateState$,r)),s(Pe(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(Es(u=>u.to)),this.params.output.playbackState$),this.subscription.add(Pr(this.hls,Be.Events.ERROR).subscribe(u=>{u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:Is.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${u.err?.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(e.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(e.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(Pr(this.hls,Be.Events.MANIFEST_PARSED).pipe(Es(({levels:u})=>u.reduce((d,l)=>{let p=l.name||l.height.toString(10),{width:h,height:m}=l,b=ct(l.attrs.QUALITY??"")??dw({width:h,height:m});if(!b)return d;let g=l.attrs["FRAME-RATE"]?parseFloat(l.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:b,bitrate:l.bitrate/1e3,size:{width:h,height:m},fps:g};return this.trackLevels.set(p,{track:v,level:l}),d.push(v),d},[]))),t.availableVideoTracks$),s(Pr(this.hls,Be.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){let d=[];for(let l of u.subtitleTracks){let p=l.name,h=l.attrs.URI||"",m=l.lang;d.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(d)}}),s(Pr(this.hls,Be.Events.LEVEL_LOADING).pipe(Es(({url:u})=>Y(u))),t.hostname$),s(Pr(this.hls,Be.Events.FRAG_CHANGED),u=>{let{video:d,audio:l}=u.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((l?.endPTS??0)-(l?.startPTS??0))*1e3)}),this.subscription.add(nt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:r}));let n=u=>Array.from(this.trackLevels.values()).find(({level:d})=>d===u)?.track,o=Pr(this.hls,Be.Events.LEVEL_SWITCHED).pipe(Es(({level:u})=>n(this.hls.levels[u])));o.pipe(aw(sw)).subscribe(t.currentVideoTrack$,r),this.subscription.add(nt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),u=>{if(nw(u))return;let d=this.trackLevels.get(u.id)?.level;if(!d)return;let l=this.hls.levels.indexOf(d),p=this.hls.currentLevel,h=this.hls.levels[p];!h||d.bitrate>h.bitrate?this.hls.nextLevel=l:(this.hls.loadLevel=l,this.hls.loadLevel=l)},{changed$:o,onError:r})),s(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let c=ow(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,cw(["init"])).pipe(iw(0));this.subscription.add(c.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await le(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Is.DOM,thrown:t}))||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0)}};var Yb="X-Playback-Duration",ku=async i=>{let e=await Ke(i),t=await e.text(),r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return r?parseInt(r,10):e.headers.has(Yb)?parseInt(e.headers.get(Yb),10):void 0};import{assertNever as gw,combine as Sw,debounce as vw,ErrorCategory as Ps,filter as yw,filterChanged as Tw,isNonNullable as zb,isNullable as As,map as Kb,merge as Iw,observableFrom as Ew,Subscription as xw,ValueSubject as $u,VideoQuality as Pw}from"@vkontakte/videoplayer-shared";var Ru=_e(Yn(),1);import{videoSizeToQuality as pw,getExponentialDelay as hw}from"@vkontakte/videoplayer-shared";var fw=i=>{let e=null;if(i.QUALITY&&(e=ct(i.QUALITY)),!e&&i.RESOLUTION){let[t,r]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=pw({width:t,height:r})}return e??null},mw=(i,e)=>{let t=i.split(`
113
+ `),r=[],a=[];for(let s=0;s<t.length;s++){let n=t[s],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),c=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!c)){if(o){let u=(0,Ru.default)(o[1].split(",").map(g=>g.split("="))),d=u.QUALITY??`stream-${u.BANDWIDTH}`,l=fw(u),p;u.BANDWIDTH&&(p=parseInt(u.BANDWIDTH,10)/1e3||void 0),!p&&u["AVERAGE-BANDWIDTH"]&&(p=parseInt(u["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=u["FRAME-RATE"]?parseFloat(u["FRAME-RATE"]):void 0,m;if(u.RESOLUTION){let[g,v]=u.RESOLUTION.split("x").map(A=>parseInt(A,10));g&&v&&(m={width:g,height:v})}let b=new URL(t[++s],e).toString();l&&r.push({id:d,quality:l,url:b,bandwidth:p,size:m,fps:h})}if(c){let u=(0,Ru.default)(c[1].split(",").map(h=>h.split("=")).map(([h,m])=>[h,m.replace(/^"|"$/g,"")])),d=u.URI?.replace(/playlist$/,"subtitles.vtt"),l=u.LANGUAGE,p=u.NAME;d&&l&&a.push({type:"internal",id:l,label:p,language:l,url:d,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:a}},bw=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),wu=0,Qb=async(i,e=i,t)=>{let a=await(await Ke(i)).text();wu+=1;try{let{qualityManifests:s,textTracks:n}=mw(a,e);return{qualityManifests:s,textTracks:n}}catch{if(wu<=t.manifestRetryMaxCount)return await bw(hw(wu-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Qb(i,e,t)}return{qualityManifests:[],textTracks:[]}},xs=Qb;var zi=class{constructor(e){this.subscription=new xw;this.videoState=new L("stopped");this.textTracksManager=new Ee;this.manifests$=new $u([]);this.liveOffset=new Ye;this.manifestStartTime$=new $u(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let u=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(a?.to!=="paused"&&u.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(u.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?I(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),I(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):a?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else a?.to==="paused"&&(I(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return gw(t)}};this.params=e,this.video=se(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Pw.INVARIANT,url:this.params.source.url},xs(K(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t})=>{t.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Ps.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Ps.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Y(this.params.source.url)),this.maxSeekBackTime$=new $u(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(c=>c.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:Ps.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=ue(this.video),s=(o,c)=>this.subscription.add(o.subscribe(c,r));s(a.ended$,e.endedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(oe(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ie(this.video,t.playbackRate,a.playbackRateState$,r)),s(Pe(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(Tw(),Kb(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),c=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&zb(u.to)){let l=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let p=this.manifests$.getValue().find(h=>h.id===l);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Y(p.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),c&&c.from==="changing_manifest"&&this.videoState.setState(c.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(a.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(Sw({startTime:this.manifestStartTime$.pipe(yw(zb)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:c})=>this.params.output.liveTime$.next(o+c*1e3),r)),this.subscription.add(this.manifests$.pipe(Kb(o=>o.map(({id:c,quality:u,size:d,bandwidth:l,fps:p})=>({id:c,quality:u,size:d,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,r));let n=Iw(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ew(["init"])).pipe(vw(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ne(this.video)}prepare(){let e=this.selectManifest();if(As(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:c}=t?.to??r??{};for(let[u,d]of[[o,"mq"],[c,"lq"]]){let l=String(parseFloat(u||""));d&&u&&a.searchParams.set(d,l)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=K(a.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),ku(n).then(o=>{if(!As(o))this.maxSeekBackTime$.next(o);else{let c=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(As(c)||!isFinite(c))try{Ke(n).then(u=>u.text()).then(u=>{let d=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(u)?.[1];if(d){let l=new URL(d,n).toString();ku(l).then(p=>{As(p)||this.maxSeekBackTime$.next(p)})}})}catch{}}})}playIfAllowed(){le(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ps.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}};import{assertNever as Aw,debounce as kw,ErrorCategory as Lu,fromEvent as Mu,isNonNullable as ww,isNullable as Rw,map as Jb,merge as Xb,observableFrom as Zb,Subscription as $w,ValueSubject as Lw,VideoQuality as Mw,clientChecker as Cw}from"@vkontakte/videoplayer-shared";var Ki=class{constructor(e){this.subscription=new $w;this.videoState=new L("stopped");this.textTracksManager=new Ee;this.manifests$=new Lw([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let u=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:l}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:l*1e3,forcePrecise:!0});return}switch(a?.to!=="paused"&&u.state==="requested"&&this.seek(u.position),t){case"ready":r==="ready"?I(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):a?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):a?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return Aw(t)}};this.params=e,this.video=se(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Mw.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Y(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),xs(K(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Lu.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(c=>c.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:Lu.WTF,message:"HlsProvider internal logic error",thrown:o})},a=ue(this.video),s=(o,c)=>this.subscription.add(o.subscribe(c));if(s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(Jb(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Fe(this.video,t.isLooped,r)),this.subscription.add(oe(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ie(this.video,t.playbackRate,a.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),c=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&ww(u.to)){let l=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let p=this.manifests$.getValue().find(h=>h.id===l);if(p){this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Y(p.url));let h=this.params.desiredState.playbackRate.getState(),m=this.params.output.element$.getValue()?.playbackRate;if(h!==m){let b=this.params.output.element$.getValue();b&&(this.params.desiredState.playbackRate.setState(h),b.playbackRate=h)}}}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),c&&c.from==="changing_manifest"&&this.videoState.setState(c.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(Jb(o=>o.map(({id:c,quality:u,size:d,bandwidth:l,fps:p})=>({id:c,quality:u,size:d,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,r)),!Cw.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Xb(Mu(o,"addtrack"),Mu(o,"removetrack"),Mu(o,"change"),Zb(["init"])).subscribe(()=>{for(let c=0;c<o.length;c++)o[c].mode="hidden"},r))}let n=Xb(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Zb(["init"])).pipe(kw(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ne(this.video)}prepare(){let e=this.selectManifest();if(Rw(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:s,min:n}=t?.to??r??{};for(let[o,c]of[[s,"mq"],[n,"lq"]]){let u=String(parseFloat(o||""));c&&o&&a.searchParams.set(c,u)}}this.video.setAttribute("src",a.toString()),this.video.load()}playIfAllowed(){le(this.video).then(e=>{e||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Lu.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as Dw,assertNonNullable as eg,debounce as Bw,ErrorCategory as tg,isHigher as Vw,isHigherOrEqual as Ow,isInvariantQuality as rg,isLowerOrEqual as _w,isNonNullable as Nw,merge as Fw,observableFrom as qw,Subscription as Uw,map as Hw}from"@vkontakte/videoplayer-shared";var Ji=class{constructor(e){this.subscription=new Uw;this.videoState=new L("stopped");this.trackUrls={};this.textTracksManager=new Ee;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:c}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0}),n.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[n.to.id]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(r?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?I(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;default:return Dw(e)}};this.params=e,this.video=se(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,r],a)=>{let s=a.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:tg.WTF,message:"MpegProvider internal logic error",thrown:o})},a=ue(this.video),s=(o,c)=>this.subscription.add(o.subscribe(c,r));s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(Hw(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Fe(this.video,t.isLooped,r)),this.subscription.add(oe(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ie(this.video,t.playbackRate,a.playbackRateState$,r)),s(Pe(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&Nw(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),u=this.params.output.element$.getValue()?.playbackRate;if(c!==u){let d=this.params.output.element$.getValue();d&&(this.params.desiredState.playbackRate.setState(c),d.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=Fw(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,qw(["init"])).pipe(Bw(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),ne(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;eg(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];eg(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ni(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Y(t))}playIfAllowed(){le(this.video).then(e=>{e||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:tg.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){let t,r=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){let a=Object.values(this.trackUrls).find(o=>!rg(o.track.quality)&&_w(o.track.quality,e))?.track,s=this.params.desiredState.videoTrack.getState()?.id,n=this.trackUrls[s??"0"]?.track;if(a&&n&&Ow(n.quality,a.quality)&&(t=a),!t){let o=Object.values(this.trackUrls).filter(u=>!rg(u.track.quality)&&Vw(u.track.quality,e)),c=o.length;c&&(t=o[c-1].track)}t&&(r=t.quality)}else if(!e){let a=Object.values(this.trackUrls).map(s=>s.track);t=lt(a,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};import{assertNever as ag,debounce as Yw,merge as sg,observableFrom as Qw,Subscription as zw,map as ng,ValueSubject as Kw,ErrorCategory as Du,VideoQuality as Jw}from"@vkontakte/videoplayer-shared";import{ErrorCategory as jw}from"@vkontakte/videoplayer-shared";var ig=["stun:videostun.mycdn.me:80"],Gw=1e3,Ww=3,Cu=()=>null,ks=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=Cu;this.externalStopCallback=Cu;this.externalErrorCallback=Cu;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:ig}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:jw.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),Gw)}normalizeOptions(e={}){let t={stunServerList:ig,maxRetryNumber:Ww,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Xi=class{constructor(e){this.videoState=new L("stopped");this.maxSeekBackTime$=new Kw(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;default:return ag(e)}};this.subscription=new zw,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=se(e.container,e.tuning),this.liveStreamClient=new ks(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),ne(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Du.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};sg(this.videoState.stateChangeStarted$.pipe(ng(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ng(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=ue(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(a.timeUpdate$,e.liveTime$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(Pe(this.video),this.params.output.elementVisible$),this.subscription.add(a.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(a.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(oe(this.video,t.volume,a.volumeState$,r)).add(a.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return ag(n.to)}},r)).add(sg(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Qw(["init"])).pipe(Yw(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Y(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:Jw.INVARIANT}),this.video.srcObject=e,I(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Du.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){le(this.video).then(e=>{e||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Du.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Zi=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as ra,assertNonNullable as ht,ErrorCategory as Rs,filter as aR,isNonNullable as pg,isNullable as sR,map as nR,merge as oR,once as uR,Subject as ge,Subscription as hg,ValueSubject as M,flattenObject as fg}from"@vkontakte/videoplayer-shared";import{Observable as Xw,map as og,Subscription as Zw,Subject as eR}from"@vkontakte/videoplayer-shared";var ug=i=>new Xw(e=>{let t=new Zw,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(og(({from:u,to:d})=>`${u}-${d}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe(og(({type:u})=>u!==void 0)),n=new eR,o=0,c="unknown";return t.add(r.subscribe(u=>{o&&window.clearTimeout(o),c=u,o=window.setTimeout(()=>n.next(u),i.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(o),c="unknown",o=0})),t.add(s.subscribe(u=>{o&&(window.clearTimeout(o),o=0,u&&(o=window.setTimeout(()=>n.next(c),i.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as cg,Subscription as tR,combine as rR,filter as lg,once as dg}from"@vkontakte/videoplayer-shared";var ea=null,ws=null;function Bu(){return ea||(ea=new(window.AudioContext||window.webkitAudioContext)),ws||(ws=new GainNode(ea,{gain:1}),ws.connect(ea.destination)),{audioCtx:ea,gainNode:ws}}import{clientChecker as iR}from"@vkontakte/videoplayer-shared";var ta=class i{constructor(e,t,r,a,s){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=a;this.subscriptions=new tR;this.lastAudioContextResumeId=0;!s||!this.isSupported()||a===1||this.subscriptions.add(this.provider$.pipe(lg(n=>!!n.type),dg()).subscribe(({type:n})=>this.subscribe(n)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){iR.isSafari&&e!=="MPEG"||this.subscriptions.add(rR({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(lg(({playbackState:t,video:r,volume:{muted:a,volume:s}})=>t==="playing"&&!!r&&!a&&!!s),dg()).subscribe(({video:t})=>this.initAudioContextOnce(t)))}isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){let{volumeMultiplier:t}=this,{audioCtx:r,gainNode:a}=Bu(),s=(Math.random()+1)*999999;this.lastAudioContextResumeId=s,r.resume().then(()=>{if(s!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${i.errorId} destroyed`);a.gain.value=t;try{new MediaElementAudioSourceNode(r,{mediaElement:e}).connect(a)}catch(n){this.volumeMultiplierError$.next({id:i.errorId,category:cg.VIDEO_PIPELINE,message:n?.message??"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:n})}}).catch(n=>{this.volumeMultiplierError$.next({id:i.errorId,category:cg.VIDEO_PIPELINE,message:n?.message??"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){let{gainNode:e}=Bu();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};var cR={chunkDuration:5e3,maxParallelRequests:5},ia=class{constructor(e){this.current$=new M({type:void 0});this.providerError$=new ge;this.noAvailableProvidersError$=new ge;this.volumeMultiplierError$=new ge;this.providerOutput={position$:new M(0),duration$:new M(1/0),volume$:new M({muted:!1,volume:1}),availableVideoStreams$:new M([]),currentVideoStream$:new M(void 0),availableVideoTracks$:new M([]),currentVideoTrack$:new M(void 0),availableAudioStreams$:new M([]),currentAudioStream$:new M(void 0),availableAudioTracks$:new M([]),currentVideoSegmentLength$:new M(0),currentAudioSegmentLength$:new M(0),isAudioAvailable$:new M(!0),autoVideoTrackLimitingAvailable$:new M(!1),autoVideoTrackLimits$:new M(void 0),currentBuffer$:new M(void 0),isBuffering$:new M(!0),error$:new ge,warning$:new ge,willSeekEvent$:new ge,seekedEvent$:new ge,loopedEvent$:new ge,endedEvent$:new ge,firstBytesEvent$:new ge,loadedMetadataEvent$:new ge,firstFrameEvent$:new ge,canplay$:new ge,isLive$:new M(void 0),isLowLatency$:new M(!1),canChangePlaybackSpeed$:new M(!0),liveTime$:new M(void 0),liveBufferTime$:new M(void 0),availableTextTracks$:new M([]),currentTextTrack$:new M(void 0),hostname$:new M(void 0),httpConnectionType$:new M(void 0),httpConnectionReused$:new M(void 0),inPiP$:new M(!1),inFullscreen$:new M(!1),element$:new M(void 0),elementVisible$:new M(!0),availableSources$:new M(void 0),is3DVideo$:new M(!1),playbackState$:new M("")};this.subscription=new hg;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=Cm([...Bm(this.params.tuning),...Dm(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>pg(e.sources[o])),{forceFormat:r,formatsToAvoid:a}=this.params.tuning,s=[];r?s=[r]:a.length?s=[...t.filter(o=>!a.includes(o)),...t.filter(o=>a.includes(o))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",fg(s)),this.screenFormatsIterator=new Zi(s);let n=[...Zo(!0),...Zo(!1)];this.chromecastFormatsIterator=new Zi(n.filter(o=>pg(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new ta(this.providerOutput,this.current$,this.volumeMultiplierError$,this.params.volumeMultiplier??1,this.params.tuning.useVolumeMultiplier)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager.destroy(),this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(sR(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:Rs.WTF,message:"Failed to create provider",thrown:a})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),a=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:a?r.position:t,forcePrecise:a?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return ra(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:a}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),c=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return ht(o),new Gi({...n,source:o,sourceHls:c})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return ht(o),new Wi({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return ht(o),mr||!this.params.tuning.useHlsJs?new Ki({...n,source:o}):new Qi({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return ht(o),new zi({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return ht(o),new Ji({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return ht(o),new Pm({...n,source:o,config:{...cR,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return ht(o),new Xi({container:r,source:o,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return ra(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:a,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return ht(o),new Zr({connection:o,meta:s,container:r,source:t,format:e,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return ra(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return ra(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return ra(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=a=>{let s=new URL(a);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:r(e.url)}}return(0,mg.default)(Object.entries(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new hg,t=!1,r=0;return e.add(oR(this.providerOutput.error$,ug({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(nR(a=>({id:`ProviderHangup:${a}`,category:Rs.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let a=this.params.desiredState.playbackState.transitionEnded$.pipe(aR(({to:s})=>s==="playing"),uR()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{let s=this.current$.getValue().destination,n={error:a,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=a.category===Rs.NETWORK,c=a.category===Rs.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=r<this.params.tuning.providerErrorLimit&&!c,l=u&&!c&&(o&&t||!d);n={...n,isNetworkError:o,isFatalError:c,haveFailoverHost:u,tryFailover:l,canReinitProvider:d},l?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(r++,this.reinitProvider()):this.switchToNextProvider(s??"SCREEN")}this.tracer.error("providerError",fg(n))})),e}};import{fromEvent as $s,once as lR,combine as dR,Subscription as bg,ValueSubject as Vu,map as pR,filter as hR,isNonNullable as Ls,now as Se,safeStorage as Ou}from"@vkontakte/videoplayer-shared";var fR=5e3,gg="one_video_throughput",Sg="one_video_rtt",aa=window.navigator.connection,vg=()=>{let i=aa?.downlink;if(Ls(i)&&i!==10)return i*1e3},yg=()=>{let i=aa?.rtt;if(Ls(i)&&i!==3e3)return i},Tg=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},_u=class i{constructor(e){this.subscription=new bg;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=i.load(gg)||(e.useBrowserEstimation?vg():void 0)||fR,r=i.load(Sg)??(e.useBrowserEstimation?yg():void 0)??0;if(this.throughput$=new Vu(t),this.rtt$=new Vu(r),this.rttAdjustedThroughput$=new Vu(Tg(t,r,e.rttPenaltyRequestSize)),this.throughput=Nt.getSmoothedValue(t,-1,e),this.rtt=Nt.getSmoothedValue(r,1,e),e.useBrowserEstimation){let a=()=>{let n=vg();n&&this.throughput.next(n);let o=yg();Ls(o)&&this.rtt.next(o)};aa&&"onchange"in aa&&this.subscription.add($s(aa,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{Ou.set(gg,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{Ou.set(Sg,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(dR({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(pR(({throughput:a,rtt:s})=>Tg(a,s,e.rttPenaltyRequestSize)),hR(a=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(a-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=Se(),a=new bg;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add($s(e,"progress").pipe(lR()).subscribe(s=>{t=s.loaded,r=Se()}));break;case 1:case 0:a.add($s(e,"loadstart").subscribe(()=>{t=0,r=Se()}));break}a.add($s(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Se(),c=n-t,u=o-r;this.addRawSpeed(c,u,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let a=0,s=Se(),n=0,o=Se(),c=d=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},u=async({done:d,value:l})=>{if(d)!t&&this.addRawSpeed(a,Se()-s,1),this.concurrentDownloads.delete(e);else if(l){if(t){let p=Se();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-s;m&&this.addRawSpeed(n,m,1,t),n=l.byteLength,s=Se()}else n+=l.byteLength;o=Se()}else a+=l.byteLength,n+=l.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Se()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Se()-o,this.concurrentDownloads.size),n=0,o=Se());await r?.read().then(u,c)}};this.concurrentDownloads.add(e),r?.read().then(u,c)}addRawSpeed(e,t,r=1,a=!1){if(i.sanityCheck(e,t,a)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let a=e*8/t;return!(!a||!isFinite(a)||a>1e6||a<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){let t=Ou.get(e);if(Ls(t))return parseInt(t,10)??void 0}},Ig=_u;import{fillWithDefault as mR,VideoQuality as Eg}from"@vkontakte/videoplayer-shared";var xg={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateAudioFactorAtEmptyBuffer:7,bitrateFactorAtFullBuffer:1.2,bitrateAudioFactorAtFullBuffer:5,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:Eg.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Eg.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,accumulationBufferStallSizeMs:0,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewPartialSegmentFeeding:!1,useSeparateAudioVideoABR:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1},Pg=i=>({...mR(i,xg),configName:[...i.configName??[],...xg.configName]});import{assertNonNullable as Ms,combine as ft,ErrorCategory as Cs,filter as ee,filterChanged as V,fromEvent as Fu,isNonNullable as IR,isNullable as ER,Logger as xR,map as C,mapTo as Rg,merge as mt,now as Ds,once as et,Subject as F,Subscription as $g,tap as Lg,ValueSubject as P,isHigher as PR,isInvariantQuality as Mg,flattenObject as bt,throttle as qu,getTraceSubscriptionMethod as Cg}from"@vkontakte/videoplayer-shared";import{merge as bR,map as gR,filter as Ag,isNonNullable as SR}from"@vkontakte/videoplayer-shared";var Nu=({seekState:i,position$:e})=>bR(i.stateChangeEnded$.pipe(gR(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),Ag(SR)),e.pipe(Ag(()=>i.getState().state==="none")));import{assertNonNullable as vR}from"@vkontakte/videoplayer-shared";var kg=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return vR(e,`Wrong container or containerId {${i.container}}`),e};import{filter as yR,once as TR}from"@vkontakte/videoplayer-shared";var wg=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(yR(a=>a.length>0),TR()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t?.getValue().find(r))&&e.startTransitionTo(i)};var Bs=class{constructor(e={configName:[]},t){this.subscription=new $g;this.logger=new xR;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new L("stopped"),seekState:new L({state:"none"}),volume:new L({volume:1,muted:!1}),videoTrack:new L(void 0),videoStream:new L(void 0),audioStream:new L(void 0),autoVideoTrackSwitching:new L(!0),autoVideoTrackLimits:new L({}),isLooped:new L(!1),playbackRate:new L(1),externalTextTracks:new L([]),internalTextTracks:new L([]),currentTextTrack:new L(void 0),textTrackCuesSettings:new L({}),cameraOrientation:new L({x:0,y:0})};this.info={playbackState$:new P("stopped"),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableVideoStreams$:new P([]),currentVideoStream$:new P(void 0),availableQualities$:new P([]),availableQualitiesFps$:new P({}),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),availableAudioStreams$:new P([]),currentAudioStream$:new P(void 0),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new F,ready$:new F,started$:new F,playing$:new F,paused$:new F,stopped$:new F,willStart$:new F,willResume$:new F,willPause$:new F,willStop$:new F,willDestruct$:new F,watchCoverageRecord$:new F,watchCoverageLive$:new F,managedError$:new F,fatalError$:new F,ended$:new F,looped$:new F,seeked$:new F,willSeek$:new F,firstBytes$:new F,loadedMetadata$:new F,firstFrame$:new F,canplay$:new F,log$:new F};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:am};if(this.initLogs(),this.tuning=Pg(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new pa({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Ig(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,a,s)=>{let n=Reflect.get(r,a,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(c){let u=o.map(p=>JSON.stringify(p,(h,m)=>{let b=typeof m;return["number","string","boolean"].includes(b)?m:m===null?null:`<${b}>`})),d=`Player.${String(a)}`,l=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:Cs.WTF,message:l,thrown:c}),c}}}})}initVideo(e){return this.config=e,this.tracer.log("initVideo",bt(e)),this.domContainer=kg(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new ia({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!ci()?(this.tracer.log("request play from hidden tab"),Fu(document,"visibilitychange").pipe(et()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),a=this.info.isLive$.getValue(),s=e;return e>=r&&!a&&(s=r-.1),this.tracer.log("seekTime",{duration:r,isLive:a,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){Ms(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(ee(r=>r.length>0),et()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",bt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){Ms(this.providerContainer);let t=this.providerContainer?.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",bt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return wg(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let a=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:a.x+s.x,y:a.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(ER(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return IR(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:a})=>r||a||0,0),height:e.reduce((r,{height:a})=>r||a||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(mt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(C(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(ee(({from:e})=>e==="stopped"),et()).subscribe(()=>{this.initedAt=Ds(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",bt(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Cs.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",bt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(C(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(C(n=>n.destination),V()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(C(n=>n.map(({quality:o})=>o).sort((o,c)=>Mg(o)?1:Mg(c)?-1:PR(c,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let c of n)c.fps&&(o[c.quality]=c.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(V()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(V((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(V((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(V()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(V()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(V()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n??{})})).add(e.providerOutput.currentBuffer$.pipe(C(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(ft({hasLiveOffsetByPaused:mt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(C(n=>n.to),V(),C(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(ft({atLiveEdge:ft({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Nu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(C(({isLive:n,position:o,isLowLatency:c})=>{let u=this.getActiveLiveDelay(c);return n&&Math.abs(o)<u/1e3}),V(),Lg(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(C(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(ft({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(C(({isLive:n,position:o,duration:c})=>n&&(Math.abs(c)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),V(),Lg(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(C(n=>n.muted),V()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(C(n=>n.volume),V()).subscribe(this.info.volume$)).add(Nu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(mt(e.providerOutput.endedEvent$.pipe(Rg(!0)),e.providerOutput.seekedEvent$.pipe(Rg(!1))).pipe(V()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(C(n=>({id:n?`No${n}`:"NoProviders",category:Cs.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(et(),C(n=>n??Ds()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(et(),C(()=>Ds()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(et(),C(()=>Ds()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new P(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new P(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(ee(({to:n})=>n==="playing"),et()).subscribe(()=>r.next(!1)));let a=0,s=mt(e.providerOutput.isBuffering$,t,r).pipe(C(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),V());this.subscription.add(s.subscribe(n=>{n?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})),this.subscription.add(mt(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(mt(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),c=e.providerOutput.element$.getValue(),u=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue(),l;d==="CONNECTED"?l="second_screen":c?u?n?l="pip":o?l="fullscreen":l="inline":l="invisible":l="none",this.info.surface$.getValue()!==l&&this.info.surface$.next(l)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(C(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new $g;this.subscription.add(t),this.subscription.add(e.current$.pipe(V((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ee(r=>r.length>0),et()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){let t,r=this.desiredState.videoTrack.getState()?.quality;r&&(t=e.find(({quality:a})=>a===r),t||this.setAutoQuality(!0)),t||(t=lt(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(mt(this.desiredState.videoTrack.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(C(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;Ms(this.providerContainer),Ms(e),im(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>rm(t)),this.providerContainer.current$.subscribe(({type:t})=>ii("provider",t)),e.duration$.subscribe(t=>ii("duration",t)),e.availableVideoTracks$.pipe(ee(t=>!!t.length),et()).subscribe(t=>ii("tracks",t)),this.events.fatalError$.subscribe(new X("fatalError")),this.events.managedError$.subscribe(new X("managedError")),e.position$.subscribe(new X("position")),e.currentVideoTrack$.pipe(C(t=>t?.quality)).subscribe(new X("quality")),this.info.currentBuffer$.subscribe(new X("buffer")),e.isBuffering$.subscribe(new X("isBuffering"))].forEach(t=>this.subscription.add(t)),ii("codecs",Mm())}initTracerSubscription(){let e=Cg(this.tracer.log.bind(this.tracer)),t=Cg(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(V()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(ft({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(ee(({currentQuality:r,videoBitrate:a})=>!!r&&!!a),V((r,a)=>r.currentQuality===a.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(ee(r=>r>0),V()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(ee(r=>r>0),V()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(ft({currentBuffer:this.info.currentBuffer$.pipe(ee(r=>r.end>0),V((r,a)=>r.end===a.end&&r.start===a.start)),position:this.info.position$.pipe(V())}).pipe(qu(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(V()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(V()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(V()).subscribe(e("canChangePlaybackSpeed"))).add(ft({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(ee(({liveTime:r,liveBufferTime:a})=>!!r&&!!a),qu(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(V(),ee(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(V(),ee(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(V()).subscribe(e("muted"))).add(this.info.volume$.pipe(V()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(V(),ee(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(ft({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(ee(({throughputEstimation:r,rtt:a})=>!!r&&!!a),qu(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(V(),ee(r=>r===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},r=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Cs.DOM,message:String(a)})})};this.subscription.add(mt(Fu(document,"visibilitychange"),Fu(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let a=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!e?.released;a&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(a=>a.quality===t);this.tracer.log("setVideoTrackIdByQuality",bt({quality:t,availableTracks:bt(e),track:bt(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as uj,Observable as cj,Subject as lj,ValueSubject as dj,VideoQuality as pj}from"@vkontakte/videoplayer-shared";var hj=`@vkontakte/videoplayer-core@${ju}`;export{la as ChromecastState,Hs as HttpConnectionType,cj as Observable,ie as PlaybackState,Bs as Player,hj as SDK_VERSION,lj as Subject,uj as Subscription,js as Surface,ju as VERSION,dj as ValueSubject,at as VideoFormat,pj as VideoQuality};