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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esnext.cjs.js CHANGED
@@ -1,40 +1,61 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.108-dev.377c6d18.0
3
- * Fri, 30 Aug 2024 10:29:25 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
- "use strict";var Af=Object.create;var fa=Object.defineProperty;var Rf=Object.getOwnPropertyDescriptor;var Lf=Object.getOwnPropertyNames;var $f=Object.getPrototypeOf,Mf=Object.prototype.hasOwnProperty;var f=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),Cf=(i,e)=>{for(var t in e)fa(i,t,{get:e[t],enumerable:!0})},iu=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Lf(e))!Mf.call(i,a)&&a!==t&&fa(i,a,{get:()=>e[a],enumerable:!(r=Rf(e,a))||r.enumerable});return i};var Ye=(i,e,t)=>(t=i!=null?Af($f(i)):{},iu(e||!i||!i.__esModule?fa(t,"default",{value:i,enumerable:!0}):t,i)),Df=i=>iu(fa({},"__esModule",{value:!0}),i);var we=f((Qx,su)=>{"use strict";su.exports=function(i){try{return!!i()}catch{return!0}}});var Fr=f((zx,nu)=>{"use strict";var Vf=we();nu.exports=!Vf(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var Se=f((Kx,lu)=>{"use strict";var ou=Fr(),uu=Function.prototype,Ls=uu.call,Bf=ou&&uu.bind.bind(Ls,Ls);lu.exports=ou?Bf:function(i){return function(){return Ls.apply(i,arguments)}}});var or=f((Jx,du)=>{"use strict";var cu=Se(),_f=cu({}.toString),Nf=cu("".slice);du.exports=function(i){return Nf(_f(i),8,-1)}});var hu=f((Xx,pu)=>{"use strict";var Ff=Se(),qf=we(),Uf=or(),$s=Object,Hf=Ff("".split);pu.exports=qf(function(){return!$s("z").propertyIsEnumerable(0)})?function(i){return Uf(i)==="String"?Hf(i,""):$s(i)}:$s});var ur=f((Zx,mu)=>{"use strict";mu.exports=function(i){return i==null}});var qr=f((eP,fu)=>{"use strict";var jf=ur(),Gf=TypeError;fu.exports=function(i){if(jf(i))throw new Gf("Can't call method on "+i);return i}});var lr=f((tP,bu)=>{"use strict";var Yf=hu(),Wf=qr();bu.exports=function(i){return Yf(Wf(i))}});var Ms=f((rP,Su)=>{"use strict";Su.exports=function(){}});var qt=f((iP,gu)=>{"use strict";gu.exports={}});var re=f((Cs,vu)=>{"use strict";var Ur=function(i){return i&&i.Math===Math&&i};vu.exports=Ur(typeof globalThis=="object"&&globalThis)||Ur(typeof window=="object"&&window)||Ur(typeof self=="object"&&self)||Ur(typeof global=="object"&&global)||Ur(typeof Cs=="object"&&Cs)||function(){return this}()||Function("return this")()});var te=f((aP,yu)=>{"use strict";var Ds=typeof document=="object"&&document.all;yu.exports=typeof Ds>"u"&&Ds!==void 0?function(i){return typeof i=="function"||i===Ds}:function(i){return typeof i=="function"}});var Eu=f((sP,Iu)=>{"use strict";var Qf=re(),zf=te(),Tu=Qf.WeakMap;Iu.exports=zf(Tu)&&/native code/.test(String(Tu))});var De=f((nP,xu)=>{"use strict";var Kf=te();xu.exports=function(i){return typeof i=="object"?i!==null:Kf(i)}});var Oe=f((oP,Pu)=>{"use strict";var Jf=we();Pu.exports=!Jf(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var va=f((uP,wu)=>{"use strict";var Xf=re(),ku=De(),Os=Xf.document,Zf=ku(Os)&&ku(Os.createElement);wu.exports=function(i){return Zf?Os.createElement(i):{}}});var Vs=f((lP,Au)=>{"use strict";var eb=Oe(),tb=we(),rb=va();Au.exports=!eb&&!tb(function(){return Object.defineProperty(rb("div"),"a",{get:function(){return 7}}).a!==7})});var Bs=f((cP,Ru)=>{"use strict";var ib=Oe(),ab=we();Ru.exports=ib&&ab(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var rt=f((dP,Lu)=>{"use strict";var sb=De(),nb=String,ob=TypeError;Lu.exports=function(i){if(sb(i))return i;throw new ob(nb(i)+" is not an object")}});var Ae=f((pP,$u)=>{"use strict";var ub=Fr(),ya=Function.prototype.call;$u.exports=ub?ya.bind(ya):function(){return ya.apply(ya,arguments)}});var Ta=f((hP,Mu)=>{"use strict";Mu.exports={}});var dt=f((mP,Du)=>{"use strict";var _s=Ta(),Ns=re(),lb=te(),Cu=function(i){return lb(i)?i:void 0};Du.exports=function(i,e){return arguments.length<2?Cu(_s[i])||Cu(Ns[i]):_s[i]&&_s[i][e]||Ns[i]&&Ns[i][e]}});var Hr=f((fP,Ou)=>{"use strict";var cb=Se();Ou.exports=cb({}.isPrototypeOf)});var cr=f((bP,_u)=>{"use strict";var db=re(),Vu=db.navigator,Bu=Vu&&Vu.userAgent;_u.exports=Bu?String(Bu):""});var qs=f((SP,ju)=>{"use strict";var Hu=re(),Fs=cr(),Nu=Hu.process,Fu=Hu.Deno,qu=Nu&&Nu.versions||Fu&&Fu.version,Uu=qu&&qu.v8,We,Ia;Uu&&(We=Uu.split("."),Ia=We[0]>0&&We[0]<4?1:+(We[0]+We[1]));!Ia&&Fs&&(We=Fs.match(/Edge\/(\d+)/),(!We||We[1]>=74)&&(We=Fs.match(/Chrome\/(\d+)/),We&&(Ia=+We[1])));ju.exports=Ia});var Us=f((gP,Yu)=>{"use strict";var Gu=qs(),pb=we(),hb=re(),mb=hb.String;Yu.exports=!!Object.getOwnPropertySymbols&&!pb(function(){var i=Symbol("symbol detection");return!mb(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&Gu&&Gu<41})});var Hs=f((vP,Wu)=>{"use strict";var fb=Us();Wu.exports=fb&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var js=f((yP,Qu)=>{"use strict";var bb=dt(),Sb=te(),gb=Hr(),vb=Hs(),yb=Object;Qu.exports=vb?function(i){return typeof i=="symbol"}:function(i){var e=bb("Symbol");return Sb(e)&&gb(e.prototype,yb(i))}});var jr=f((TP,zu)=>{"use strict";var Tb=String;zu.exports=function(i){try{return Tb(i)}catch{return"Object"}}});var pt=f((IP,Ku)=>{"use strict";var Ib=te(),Eb=jr(),xb=TypeError;Ku.exports=function(i){if(Ib(i))return i;throw new xb(Eb(i)+" is not a function")}});var Gr=f((EP,Ju)=>{"use strict";var Pb=pt(),kb=ur();Ju.exports=function(i,e){var t=i[e];return kb(t)?void 0:Pb(t)}});var Zu=f((xP,Xu)=>{"use strict";var Gs=Ae(),Ys=te(),Ws=De(),wb=TypeError;Xu.exports=function(i,e){var t,r;if(e==="string"&&Ys(t=i.toString)&&!Ws(r=Gs(t,i))||Ys(t=i.valueOf)&&!Ws(r=Gs(t,i))||e!=="string"&&Ys(t=i.toString)&&!Ws(r=Gs(t,i)))return r;throw new wb("Can't convert object to primitive value")}});var Qe=f((PP,el)=>{"use strict";el.exports=!0});var il=f((kP,rl)=>{"use strict";var tl=re(),Ab=Object.defineProperty;rl.exports=function(i,e){try{Ab(tl,i,{value:e,configurable:!0,writable:!0})}catch{tl[i]=e}return e}});var Yr=f((wP,nl)=>{"use strict";var Rb=Qe(),Lb=re(),$b=il(),al="__core-js_shared__",sl=nl.exports=Lb[al]||$b(al,{});(sl.versions||(sl.versions=[])).push({version:"3.38.0",mode:Rb?"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 Qs=f((AP,ul)=>{"use strict";var ol=Yr();ul.exports=function(i,e){return ol[i]||(ol[i]=e||{})}});var Wr=f((RP,ll)=>{"use strict";var Mb=qr(),Cb=Object;ll.exports=function(i){return Cb(Mb(i))}});var ze=f((LP,cl)=>{"use strict";var Db=Se(),Ob=Wr(),Vb=Db({}.hasOwnProperty);cl.exports=Object.hasOwn||function(e,t){return Vb(Ob(e),t)}});var zs=f(($P,dl)=>{"use strict";var Bb=Se(),_b=0,Nb=Math.random(),Fb=Bb(1 .toString);dl.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+Fb(++_b+Nb,36)}});var fe=f((MP,hl)=>{"use strict";var qb=re(),Ub=Qs(),pl=ze(),Hb=zs(),jb=Us(),Gb=Hs(),dr=qb.Symbol,Ks=Ub("wks"),Yb=Gb?dr.for||dr:dr&&dr.withoutSetter||Hb;hl.exports=function(i){return pl(Ks,i)||(Ks[i]=jb&&pl(dr,i)?dr[i]:Yb("Symbol."+i)),Ks[i]}});var Sl=f((CP,bl)=>{"use strict";var Wb=Ae(),ml=De(),fl=js(),Qb=Gr(),zb=Zu(),Kb=fe(),Jb=TypeError,Xb=Kb("toPrimitive");bl.exports=function(i,e){if(!ml(i)||fl(i))return i;var t=Qb(i,Xb),r;if(t){if(e===void 0&&(e="default"),r=Wb(t,i,e),!ml(r)||fl(r))return r;throw new Jb("Can't convert object to primitive value")}return e===void 0&&(e="number"),zb(i,e)}});var Js=f((DP,gl)=>{"use strict";var Zb=Sl(),eS=js();gl.exports=function(i){var e=Zb(i,"string");return eS(e)?e:e+""}});var Ut=f(yl=>{"use strict";var tS=Oe(),rS=Vs(),iS=Bs(),Ea=rt(),vl=Js(),aS=TypeError,Xs=Object.defineProperty,sS=Object.getOwnPropertyDescriptor,Zs="enumerable",en="configurable",tn="writable";yl.f=tS?iS?function(e,t,r){if(Ea(e),t=vl(t),Ea(r),typeof e=="function"&&t==="prototype"&&"value"in r&&tn in r&&!r[tn]){var a=sS(e,t);a&&a[tn]&&(e[t]=r.value,r={configurable:en in r?r[en]:a[en],enumerable:Zs in r?r[Zs]:a[Zs],writable:!1})}return Xs(e,t,r)}:Xs:function(e,t,r){if(Ea(e),t=vl(t),Ea(r),rS)try{return Xs(e,t,r)}catch{}if("get"in r||"set"in r)throw new aS("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Qr=f((VP,Tl)=>{"use strict";Tl.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var pr=f((BP,Il)=>{"use strict";var nS=Oe(),oS=Ut(),uS=Qr();Il.exports=nS?function(i,e,t){return oS.f(i,e,uS(1,t))}:function(i,e,t){return i[e]=t,i}});var xa=f((_P,xl)=>{"use strict";var lS=Qs(),cS=zs(),El=lS("keys");xl.exports=function(i){return El[i]||(El[i]=cS(i))}});var Pa=f((NP,Pl)=>{"use strict";Pl.exports={}});var nn=f((FP,Al)=>{"use strict";var dS=Eu(),wl=re(),pS=De(),hS=pr(),rn=ze(),an=Yr(),mS=xa(),fS=Pa(),kl="Object already initialized",sn=wl.TypeError,bS=wl.WeakMap,ka,zr,wa,SS=function(i){return wa(i)?zr(i):ka(i,{})},gS=function(i){return function(e){var t;if(!pS(e)||(t=zr(e)).type!==i)throw new sn("Incompatible receiver, "+i+" required");return t}};dS||an.state?(Ke=an.state||(an.state=new bS),Ke.get=Ke.get,Ke.has=Ke.has,Ke.set=Ke.set,ka=function(i,e){if(Ke.has(i))throw new sn(kl);return e.facade=i,Ke.set(i,e),e},zr=function(i){return Ke.get(i)||{}},wa=function(i){return Ke.has(i)}):(Ht=mS("state"),fS[Ht]=!0,ka=function(i,e){if(rn(i,Ht))throw new sn(kl);return e.facade=i,hS(i,Ht,e),e},zr=function(i){return rn(i,Ht)?i[Ht]:{}},wa=function(i){return rn(i,Ht)});var Ke,Ht;Al.exports={set:ka,get:zr,has:wa,enforce:SS,getterFor:gS}});var on=f((qP,Ml)=>{"use strict";var vS=Fr(),$l=Function.prototype,Rl=$l.apply,Ll=$l.call;Ml.exports=typeof Reflect=="object"&&Reflect.apply||(vS?Ll.bind(Rl):function(){return Ll.apply(Rl,arguments)})});var un=f((UP,Cl)=>{"use strict";var yS=or(),TS=Se();Cl.exports=function(i){if(yS(i)==="Function")return TS(i)}});var Bl=f(Vl=>{"use strict";var Dl={}.propertyIsEnumerable,Ol=Object.getOwnPropertyDescriptor,IS=Ol&&!Dl.call({1:2},1);Vl.f=IS?function(e){var t=Ol(this,e);return!!t&&t.enumerable}:Dl});var Fl=f(Nl=>{"use strict";var ES=Oe(),xS=Ae(),PS=Bl(),kS=Qr(),wS=lr(),AS=Js(),RS=ze(),LS=Vs(),_l=Object.getOwnPropertyDescriptor;Nl.f=ES?_l:function(e,t){if(e=wS(e),t=AS(t),LS)try{return _l(e,t)}catch{}if(RS(e,t))return kS(!xS(PS.f,e,t),e[t])}});var ln=f((GP,ql)=>{"use strict";var $S=we(),MS=te(),CS=/#|\.prototype\./,Kr=function(i,e){var t=OS[DS(i)];return t===BS?!0:t===VS?!1:MS(e)?$S(e):!!e},DS=Kr.normalize=function(i){return String(i).replace(CS,".").toLowerCase()},OS=Kr.data={},VS=Kr.NATIVE="N",BS=Kr.POLYFILL="P";ql.exports=Kr});var Jr=f((YP,Hl)=>{"use strict";var Ul=un(),_S=pt(),NS=Fr(),FS=Ul(Ul.bind);Hl.exports=function(i,e){return _S(i),e===void 0?i:NS?FS(i,e):function(){return i.apply(e,arguments)}}});var Ve=f((WP,Gl)=>{"use strict";var Xr=re(),qS=on(),US=un(),HS=te(),jS=Fl().f,GS=ln(),hr=Ta(),YS=Jr(),mr=pr(),jl=ze();Yr();var WS=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 qS(i,this,arguments)};return e.prototype=i.prototype,e};Gl.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?Xr:a?Xr[t]:Xr[t]&&Xr[t].prototype,o=r?hr:hr[t]||mr(hr,t,{})[t],l=o.prototype,u,c,d,p,m,b,g,y,I;for(p in e)u=GS(r?p:t+(a?".":"#")+p,i.forced),c=!u&&n&&jl(n,p),b=o[p],c&&(i.dontCallGetSet?(I=jS(n,p),g=I&&I.value):g=n[p]),m=c&&g?g:e[p],!(!u&&!s&&typeof b==typeof m)&&(i.bind&&c?y=YS(m,Xr):i.wrap&&c?y=WS(m):s&&HS(m)?y=US(m):y=m,(i.sham||m&&m.sham||b&&b.sham)&&mr(y,"sham",!0),mr(o,p,y),s&&(d=t+"Prototype",jl(hr,d)||mr(hr,d,{}),mr(hr[d],p,m),i.real&&l&&(u||!l[p])&&mr(l,p,m)))}});var Ql=f((QP,Wl)=>{"use strict";var cn=Oe(),QS=ze(),Yl=Function.prototype,zS=cn&&Object.getOwnPropertyDescriptor,dn=QS(Yl,"name"),KS=dn&&function(){}.name==="something",JS=dn&&(!cn||cn&&zS(Yl,"name").configurable);Wl.exports={EXISTS:dn,PROPER:KS,CONFIGURABLE:JS}});var Kl=f((zP,zl)=>{"use strict";var XS=Math.ceil,ZS=Math.floor;zl.exports=Math.trunc||function(e){var t=+e;return(t>0?ZS:XS)(t)}});var Aa=f((KP,Jl)=>{"use strict";var eg=Kl();Jl.exports=function(i){var e=+i;return e!==e||e===0?0:eg(e)}});var Zl=f((JP,Xl)=>{"use strict";var tg=Aa(),rg=Math.max,ig=Math.min;Xl.exports=function(i,e){var t=tg(i);return t<0?rg(t+e,0):ig(t,e)}});var tc=f((XP,ec)=>{"use strict";var ag=Aa(),sg=Math.min;ec.exports=function(i){var e=ag(i);return e>0?sg(e,9007199254740991):0}});var Ra=f((ZP,rc)=>{"use strict";var ng=tc();rc.exports=function(i){return ng(i.length)}});var sc=f((ek,ac)=>{"use strict";var og=lr(),ug=Zl(),lg=Ra(),ic=function(i){return function(e,t,r){var a=og(e),s=lg(a);if(s===0)return!i&&-1;var n=ug(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}};ac.exports={includes:ic(!0),indexOf:ic(!1)}});var uc=f((tk,oc)=>{"use strict";var cg=Se(),pn=ze(),dg=lr(),pg=sc().indexOf,hg=Pa(),nc=cg([].push);oc.exports=function(i,e){var t=dg(i),r=0,a=[],s;for(s in t)!pn(hg,s)&&pn(t,s)&&nc(a,s);for(;e.length>r;)pn(t,s=e[r++])&&(~pg(a,s)||nc(a,s));return a}});var hn=f((rk,lc)=>{"use strict";lc.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var dc=f((ik,cc)=>{"use strict";var mg=uc(),fg=hn();cc.exports=Object.keys||function(e){return mg(e,fg)}});var hc=f(pc=>{"use strict";var bg=Oe(),Sg=Bs(),gg=Ut(),vg=rt(),yg=lr(),Tg=dc();pc.f=bg&&!Sg?Object.defineProperties:function(e,t){vg(e);for(var r=yg(t),a=Tg(t),s=a.length,n=0,o;s>n;)gg.f(e,o=a[n++],r[o]);return e}});var mn=f((sk,mc)=>{"use strict";var Ig=dt();mc.exports=Ig("document","documentElement")});var gn=f((nk,Tc)=>{"use strict";var Eg=rt(),xg=hc(),fc=hn(),Pg=Pa(),kg=mn(),wg=va(),Ag=xa(),bc=">",Sc="<",bn="prototype",Sn="script",vc=Ag("IE_PROTO"),fn=function(){},yc=function(i){return Sc+Sn+bc+i+Sc+"/"+Sn+bc},gc=function(i){i.write(yc("")),i.close();var e=i.parentWindow.Object;return i=null,e},Rg=function(){var i=wg("iframe"),e="java"+Sn+":",t;return i.style.display="none",kg.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(yc("document.F=Object")),t.close(),t.F},La,$a=function(){try{La=new ActiveXObject("htmlfile")}catch{}$a=typeof document<"u"?document.domain&&La?gc(La):Rg():gc(La);for(var i=fc.length;i--;)delete $a[bn][fc[i]];return $a()};Pg[vc]=!0;Tc.exports=Object.create||function(e,t){var r;return e!==null?(fn[bn]=Eg(e),r=new fn,fn[bn]=null,r[vc]=e):r=$a(),t===void 0?r:xg.f(r,t)}});var Ec=f((ok,Ic)=>{"use strict";var Lg=we();Ic.exports=!Lg(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var yn=f((uk,Pc)=>{"use strict";var $g=ze(),Mg=te(),Cg=Wr(),Dg=xa(),Og=Ec(),xc=Dg("IE_PROTO"),vn=Object,Vg=vn.prototype;Pc.exports=Og?vn.getPrototypeOf:function(i){var e=Cg(i);if($g(e,xc))return e[xc];var t=e.constructor;return Mg(t)&&e instanceof t?t.prototype:e instanceof vn?Vg:null}});var fr=f((lk,kc)=>{"use strict";var Bg=pr();kc.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:Bg(i,e,t),i}});var xn=f((ck,Rc)=>{"use strict";var _g=we(),Ng=te(),Fg=De(),qg=gn(),wc=yn(),Ug=fr(),Hg=fe(),jg=Qe(),En=Hg("iterator"),Ac=!1,ht,Tn,In;[].keys&&(In=[].keys(),"next"in In?(Tn=wc(wc(In)),Tn!==Object.prototype&&(ht=Tn)):Ac=!0);var Gg=!Fg(ht)||_g(function(){var i={};return ht[En].call(i)!==i});Gg?ht={}:jg&&(ht=qg(ht));Ng(ht[En])||Ug(ht,En,function(){return this});Rc.exports={IteratorPrototype:ht,BUGGY_SAFARI_ITERATORS:Ac}});var Ma=f((dk,$c)=>{"use strict";var Yg=fe(),Wg=Yg("toStringTag"),Lc={};Lc[Wg]="z";$c.exports=String(Lc)==="[object z]"});var Zr=f((pk,Mc)=>{"use strict";var Qg=Ma(),zg=te(),Ca=or(),Kg=fe(),Jg=Kg("toStringTag"),Xg=Object,Zg=Ca(function(){return arguments}())==="Arguments",ev=function(i,e){try{return i[e]}catch{}};Mc.exports=Qg?Ca:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=ev(e=Xg(i),Jg))=="string"?t:Zg?Ca(e):(r=Ca(e))==="Object"&&zg(e.callee)?"Arguments":r}});var Dc=f((hk,Cc)=>{"use strict";var tv=Ma(),rv=Zr();Cc.exports=tv?{}.toString:function(){return"[object "+rv(this)+"]"}});var ei=f((mk,Vc)=>{"use strict";var iv=Ma(),av=Ut().f,sv=pr(),nv=ze(),ov=Dc(),uv=fe(),Oc=uv("toStringTag");Vc.exports=function(i,e,t,r){var a=t?i:i&&i.prototype;a&&(nv(a,Oc)||av(a,Oc,{configurable:!0,value:e}),r&&!iv&&sv(a,"toString",ov))}});var _c=f((fk,Bc)=>{"use strict";var lv=xn().IteratorPrototype,cv=gn(),dv=Qr(),pv=ei(),hv=qt(),mv=function(){return this};Bc.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=cv(lv,{next:dv(+!r,t)}),pv(i,a,!1,!0),hv[a]=mv,i}});var Fc=f((bk,Nc)=>{"use strict";var fv=Se(),bv=pt();Nc.exports=function(i,e,t){try{return fv(bv(Object.getOwnPropertyDescriptor(i,e)[t]))}catch{}}});var Uc=f((Sk,qc)=>{"use strict";var Sv=De();qc.exports=function(i){return Sv(i)||i===null}});var jc=f((gk,Hc)=>{"use strict";var gv=Uc(),vv=String,yv=TypeError;Hc.exports=function(i){if(gv(i))return i;throw new yv("Can't set "+vv(i)+" as a prototype")}});var Pn=f((vk,Gc)=>{"use strict";var Tv=Fc(),Iv=De(),Ev=qr(),xv=jc();Gc.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=Tv(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch{}return function(a,s){return Ev(a),xv(s),Iv(a)&&(i?t(a,s):a.__proto__=s),a}}():void 0)});var rd=f((yk,td)=>{"use strict";var Pv=Ve(),kv=Ae(),Da=Qe(),Zc=Ql(),wv=te(),Av=_c(),Yc=yn(),Wc=Pn(),Rv=ei(),Lv=pr(),kn=fr(),$v=fe(),Qc=qt(),ed=xn(),Mv=Zc.PROPER,Cv=Zc.CONFIGURABLE,zc=ed.IteratorPrototype,Oa=ed.BUGGY_SAFARI_ITERATORS,ti=$v("iterator"),Kc="keys",ri="values",Jc="entries",Xc=function(){return this};td.exports=function(i,e,t,r,a,s,n){Av(t,e,r);var o=function(I){if(I===a&&p)return p;if(!Oa&&I&&I in c)return c[I];switch(I){case Kc:return function(){return new t(this,I)};case ri:return function(){return new t(this,I)};case Jc:return function(){return new t(this,I)}}return function(){return new t(this)}},l=e+" Iterator",u=!1,c=i.prototype,d=c[ti]||c["@@iterator"]||a&&c[a],p=!Oa&&d||o(a),m=e==="Array"&&c.entries||d,b,g,y;if(m&&(b=Yc(m.call(new i)),b!==Object.prototype&&b.next&&(!Da&&Yc(b)!==zc&&(Wc?Wc(b,zc):wv(b[ti])||kn(b,ti,Xc)),Rv(b,l,!0,!0),Da&&(Qc[l]=Xc))),Mv&&a===ri&&d&&d.name!==ri&&(!Da&&Cv?Lv(c,"name",ri):(u=!0,p=function(){return kv(d,this)})),a)if(g={values:o(ri),keys:s?p:o(Kc),entries:o(Jc)},n)for(y in g)(Oa||u||!(y in c))&&kn(c,y,g[y]);else Pv({target:e,proto:!0,forced:Oa||u},g);return(!Da||n)&&c[ti]!==p&&kn(c,ti,p,{name:a}),Qc[e]=p,g}});var ad=f((Tk,id)=>{"use strict";id.exports=function(i,e){return{value:i,done:e}}});var An=f((Ik,ld)=>{"use strict";var Dv=lr(),wn=Ms(),sd=qt(),od=nn(),Ov=Ut().f,Vv=rd(),Va=ad(),Bv=Qe(),_v=Oe(),ud="Array Iterator",Nv=od.set,Fv=od.getterFor(ud);ld.exports=Vv(Array,"Array",function(i,e){Nv(this,{type:ud,target:Dv(i),index:0,kind:e})},function(){var i=Fv(this),e=i.target,t=i.index++;if(!e||t>=e.length)return i.target=void 0,Va(void 0,!0);switch(i.kind){case"keys":return Va(t,!1);case"values":return Va(e[t],!1)}return Va([t,e[t]],!1)},"values");var nd=sd.Arguments=sd.Array;wn("keys");wn("values");wn("entries");if(!Bv&&_v&&nd.name!=="values")try{Ov(nd,"name",{value:"values"})}catch{}});var dd=f((Ek,cd)=>{"use strict";var qv=fe(),Uv=qt(),Hv=qv("iterator"),jv=Array.prototype;cd.exports=function(i){return i!==void 0&&(Uv.Array===i||jv[Hv]===i)}});var Rn=f((xk,hd)=>{"use strict";var Gv=Zr(),pd=Gr(),Yv=ur(),Wv=qt(),Qv=fe(),zv=Qv("iterator");hd.exports=function(i){if(!Yv(i))return pd(i,zv)||pd(i,"@@iterator")||Wv[Gv(i)]}});var fd=f((Pk,md)=>{"use strict";var Kv=Ae(),Jv=pt(),Xv=rt(),Zv=jr(),ey=Rn(),ty=TypeError;md.exports=function(i,e){var t=arguments.length<2?ey(i):e;if(Jv(t))return Xv(Kv(t,i));throw new ty(Zv(i)+" is not iterable")}});var gd=f((kk,Sd)=>{"use strict";var ry=Ae(),bd=rt(),iy=Gr();Sd.exports=function(i,e,t){var r,a;bd(i);try{if(r=iy(i,"return"),!r){if(e==="throw")throw t;return t}r=ry(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return bd(r),t}});var _a=f((wk,Id)=>{"use strict";var ay=Jr(),sy=Ae(),ny=rt(),oy=jr(),uy=dd(),ly=Ra(),vd=Hr(),cy=fd(),dy=Rn(),yd=gd(),py=TypeError,Ba=function(i,e){this.stopped=i,this.result=e},Td=Ba.prototype;Id.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=ay(e,r),u,c,d,p,m,b,g,y=function(D){return u&&yd(u,"normal",D),new Ba(!0,D)},I=function(D){return a?(ny(D),o?l(D[0],D[1],y):l(D[0],D[1])):o?l(D,y):l(D)};if(s)u=i.iterator;else if(n)u=i;else{if(c=dy(i),!c)throw new py(oy(i)+" is not iterable");if(uy(c)){for(d=0,p=ly(i);p>d;d++)if(m=I(i[d]),m&&vd(Td,m))return m;return new Ba(!1)}u=cy(i,c)}for(b=s?i.next:u.next;!(g=sy(b,u)).done;){try{m=I(g.value)}catch(D){yd(u,"throw",D)}if(typeof m=="object"&&m&&vd(Td,m))return m}return new Ba(!1)}});var xd=f((Ak,Ed)=>{"use strict";var hy=Oe(),my=Ut(),fy=Qr();Ed.exports=function(i,e,t){hy?my.f(i,e,fy(0,t)):i[e]=t}});var Pd=f(()=>{"use strict";var by=Ve(),Sy=_a(),gy=xd();by({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Sy(e,function(r,a){gy(t,r,a)},{AS_ENTRIES:!0}),t}})});var wd=f(($k,kd)=>{"use strict";An();Pd();var vy=Ta();kd.exports=vy.Object.fromEntries});var Rd=f((Mk,Ad)=>{"use strict";Ad.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 $d=f(()=>{"use strict";An();var yy=Rd(),Ty=re(),Iy=ei(),Ld=qt();for(Na in yy)Iy(Ty[Na],Na),Ld[Na]=Ld.Array;var Na});var Cd=f((Ok,Md)=>{"use strict";var Ey=wd();$d();Md.exports=Ey});var Ln=f((Vk,Dd)=>{"use strict";var xy=Cd();Dd.exports=xy});var Od=f(()=>{"use strict"});var $n=f((Nk,Vd)=>{"use strict";var ii=re(),Py=cr(),ky=or(),Fa=function(i){return Py.slice(0,i.length)===i};Vd.exports=function(){return Fa("Bun/")?"BUN":Fa("Cloudflare-Workers")?"CLOUDFLARE":Fa("Deno/")?"DENO":Fa("Node.js/")?"NODE":ii.Bun&&typeof Bun.version=="string"?"BUN":ii.Deno&&typeof Deno.version=="object"?"DENO":ky(ii.process)==="process"?"NODE":ii.window&&ii.document?"BROWSER":"REST"}()});var qa=f((Fk,Bd)=>{"use strict";var wy=$n();Bd.exports=wy==="NODE"});var Nd=f((qk,_d)=>{"use strict";var Ay=Ut();_d.exports=function(i,e,t){return Ay.f(i,e,t)}});var Ud=f((Uk,qd)=>{"use strict";var Ry=dt(),Ly=Nd(),$y=fe(),My=Oe(),Fd=$y("species");qd.exports=function(i){var e=Ry(i);My&&e&&!e[Fd]&&Ly(e,Fd,{configurable:!0,get:function(){return this}})}});var jd=f((Hk,Hd)=>{"use strict";var Cy=Hr(),Dy=TypeError;Hd.exports=function(i,e){if(Cy(e,i))return i;throw new Dy("Incorrect invocation")}});var Cn=f((jk,Gd)=>{"use strict";var Oy=Se(),Vy=te(),Mn=Yr(),By=Oy(Function.toString);Vy(Mn.inspectSource)||(Mn.inspectSource=function(i){return By(i)});Gd.exports=Mn.inspectSource});var Jd=f((Gk,Kd)=>{"use strict";var _y=Se(),Ny=we(),Yd=te(),Fy=Zr(),qy=dt(),Uy=Cn(),Wd=function(){},Qd=qy("Reflect","construct"),Dn=/^\s*(?:class|function)\b/,Hy=_y(Dn.exec),jy=!Dn.test(Wd),ai=function(e){if(!Yd(e))return!1;try{return Qd(Wd,[],e),!0}catch{return!1}},zd=function(e){if(!Yd(e))return!1;switch(Fy(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return jy||!!Hy(Dn,Uy(e))}catch{return!0}};zd.sham=!0;Kd.exports=!Qd||Ny(function(){var i;return ai(ai.call)||!ai(Object)||!ai(function(){i=!0})||i})?zd:ai});var Zd=f((Yk,Xd)=>{"use strict";var Gy=Jd(),Yy=jr(),Wy=TypeError;Xd.exports=function(i){if(Gy(i))return i;throw new Wy(Yy(i)+" is not a constructor")}});var On=f((Wk,tp)=>{"use strict";var ep=rt(),Qy=Zd(),zy=ur(),Ky=fe(),Jy=Ky("species");tp.exports=function(i,e){var t=ep(i).constructor,r;return t===void 0||zy(r=ep(t)[Jy])?e:Qy(r)}});var ip=f((Qk,rp)=>{"use strict";var Xy=Se();rp.exports=Xy([].slice)});var sp=f((zk,ap)=>{"use strict";var Zy=TypeError;ap.exports=function(i,e){if(i<e)throw new Zy("Not enough arguments");return i}});var Vn=f((Kk,np)=>{"use strict";var eT=cr();np.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(eT)});var Gn=f((Jk,fp)=>{"use strict";var Re=re(),tT=on(),rT=Jr(),op=te(),iT=ze(),mp=we(),up=mn(),aT=ip(),lp=va(),sT=sp(),nT=Vn(),oT=qa(),Un=Re.setImmediate,Hn=Re.clearImmediate,uT=Re.process,Bn=Re.Dispatch,lT=Re.Function,cp=Re.MessageChannel,cT=Re.String,_n=0,si={},dp="onreadystatechange",ni,jt,Nn,Fn;mp(function(){ni=Re.location});var jn=function(i){if(iT(si,i)){var e=si[i];delete si[i],e()}},qn=function(i){return function(){jn(i)}},pp=function(i){jn(i.data)},hp=function(i){Re.postMessage(cT(i),ni.protocol+"//"+ni.host)};(!Un||!Hn)&&(Un=function(e){sT(arguments.length,1);var t=op(e)?e:lT(e),r=aT(arguments,1);return si[++_n]=function(){tT(t,void 0,r)},jt(_n),_n},Hn=function(e){delete si[e]},oT?jt=function(i){uT.nextTick(qn(i))}:Bn&&Bn.now?jt=function(i){Bn.now(qn(i))}:cp&&!nT?(Nn=new cp,Fn=Nn.port2,Nn.port1.onmessage=pp,jt=rT(Fn.postMessage,Fn)):Re.addEventListener&&op(Re.postMessage)&&!Re.importScripts&&ni&&ni.protocol!=="file:"&&!mp(hp)?(jt=hp,Re.addEventListener("message",pp,!1)):dp in lp("script")?jt=function(i){up.appendChild(lp("script"))[dp]=function(){up.removeChild(this),jn(i)}}:jt=function(i){setTimeout(qn(i),0)});fp.exports={set:Un,clear:Hn}});var gp=f((Xk,Sp)=>{"use strict";var bp=re(),dT=Oe(),pT=Object.getOwnPropertyDescriptor;Sp.exports=function(i){if(!dT)return bp[i];var e=pT(bp,i);return e&&e.value}});var Yn=f((Zk,yp)=>{"use strict";var vp=function(){this.head=null,this.tail=null};vp.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}}};yp.exports=vp});var Ip=f((ew,Tp)=>{"use strict";var hT=cr();Tp.exports=/ipad|iphone|ipod/i.test(hT)&&typeof Pebble<"u"});var xp=f((tw,Ep)=>{"use strict";var mT=cr();Ep.exports=/web0s(?!.*chrome)/i.test(mT)});var $p=f((rw,Lp)=>{"use strict";var Sr=re(),fT=gp(),Pp=Jr(),Wn=Gn().set,bT=Yn(),ST=Vn(),gT=Ip(),vT=xp(),Qn=qa(),kp=Sr.MutationObserver||Sr.WebKitMutationObserver,wp=Sr.document,Ap=Sr.process,Ua=Sr.Promise,Jn=fT("queueMicrotask"),br,zn,Kn,Ha,Rp;Jn||(oi=new bT,ui=function(){var i,e;for(Qn&&(i=Ap.domain)&&i.exit();e=oi.get();)try{e()}catch(t){throw oi.head&&br(),t}i&&i.enter()},!ST&&!Qn&&!vT&&kp&&wp?(zn=!0,Kn=wp.createTextNode(""),new kp(ui).observe(Kn,{characterData:!0}),br=function(){Kn.data=zn=!zn}):!gT&&Ua&&Ua.resolve?(Ha=Ua.resolve(void 0),Ha.constructor=Ua,Rp=Pp(Ha.then,Ha),br=function(){Rp(ui)}):Qn?br=function(){Ap.nextTick(ui)}:(Wn=Pp(Wn,Sr),br=function(){Wn(ui)}),Jn=function(i){oi.head||br(),oi.add(i)});var oi,ui;Lp.exports=Jn});var Cp=f((iw,Mp)=>{"use strict";Mp.exports=function(i,e){try{arguments.length===1?console.error(i):console.error(i,e)}catch{}}});var ja=f((aw,Dp)=>{"use strict";Dp.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var Gt=f((sw,Op)=>{"use strict";var yT=re();Op.exports=yT.Promise});var gr=f((nw,Np)=>{"use strict";var TT=re(),li=Gt(),IT=te(),ET=ln(),xT=Cn(),PT=fe(),Vp=$n(),kT=Qe(),Xn=qs(),Bp=li&&li.prototype,wT=PT("species"),Zn=!1,_p=IT(TT.PromiseRejectionEvent),AT=ET("Promise",function(){var i=xT(li),e=i!==String(li);if(!e&&Xn===66||kT&&!(Bp.catch&&Bp.finally))return!0;if(!Xn||Xn<51||!/native code/.test(i)){var t=new li(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[wT]=r,Zn=t.then(function(){})instanceof r,!Zn)return!0}return!e&&(Vp==="BROWSER"||Vp==="DENO")&&!_p});Np.exports={CONSTRUCTOR:AT,REJECTION_EVENT:_p,SUBCLASSING:Zn}});var vr=f((ow,qp)=>{"use strict";var Fp=pt(),RT=TypeError,LT=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw new RT("Bad Promise constructor");e=r,t=a}),this.resolve=Fp(e),this.reject=Fp(t)};qp.exports.f=function(i){return new LT(i)}});var nh=f(()=>{"use strict";var $T=Ve(),MT=Qe(),Qa=qa(),Lt=re(),Er=Ae(),Up=fr(),Hp=Pn(),CT=ei(),DT=Ud(),OT=pt(),Wa=te(),VT=De(),BT=jd(),_T=On(),Qp=Gn().set,ao=$p(),NT=Cp(),FT=ja(),qT=Yn(),zp=nn(),za=Gt(),so=gr(),Kp=vr(),Ka="Promise",Jp=so.CONSTRUCTOR,UT=so.REJECTION_EVENT,HT=so.SUBCLASSING,eo=zp.getterFor(Ka),jT=zp.set,yr=za&&za.prototype,Yt=za,Ga=yr,Xp=Lt.TypeError,to=Lt.document,no=Lt.process,ro=Kp.f,GT=ro,YT=!!(to&&to.createEvent&&Lt.dispatchEvent),Zp="unhandledrejection",WT="rejectionhandled",jp=0,eh=1,QT=2,oo=1,th=2,Ya,Gp,zT,Yp,rh=function(i){var e;return VT(i)&&Wa(e=i.then)?e:!1},ih=function(i,e){var t=e.value,r=e.state===eh,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,l,u,c;try{a?(r||(e.rejection===th&&JT(e),e.rejection=oo),a===!0?l=t:(o&&o.enter(),l=a(t),o&&(o.exit(),c=!0)),l===i.promise?n(new Xp("Promise-chain cycle")):(u=rh(l))?Er(u,l,s,n):s(l)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},ah=function(i,e){i.notified||(i.notified=!0,ao(function(){for(var t=i.reactions,r;r=t.get();)ih(r,i);i.notified=!1,e&&!i.rejection&&KT(i)}))},sh=function(i,e,t){var r,a;YT?(r=to.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),Lt.dispatchEvent(r)):r={promise:e,reason:t},!UT&&(a=Lt["on"+i])?a(r):i===Zp&&NT("Unhandled promise rejection",t)},KT=function(i){Er(Qp,Lt,function(){var e=i.facade,t=i.value,r=Wp(i),a;if(r&&(a=FT(function(){Qa?no.emit("unhandledRejection",t,e):sh(Zp,e,t)}),i.rejection=Qa||Wp(i)?th:oo,a.error))throw a.value})},Wp=function(i){return i.rejection!==oo&&!i.parent},JT=function(i){Er(Qp,Lt,function(){var e=i.facade;Qa?no.emit("rejectionHandled",e):sh(WT,e,i.value)})},Tr=function(i,e,t){return function(r){i(e,r,t)}},Ir=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=QT,ah(i,!0))},io=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw new Xp("Promise can't be resolved itself");var r=rh(e);r?ao(function(){var a={done:!1};try{Er(r,e,Tr(io,a,i),Tr(Ir,a,i))}catch(s){Ir(a,s,i)}}):(i.value=e,i.state=eh,ah(i,!1))}catch(a){Ir({done:!1},a,i)}}};if(Jp&&(Yt=function(e){BT(this,Ga),OT(e),Er(Ya,this);var t=eo(this);try{e(Tr(io,t),Tr(Ir,t))}catch(r){Ir(t,r)}},Ga=Yt.prototype,Ya=function(e){jT(this,{type:Ka,done:!1,notified:!1,parent:!1,reactions:new qT,rejection:!1,state:jp,value:void 0})},Ya.prototype=Up(Ga,"then",function(e,t){var r=eo(this),a=ro(_T(this,Yt));return r.parent=!0,a.ok=Wa(e)?e:!0,a.fail=Wa(t)&&t,a.domain=Qa?no.domain:void 0,r.state===jp?r.reactions.add(a):ao(function(){ih(a,r)}),a.promise}),Gp=function(){var i=new Ya,e=eo(i);this.promise=i,this.resolve=Tr(io,e),this.reject=Tr(Ir,e)},Kp.f=ro=function(i){return i===Yt||i===zT?new Gp(i):GT(i)},!MT&&Wa(za)&&yr!==Object.prototype)){Yp=yr.then,HT||Up(yr,"then",function(e,t){var r=this;return new Yt(function(a,s){Er(Yp,r,a,s)}).then(e,t)},{unsafe:!0});try{delete yr.constructor}catch{}Hp&&Hp(yr,Ga)}$T({global:!0,constructor:!0,wrap:!0,forced:Jp},{Promise:Yt});CT(Yt,Ka,!1,!0);DT(Ka)});var dh=f((cw,ch)=>{"use strict";var XT=fe(),uh=XT("iterator"),lh=!1;try{oh=0,uo={next:function(){return{done:!!oh++}},return:function(){lh=!0}},uo[uh]=function(){return this},Array.from(uo,function(){throw 2})}catch{}var oh,uo;ch.exports=function(i,e){try{if(!e&&!lh)return!1}catch{return!1}var t=!1;try{var r={};r[uh]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch{}return t}});var lo=f((dw,ph)=>{"use strict";var ZT=Gt(),eI=dh(),tI=gr().CONSTRUCTOR;ph.exports=tI||!eI(function(i){ZT.all(i).then(void 0,function(){})})});var hh=f(()=>{"use strict";var rI=Ve(),iI=Ae(),aI=pt(),sI=vr(),nI=ja(),oI=_a(),uI=lo();rI({target:"Promise",stat:!0,forced:uI},{all:function(e){var t=this,r=sI.f(t),a=r.resolve,s=r.reject,n=nI(function(){var o=aI(t.resolve),l=[],u=0,c=1;oI(e,function(d){var p=u++,m=!1;c++,iI(o,t,d).then(function(b){m||(m=!0,l[p]=b,--c||a(l))},s)}),--c||a(l)});return n.error&&s(n.value),r.promise}})});var fh=f(()=>{"use strict";var lI=Ve(),cI=Qe(),dI=gr().CONSTRUCTOR,po=Gt(),pI=dt(),hI=te(),mI=fr(),mh=po&&po.prototype;lI({target:"Promise",proto:!0,forced:dI,real:!0},{catch:function(i){return this.then(void 0,i)}});!cI&&hI(po)&&(co=pI("Promise").prototype.catch,mh.catch!==co&&mI(mh,"catch",co,{unsafe:!0}));var co});var bh=f(()=>{"use strict";var fI=Ve(),bI=Ae(),SI=pt(),gI=vr(),vI=ja(),yI=_a(),TI=lo();fI({target:"Promise",stat:!0,forced:TI},{race:function(e){var t=this,r=gI.f(t),a=r.reject,s=vI(function(){var n=SI(t.resolve);yI(e,function(o){bI(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var Sh=f(()=>{"use strict";var II=Ve(),EI=vr(),xI=gr().CONSTRUCTOR;II({target:"Promise",stat:!0,forced:xI},{reject:function(e){var t=EI.f(this),r=t.reject;return r(e),t.promise}})});var ho=f((yw,gh)=>{"use strict";var PI=rt(),kI=De(),wI=vr();gh.exports=function(i,e){if(PI(i),kI(e)&&e.constructor===i)return e;var t=wI.f(i),r=t.resolve;return r(e),t.promise}});var Th=f(()=>{"use strict";var AI=Ve(),RI=dt(),vh=Qe(),LI=Gt(),yh=gr().CONSTRUCTOR,$I=ho(),MI=RI("Promise"),CI=vh&&!yh;AI({target:"Promise",stat:!0,forced:vh||yh},{resolve:function(e){return $I(CI&&this===MI?LI:this,e)}})});var Ih=f(()=>{"use strict";nh();hh();fh();bh();Sh();Th()});var kh=f(()=>{"use strict";var DI=Ve(),OI=Qe(),Ja=Gt(),VI=we(),xh=dt(),Ph=te(),BI=On(),Eh=ho(),_I=fr(),fo=Ja&&Ja.prototype,NI=!!Ja&&VI(function(){fo.finally.call({then:function(){}},function(){})});DI({target:"Promise",proto:!0,real:!0,forced:NI},{finally:function(i){var e=BI(this,xh("Promise")),t=Ph(i);return this.then(t?function(r){return Eh(e,i()).then(function(){return r})}:i,t?function(r){return Eh(e,i()).then(function(){throw r})}:i)}});!OI&&Ph(Ja)&&(mo=xh("Promise").prototype.finally,fo.finally!==mo&&_I(fo,"finally",mo,{unsafe:!0}));var mo});var Xa=f((ww,wh)=>{"use strict";var FI=dt();wh.exports=FI});var Rh=f((Aw,Ah)=>{"use strict";Od();Ih();kh();var qI=Xa();Ah.exports=qI("Promise","finally")});var $h=f((Rw,Lh)=>{"use strict";var UI=Rh();Lh.exports=UI});var Za=f((Lw,Mh)=>{"use strict";var HI=$h();Mh.exports=HI});var Uh=f(()=>{"use strict";var JI=Ve(),XI=Wr(),ZI=Ra(),eE=Aa(),tE=Ms();JI({target:"Array",proto:!0},{at:function(e){var t=XI(this),r=ZI(t),a=eE(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});tE("at")});var jh=f((AA,Hh)=>{"use strict";Uh();var rE=Xa();Hh.exports=rE("Array","at")});var Yh=f((RA,Gh)=>{"use strict";var iE=jh();Gh.exports=iE});var di=f((LA,Wh)=>{"use strict";var aE=Yh();Wh.exports=aE});var Em=f(()=>{"use strict"});var xm=f(()=>{"use strict"});var km=f((gM,Pm)=>{"use strict";var qE=De(),UE=or(),HE=fe(),jE=HE("match");Pm.exports=function(i){var e;return qE(i)&&((e=i[jE])!==void 0?!!e:UE(i)==="RegExp")}});var Am=f((vM,wm)=>{"use strict";var GE=Zr(),YE=String;wm.exports=function(i){if(GE(i)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return YE(i)}});var Lm=f((yM,Rm)=>{"use strict";var WE=rt();Rm.exports=function(){var i=WE(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 Cm=f((TM,Mm)=>{"use strict";var QE=Ae(),zE=ze(),KE=Hr(),JE=Lm(),$m=RegExp.prototype;Mm.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in $m)&&!zE(i,"flags")&&KE($m,i)?QE(JE,i):e}});var Om=f((IM,Dm)=>{"use strict";var _o=Se(),XE=Wr(),ZE=Math.floor,Vo=_o("".charAt),ex=_o("".replace),Bo=_o("".slice),tx=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,rx=/\$([$&'`]|\d{1,2})/g;Dm.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,l=rx;return a!==void 0&&(a=XE(a),l=tx),ex(s,l,function(u,c){var d;switch(Vo(c,0)){case"$":return"$";case"&":return i;case"`":return Bo(e,0,t);case"'":return Bo(e,n);case"<":d=a[Bo(c,1,-1)];break;default:var p=+c;if(p===0)return u;if(p>o){var m=ZE(p/10);return m===0?u:m<=o?r[m-1]===void 0?Vo(c,1):r[m-1]+Vo(c,1):u}d=r[p-1]}return d===void 0?"":d})}});var _m=f(()=>{"use strict";var ix=Ve(),ax=Ae(),Fo=Se(),Vm=qr(),sx=te(),nx=ur(),ox=km(),Mr=Am(),ux=Gr(),lx=Cm(),cx=Om(),dx=fe(),px=Qe(),hx=dx("replace"),mx=TypeError,No=Fo("".indexOf),fx=Fo("".replace),Bm=Fo("".slice),bx=Math.max;ix({target:"String",proto:!0},{replaceAll:function(e,t){var r=Vm(this),a,s,n,o,l,u,c,d,p,m,b=0,g="";if(!nx(e)){if(a=ox(e),a&&(s=Mr(Vm(lx(e))),!~No(s,"g")))throw new mx("`.replaceAll` does not allow non-global regexes");if(n=ux(e,hx),n)return ax(n,e,r,t);if(px&&a)return fx(Mr(r),e,t)}for(o=Mr(r),l=Mr(e),u=sx(t),u||(t=Mr(t)),c=l.length,d=bx(1,c),p=No(o,l);p!==-1;)m=u?Mr(t(l,p,o)):cx(l,o,p,[],void 0,t),g+=Bm(o,b,p)+m,b=p+c,p=p+d>o.length?-1:No(o,l,p+d);return b<o.length&&(g+=Bm(o,b)),g}})});var Fm=f((PM,Nm)=>{"use strict";Em();xm();_m();var Sx=Xa();Nm.exports=Sx("String","replaceAll")});var Um=f((kM,qm)=>{"use strict";var gx=Fm();qm.exports=gx});var jm=f((wM,Hm)=>{"use strict";var vx=Um();Hm.exports=vx});var Dx={};Cf(Dx,{ChromecastState:()=>Nr,HttpConnectionType:()=>ba,Observable:()=>ot.Observable,PlaybackState:()=>me,Player:()=>ua,SDK_VERSION:()=>Cx,Subject:()=>ot.Subject,Subscription:()=>ot.Subscription,Surface:()=>Sa,VERSION:()=>Rs,ValueSubject:()=>ot.ValueSubject,VideoFormat:()=>ct,VideoQuality:()=>ot.VideoQuality});module.exports=Df(Dx);var Rs="2.0.108-dev.377c6d18.0";var me=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(me||{}),ct=(x=>(x.MPEG="MPEG",x.DASH="DASH",x.DASH_SEP="DASH_SEP",x.DASH_SEP_VK="DASH_SEP",x.DASH_WEBM="DASH_WEBM",x.DASH_WEBM_AV1="DASH_WEBM_AV1",x.DASH_STREAMS="DASH_STREAMS",x.DASH_WEBM_VK="DASH_WEBM",x.DASH_ONDEMAND="DASH_ONDEMAND",x.DASH_ONDEMAND_VK="DASH_ONDEMAND",x.DASH_LIVE="DASH_LIVE",x.DASH_LIVE_CMAF="DASH_LIVE_CMAF",x.DASH_LIVE_WEBM="DASH_LIVE_WEBM",x.HLS="HLS",x.HLS_ONDEMAND="HLS_ONDEMAND",x.HLS_JS="HLS",x.HLS_LIVE="HLS_LIVE",x.HLS_LIVE_CMAF="HLS_LIVE_CMAF",x.WEB_RTC_LIVE="WEB_RTC_LIVE",x))(ct||{});var Nr=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(Nr||{}),ba=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(ba||{});var Sa=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Sa||{});var N=require("@vkontakte/videoplayer-shared");var au=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 ga=class{constructor(e){this.connection$=new N.ValueSubject(void 0);this.castState$=new N.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new N.Subject;this.realCastState$=new N.ValueSubject("NOT_AVAILABLE");this.subscription=new N.Subscription;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=(0,N.isNonNullable)(window.chrome?.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},a||au("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:N.ErrorCategory.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(){(0,N.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,N.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,N.isNullable)(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((0,N.fromEvent)(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(0,N.assertNever)(a.sessionState)}})).add((0,N.merge)((0,N.fromEvent)(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,N.tap)(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),(0,N.map)(a=>a.castState)),(0,N.observableFrom)([r.getCastState()])).pipe((0,N.filterChanged)(),(0,N.map)(Of),(0,N.tap)(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=(0,N.isNonNullable)(this.connection$.getValue());if(s&&!n){let o=r.getCurrentSession();(0,N.assertNonNullable)(o);let l=o.getCastDevice(),u=o.getMediaSession()?.media.contentId;((0,N.isNullable)(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"?(0,N.isNonNullable)(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:N.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},Of=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(0,N.assertNever)(i)}};var pf=Ye(Ln(),1);var Vh=Ye(Za(),1);var bo=require("@vkontakte/videoplayer-shared");var de=(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:(0,bo.assertNever)(t)}return i},So=(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:(0,bo.assertNever)(e)}};var k=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};var it=require("@vkontakte/videoplayer-shared"),q=class{constructor(e){this.transitionStarted$=new it.Subject;this.transitionEnded$=new it.Subject;this.transitionUpdated$=new it.Subject;this.forceChanged$=new it.Subject;this.stateChangeStarted$=(0,it.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,it.merge)(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||(0,it.isNonNullable)(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}};var Ch=require("@vkontakte/videoplayer-shared"),Dh=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(0,Ch.assertNever)(i)}};var L=require("@vkontakte/videoplayer-shared");var jI=5,GI=5,YI=500,Oh=7e3,ci=class{constructor(e){this.subscription=new L.Subscription;this.loadMediaTimeoutSubscription=new L.Subscription;this.videoState=new q("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:(0,L.assertNever)(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:(0,L.assertNever)(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:(0,L.assertNever)(e)}break}default:(0,L.assertNever)(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Dh(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 L.Subscription;this.subscription.add(e),this.subscription.add((0,L.merge)(this.videoState.stateChangeStarted$.pipe((0,L.map)(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe((0,L.map)(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 L.Subject;e.add(a.pipe((0,L.debounce)(YI)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,L.fromEvent)(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)>jI)&&a.next(o),s=o})),e.add((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,L.fromEvent)(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<GI&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(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:(0,L.assertNever)(n)}}),t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=(0,L.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,L.observableFrom)(["init"])).pipe((0,L.debounce)(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"),k(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),k(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"),k(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),k(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&k(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];(0,L.assertNonNullable)(u);let c=(0,L.getHighestQuality)(Object.keys(u));(0,L.assertNonNullable)(c);let d=u[c];(0,L.assertNonNullable)(d),r=d,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let u=t[e];(0,L.assertNonNullable)(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];(0,L.assertNonNullable)(u),r=u.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let u=t[e];(0,L.assertNonNullable)(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];(0,L.assertNonNullable)(u),r=de(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:L.ErrorCategory.VIDEO_PIPELINE,message:u,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,L.assertNever)(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(0,L.isNonNullable)(o)&&(n.metadata.title=o),(0,L.isNonNullable)(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((0,L.timeout)(Oh).subscribe(()=>s(`timeout(${Oh})`)))});(0,Vh.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:L.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var To=require("@vkontakte/videoplayer-shared");var Bh=require("@vkontakte/videoplayer-shared"),_h=i=>{try{i.pause(),i.playbackRate=0,(0,Bh.clearVideoElement)(i),i.remove()}catch(e){console.error(e)}};var es=require("@vkontakte/videoplayer-shared"),go=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 go,yo=window.WeakMap?new WeakMap:new Map,WI=(i,e=20)=>{let t=0;return(0,es.fromEvent)(i,"ratechange").subscribe(r=>{t++,t>=e&&(i.currentTime=i.currentTime,t=0)})},ge=(i,{audioVideoSyncRate:e})=>{let t=i.querySelector("video"),r=!!t;t?(0,To.clearVideoElement)(t):(t=document.createElement("video"),i.appendChild(t)),vo.set(t,r);let a=new es.Subscription;return a.add(WI(t,e)),yo.set(t,a),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},ve=i=>{yo.get(i)?.unsubscribe(),yo.delete(i);let t=vo.get(i);vo.delete(i),t?(0,To.clearVideoElement)(i):_h(i)};var $=require("@vkontakte/videoplayer-shared");var $t=require("@vkontakte/videoplayer-shared"),ts=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),l=(0,$t.isNullable)(a),u=new $t.Subscription;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},at=(i,e,t)=>ts(e,()=>i.loop,r=>{(0,$t.isNonNullable)(r)&&(i.loop=r)},{onError:t}),ye=(i,e,t,r)=>ts(e,()=>({muted:i.muted,volume:i.volume}),a=>{(0,$t.isNonNullable)(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}),Be=(i,e,t,r)=>ts(e,()=>i.playbackRate,a=>{(0,$t.isNonNullable)(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),Mt=ts;var QI=i=>["__",i.language,i.label].join("|"),zI=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},Io=class i{constructor(){this.available$=new $.Subject;this.current$=new $.ValueSubject(void 0);this.error$=new $.Subject;this.subscription=new $.Subscription;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:$.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(Mt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{(0,$.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,$.isNonNullable)(s)&&(0,$.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},l)=>o===n[l].id),changed$:this.available$.pipe((0,$.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(Mt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{(0,$.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,$.isNonNullable)(s)&&(0,$.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},l)=>o===n[l].id),changed$:this.available$.pipe((0,$.map)(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(Mt(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:a})),this.subscription.add(Mt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,$.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,$.fromEvent)(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add((0,$.merge)((0,$.fromEvent)(e,"addtrack"),(0,$.fromEvent)(e,"removetrack"),(0,$.observableFrom)(["init"])).pipe((0,$.map)(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),(0,$.filterChanged)((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add((0,$.merge)((0,$.fromEvent)(e,"change"),(0,$.observableFrom)(["init"])).pipe((0,$.map)(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),(0,$.map)(r=>r&&this.htmlTextTrackToITextTrack(r).id),(0,$.filterChanged)()).subscribe(this.current$));let t=r=>this.applyCueSettings(r.target?.activeCues??null);this.subscription.add((0,$.fromEvent)(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((0,$.fromEvent)(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;(0,$.isNonNullable)(t.align)&&(a.align=t.align),(0,$.isNonNullable)(t.position)&&(a.position=t.position),(0,$.isNonNullable)(t.size)&&(a.size=t.size),(0,$.isNonNullable)(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,$.assertNonNullable)(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:QI(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){(0,$.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,$.isNullable)(e)||!zI(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){(0,$.assertNonNullable)(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){(0,$.assertNonNullable)(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)}},_e=Io;var ft=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 Nh=i=>{let e=i;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Eo=i=>{let e=Nh(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},Fh=i=>{let e=Nh(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};var C=require("@vkontakte/videoplayer-shared");var KI=3,qh=(i,e,t=KI)=>{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 Te=i=>{let e=x=>(0,C.fromEvent)(i,x).pipe((0,C.mapTo)(void 0)),r=(0,C.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(x=>(0,C.fromEvent)(i,x))).pipe((0,C.map)(x=>x.type==="ended"?i.readyState<2:i.readyState<3),(0,C.filterChanged)()),a=(0,C.merge)((0,C.fromEvent)(i,"progress"),(0,C.fromEvent)(i,"timeupdate")).pipe((0,C.map)(()=>qh(i.buffered,i.currentTime))),s=C.clientChecker.isSafari?(0,C.combine)({play:e("play").pipe((0,C.once)()),playing:e("playing")}).pipe((0,C.mapTo)(void 0)):e("playing"),n=(0,C.fromEvent)(i,"volumechange").pipe((0,C.map)(()=>({muted:i.muted,volume:i.volume}))),o=(0,C.fromEvent)(i,"ratechange").pipe((0,C.map)(()=>i.playbackRate)),l=(0,C.fromEvent)(i,"error").pipe((0,C.filter)(()=>!!(i.error||i.played.length)),(0,C.map)(()=>{let x=i.error;return{id:x?`MediaError#${x.code}`:"HtmlVideoError",category:C.ErrorCategory.VIDEO_PIPELINE,message:x?x.message:"Error event from HTML video element",thrown:i.error??void 0}})),u=(0,C.fromEvent)(i,"timeupdate").pipe((0,C.map)(()=>i.currentTime)),c=new C.Subject,d=.3,p;u.subscribe(x=>{i.loop&&(0,C.isNonNullable)(p)&&(0,C.isNonNullable)(x)&&p>=i.duration-d&&x<=d&&c.next(p),p=x});let m=e("pause").pipe((0,C.filter)(()=>!i.error&&p!==i.duration)),b=(0,C.fromEvent)(i,"enterpictureinpicture"),g=(0,C.fromEvent)(i,"leavepictureinpicture"),y=new C.ValueSubject(Fh(i));b.subscribe(()=>y.next(!0)),g.subscribe(()=>y.next(!1));let I=new C.ValueSubject(Eo(i));return(0,C.fromEvent)(i,"fullscreenchange").pipe((0,C.map)(()=>Eo(i))).subscribe(I),{playing$:s,pause$:m,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$:(0,C.fromEvent)(i,"durationchange").pipe((0,C.map)(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:n,playbackRateState$:o,inPiP$:y,inFullscreen$:I}};var bt=require("@vkontakte/videoplayer-shared"),Ct=i=>{switch(i){case"mobile":return bt.VideoQuality.Q_144P;case"lowest":return bt.VideoQuality.Q_240P;case"low":return bt.VideoQuality.Q_360P;case"sd":case"medium":return bt.VideoQuality.Q_480P;case"hd":case"high":return bt.VideoQuality.Q_720P;case"fullhd":case"full":return bt.VideoQuality.Q_1080P;case"quadhd":case"quad":return bt.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return bt.VideoQuality.Q_2160P}};var Po=Ye(di(),1),H=require("@vkontakte/videoplayer-shared");var xo=!1,St={},Qh=i=>{xo=i},zh=()=>{St={}},Kh=i=>{i(St)},pi=(i,e)=>{xo&&(St.meta=St.meta??{},St.meta[i]=e)},be=class{constructor(e){this.name=e}next(e){if(!xo)return;St.series=St.series??{};let t=St.series[this.name]??[];t.push([Date.now(),e]),St.series[this.name]=t}};var sE=new be("best_bitrate"),nE=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t,rs=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,H.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},oE='Assertion "ABR Tracks is empty array" failed',uE=(i,{container:e,throughput:t,tuning:r,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:l,history:u,droppedVideoMaxQualityLimit:c,abrLogger:d})=>{(0,H.assertNotEmptyArray)(i,oE);let p=r.usePixelRatio?window.devicePixelRatio??1:1,m=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*p*r.containerSizeFactor,height:e.height*p*r.containerSizeFactor},b=m&&(0,H.videoSizeToQuality)(m),g=r.considerPlaybackRate&&(0,H.isNonNullable)(o)?o:1,y=i.filter(A=>!(0,H.isInvariantQuality)(A.quality)).sort((A,Q)=>(0,H.isHigher)(A.quality,Q.quality)?-1:1),I=(0,Po.default)(y,-1)?.quality,D=(0,Po.default)(y,0)?.quality,x=(0,H.isNullable)(a)||(0,H.isNonNullable)(a.min)&&(0,H.isNonNullable)(a.max)&&(0,H.isLower)(a.max,a.min)||(0,H.isNonNullable)(a.min)&&D&&(0,H.isHigher)(a.min,D)||(0,H.isNonNullable)(a.max)&&I&&(0,H.isLower)(a.max,I),T=g*nE(n??.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),P={},w=y.filter(A=>(b?(0,H.isLower)(A.quality,b):!0)?((0,H.isNonNullable)(t)&&isFinite(t)&&(0,H.isNonNullable)(A.bitrate)?t-s>=A.bitrate*T:!0)?r.lazyQualitySwitch&&(0,H.isNonNullable)(r.minBufferToSwitchUp)&&l&&!(0,H.isInvariantQuality)(l.quality)&&(n??0)<r.minBufferToSwitchUp&&(0,H.isHigher)(A.quality,l.quality)?(P[A.quality]="Buffer",!1):!!c&&(0,H.isHigherOrEqual)(A.quality,c)?(P[A.quality]="DroppedFramesLimit",!1):x||((0,H.isNullable)(a.max)||(0,H.isLowerOrEqual)(A.quality,a.max))&&((0,H.isNullable)(a.min)||(0,H.isHigherOrEqual)(A.quality,a.min))?!0:(P[A.quality]="FitsQualityLimits",!1):(P[A.quality]="FitsThroughput",!1):(P[A.quality]="FitsContainer",!1))[0];w&&w.bitrate&&sE.next(w.bitrate);let _=w??y[Math.ceil((y.length-1)/2)]??i[0];_.quality!==u?.last?.quality&&d({message:`
7
- [available tracks]
8
- ${i.map(A=>`{ id: ${A.id}, quality: ${A.quality}, bitrate: ${A.bitrate} }`).join(`
6
+ "use strict";var Cm=Object.create;var na=Object.defineProperty;var Dm=Object.getOwnPropertyDescriptor;var Bm=Object.getOwnPropertyNames;var Vm=Object.getPrototypeOf,Om=Object.prototype.hasOwnProperty;var m=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),_m=(i,e)=>{for(var t in e)na(i,t,{get:e[t],enumerable:!0})},Jo=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Bm(e))!Om.call(i,a)&&a!==t&&na(i,a,{get:()=>e[a],enumerable:!(r=Dm(e,a))||r.enumerable});return i};var Fe=(i,e,t)=>(t=i!=null?Cm(Vm(i)):{},Jo(e||!i||!i.__esModule?na(t,"default",{value:i,enumerable:!0}):t,i)),Nm=i=>Jo(na({},"__esModule",{value:!0}),i);var Pe=m((Kx,Zo)=>{"use strict";Zo.exports=function(i){try{return!!i()}catch{return!0}}});var Mr=m((Jx,eu)=>{"use strict";var qm=Pe();eu.exports=!qm(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var be=m((Xx,iu)=>{"use strict";var tu=Mr(),ru=Function.prototype,Ps=ru.call,Um=tu&&ru.bind.bind(Ps,Ps);iu.exports=tu?Um:function(i){return function(){return Ps.apply(i,arguments)}}});var Zt=m((Zx,su)=>{"use strict";var au=be(),Hm=au({}.toString),jm=au("".slice);su.exports=function(i){return jm(Hm(i),8,-1)}});var ou=m((eP,nu)=>{"use strict";var Gm=be(),Wm=Pe(),Ym=Zt(),As=Object,Qm=Gm("".split);nu.exports=Wm(function(){return!As("z").propertyIsEnumerable(0)})?function(i){return Ym(i)==="String"?Qm(i,""):As(i)}:As});var er=m((tP,uu)=>{"use strict";uu.exports=function(i){return i==null}});var Cr=m((rP,cu)=>{"use strict";var zm=er(),Km=TypeError;cu.exports=function(i){if(zm(i))throw new Km("Can't call method on "+i);return i}});var tr=m((iP,lu)=>{"use strict";var Jm=ou(),Xm=Cr();lu.exports=function(i){return Jm(Xm(i))}});var ks=m((aP,du)=>{"use strict";du.exports=function(){}});var Lt=m((sP,pu)=>{"use strict";pu.exports={}});var ie=m((ws,hu)=>{"use strict";var Dr=function(i){return i&&i.Math===Math&&i};hu.exports=Dr(typeof globalThis=="object"&&globalThis)||Dr(typeof window=="object"&&window)||Dr(typeof self=="object"&&self)||Dr(typeof global=="object"&&global)||Dr(typeof ws=="object"&&ws)||function(){return this}()||Function("return this")()});var re=m((nP,fu)=>{"use strict";var Rs=typeof document=="object"&&document.all;fu.exports=typeof Rs>"u"&&Rs!==void 0?function(i){return typeof i=="function"||i===Rs}:function(i){return typeof i=="function"}});var gu=m((oP,bu)=>{"use strict";var Zm=ie(),eb=re(),mu=Zm.WeakMap;bu.exports=eb(mu)&&/native code/.test(String(mu))});var $e=m((uP,Su)=>{"use strict";var tb=re();Su.exports=function(i){return typeof i=="object"?i!==null:tb(i)}});var Le=m((cP,vu)=>{"use strict";var rb=Pe();vu.exports=!rb(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var la=m((lP,Tu)=>{"use strict";var ib=ie(),yu=$e(),$s=ib.document,ab=yu($s)&&yu($s.createElement);Tu.exports=function(i){return ab?$s.createElement(i):{}}});var Ls=m((dP,Iu)=>{"use strict";var sb=Le(),nb=Pe(),ob=la();Iu.exports=!sb&&!nb(function(){return Object.defineProperty(ob("div"),"a",{get:function(){return 7}}).a!==7})});var Ms=m((pP,Eu)=>{"use strict";var ub=Le(),cb=Pe();Eu.exports=ub&&cb(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var ze=m((hP,xu)=>{"use strict";var lb=$e(),db=String,pb=TypeError;xu.exports=function(i){if(lb(i))return i;throw new pb(db(i)+" is not an object")}});var Ae=m((fP,Pu)=>{"use strict";var hb=Mr(),da=Function.prototype.call;Pu.exports=hb?da.bind(da):function(){return da.apply(da,arguments)}});var pa=m((mP,Au)=>{"use strict";Au.exports={}});var rt=m((bP,wu)=>{"use strict";var Cs=pa(),Ds=ie(),fb=re(),ku=function(i){return fb(i)?i:void 0};wu.exports=function(i,e){return arguments.length<2?ku(Cs[i])||ku(Ds[i]):Cs[i]&&Cs[i][e]||Ds[i]&&Ds[i][e]}});var Br=m((gP,Ru)=>{"use strict";var mb=be();Ru.exports=mb({}.isPrototypeOf)});var rr=m((SP,Mu)=>{"use strict";var bb=ie(),$u=bb.navigator,Lu=$u&&$u.userAgent;Mu.exports=Lu?String(Lu):""});var Vs=m((vP,_u)=>{"use strict";var Ou=ie(),Bs=rr(),Cu=Ou.process,Du=Ou.Deno,Bu=Cu&&Cu.versions||Du&&Du.version,Vu=Bu&&Bu.v8,qe,ha;Vu&&(qe=Vu.split("."),ha=qe[0]>0&&qe[0]<4?1:+(qe[0]+qe[1]));!ha&&Bs&&(qe=Bs.match(/Edge\/(\d+)/),(!qe||qe[1]>=74)&&(qe=Bs.match(/Chrome\/(\d+)/),qe&&(ha=+qe[1])));_u.exports=ha});var Os=m((yP,Fu)=>{"use strict";var Nu=Vs(),gb=Pe(),Sb=ie(),vb=Sb.String;Fu.exports=!!Object.getOwnPropertySymbols&&!gb(function(){var i=Symbol("symbol detection");return!vb(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&Nu&&Nu<41})});var _s=m((TP,qu)=>{"use strict";var yb=Os();qu.exports=yb&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Ns=m((IP,Uu)=>{"use strict";var Tb=rt(),Ib=re(),Eb=Br(),xb=_s(),Pb=Object;Uu.exports=xb?function(i){return typeof i=="symbol"}:function(i){var e=Tb("Symbol");return Ib(e)&&Eb(e.prototype,Pb(i))}});var Vr=m((EP,Hu)=>{"use strict";var Ab=String;Hu.exports=function(i){try{return Ab(i)}catch{return"Object"}}});var it=m((xP,ju)=>{"use strict";var kb=re(),wb=Vr(),Rb=TypeError;ju.exports=function(i){if(kb(i))return i;throw new Rb(wb(i)+" is not a function")}});var Or=m((PP,Gu)=>{"use strict";var $b=it(),Lb=er();Gu.exports=function(i,e){var t=i[e];return Lb(t)?void 0:$b(t)}});var Yu=m((AP,Wu)=>{"use strict";var Fs=Ae(),qs=re(),Us=$e(),Mb=TypeError;Wu.exports=function(i,e){var t,r;if(e==="string"&&qs(t=i.toString)&&!Us(r=Fs(t,i))||qs(t=i.valueOf)&&!Us(r=Fs(t,i))||e!=="string"&&qs(t=i.toString)&&!Us(r=Fs(t,i)))return r;throw new Mb("Can't convert object to primitive value")}});var Ue=m((kP,Qu)=>{"use strict";Qu.exports=!0});var Ju=m((wP,Ku)=>{"use strict";var zu=ie(),Cb=Object.defineProperty;Ku.exports=function(i,e){try{Cb(zu,i,{value:e,configurable:!0,writable:!0})}catch{zu[i]=e}return e}});var _r=m((RP,ec)=>{"use strict";var Db=Ue(),Bb=ie(),Vb=Ju(),Xu="__core-js_shared__",Zu=ec.exports=Bb[Xu]||Vb(Xu,{});(Zu.versions||(Zu.versions=[])).push({version:"3.38.0",mode:Db?"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 Hs=m(($P,rc)=>{"use strict";var tc=_r();rc.exports=function(i,e){return tc[i]||(tc[i]=e||{})}});var Nr=m((LP,ic)=>{"use strict";var Ob=Cr(),_b=Object;ic.exports=function(i){return _b(Ob(i))}});var He=m((MP,ac)=>{"use strict";var Nb=be(),Fb=Nr(),qb=Nb({}.hasOwnProperty);ac.exports=Object.hasOwn||function(e,t){return qb(Fb(e),t)}});var js=m((CP,sc)=>{"use strict";var Ub=be(),Hb=0,jb=Math.random(),Gb=Ub(1 .toString);sc.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+Gb(++Hb+jb,36)}});var pe=m((DP,oc)=>{"use strict";var Wb=ie(),Yb=Hs(),nc=He(),Qb=js(),zb=Os(),Kb=_s(),ir=Wb.Symbol,Gs=Yb("wks"),Jb=Kb?ir.for||ir:ir&&ir.withoutSetter||Qb;oc.exports=function(i){return nc(Gs,i)||(Gs[i]=zb&&nc(ir,i)?ir[i]:Jb("Symbol."+i)),Gs[i]}});var dc=m((BP,lc)=>{"use strict";var Xb=Ae(),uc=$e(),cc=Ns(),Zb=Or(),eg=Yu(),tg=pe(),rg=TypeError,ig=tg("toPrimitive");lc.exports=function(i,e){if(!uc(i)||cc(i))return i;var t=Zb(i,ig),r;if(t){if(e===void 0&&(e="default"),r=Xb(t,i,e),!uc(r)||cc(r))return r;throw new rg("Can't convert object to primitive value")}return e===void 0&&(e="number"),eg(i,e)}});var Ws=m((VP,pc)=>{"use strict";var ag=dc(),sg=Ns();pc.exports=function(i){var e=ag(i,"string");return sg(e)?e:e+""}});var Mt=m(fc=>{"use strict";var ng=Le(),og=Ls(),ug=Ms(),fa=ze(),hc=Ws(),cg=TypeError,Ys=Object.defineProperty,lg=Object.getOwnPropertyDescriptor,Qs="enumerable",zs="configurable",Ks="writable";fc.f=ng?ug?function(e,t,r){if(fa(e),t=hc(t),fa(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Ks in r&&!r[Ks]){var a=lg(e,t);a&&a[Ks]&&(e[t]=r.value,r={configurable:zs in r?r[zs]:a[zs],enumerable:Qs in r?r[Qs]:a[Qs],writable:!1})}return Ys(e,t,r)}:Ys:function(e,t,r){if(fa(e),t=hc(t),fa(r),og)try{return Ys(e,t,r)}catch{}if("get"in r||"set"in r)throw new cg("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Fr=m((_P,mc)=>{"use strict";mc.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var ar=m((NP,bc)=>{"use strict";var dg=Le(),pg=Mt(),hg=Fr();bc.exports=dg?function(i,e,t){return pg.f(i,e,hg(1,t))}:function(i,e,t){return i[e]=t,i}});var ma=m((FP,Sc)=>{"use strict";var fg=Hs(),mg=js(),gc=fg("keys");Sc.exports=function(i){return gc[i]||(gc[i]=mg(i))}});var ba=m((qP,vc)=>{"use strict";vc.exports={}});var en=m((UP,Ic)=>{"use strict";var bg=gu(),Tc=ie(),gg=$e(),Sg=ar(),Js=He(),Xs=_r(),vg=ma(),yg=ba(),yc="Object already initialized",Zs=Tc.TypeError,Tg=Tc.WeakMap,ga,qr,Sa,Ig=function(i){return Sa(i)?qr(i):ga(i,{})},Eg=function(i){return function(e){var t;if(!gg(e)||(t=qr(e)).type!==i)throw new Zs("Incompatible receiver, "+i+" required");return t}};bg||Xs.state?(je=Xs.state||(Xs.state=new Tg),je.get=je.get,je.has=je.has,je.set=je.set,ga=function(i,e){if(je.has(i))throw new Zs(yc);return e.facade=i,je.set(i,e),e},qr=function(i){return je.get(i)||{}},Sa=function(i){return je.has(i)}):(Ct=vg("state"),yg[Ct]=!0,ga=function(i,e){if(Js(i,Ct))throw new Zs(yc);return e.facade=i,Sg(i,Ct,e),e},qr=function(i){return Js(i,Ct)?i[Ct]:{}},Sa=function(i){return Js(i,Ct)});var je,Ct;Ic.exports={set:ga,get:qr,has:Sa,enforce:Ig,getterFor:Eg}});var tn=m((HP,Ac)=>{"use strict";var xg=Mr(),Pc=Function.prototype,Ec=Pc.apply,xc=Pc.call;Ac.exports=typeof Reflect=="object"&&Reflect.apply||(xg?xc.bind(Ec):function(){return xc.apply(Ec,arguments)})});var rn=m((jP,kc)=>{"use strict";var Pg=Zt(),Ag=be();kc.exports=function(i){if(Pg(i)==="Function")return Ag(i)}});var Lc=m($c=>{"use strict";var wc={}.propertyIsEnumerable,Rc=Object.getOwnPropertyDescriptor,kg=Rc&&!wc.call({1:2},1);$c.f=kg?function(e){var t=Rc(this,e);return!!t&&t.enumerable}:wc});var Dc=m(Cc=>{"use strict";var wg=Le(),Rg=Ae(),$g=Lc(),Lg=Fr(),Mg=tr(),Cg=Ws(),Dg=He(),Bg=Ls(),Mc=Object.getOwnPropertyDescriptor;Cc.f=wg?Mc:function(e,t){if(e=Mg(e),t=Cg(t),Bg)try{return Mc(e,t)}catch{}if(Dg(e,t))return Lg(!Rg($g.f,e,t),e[t])}});var an=m((YP,Bc)=>{"use strict";var Vg=Pe(),Og=re(),_g=/#|\.prototype\./,Ur=function(i,e){var t=Fg[Ng(i)];return t===Ug?!0:t===qg?!1:Og(e)?Vg(e):!!e},Ng=Ur.normalize=function(i){return String(i).replace(_g,".").toLowerCase()},Fg=Ur.data={},qg=Ur.NATIVE="N",Ug=Ur.POLYFILL="P";Bc.exports=Ur});var Hr=m((QP,Oc)=>{"use strict";var Vc=rn(),Hg=it(),jg=Mr(),Gg=Vc(Vc.bind);Oc.exports=function(i,e){return Hg(i),e===void 0?i:jg?Gg(i,e):function(){return i.apply(e,arguments)}}});var Me=m((zP,Nc)=>{"use strict";var jr=ie(),Wg=tn(),Yg=rn(),Qg=re(),zg=Dc().f,Kg=an(),sr=pa(),Jg=Hr(),nr=ar(),_c=He();_r();var Xg=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 Wg(i,this,arguments)};return e.prototype=i.prototype,e};Nc.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?jr:a?jr[t]:jr[t]&&jr[t].prototype,o=r?sr:sr[t]||nr(sr,t,{})[t],c=o.prototype,u,d,l,p,f,b,g,y,E;for(p in e)u=Kg(r?p:t+(a?".":"#")+p,i.forced),d=!u&&n&&_c(n,p),b=o[p],d&&(i.dontCallGetSet?(E=zg(n,p),g=E&&E.value):g=n[p]),f=d&&g?g:e[p],!(!u&&!s&&typeof b==typeof f)&&(i.bind&&d?y=Jg(f,jr):i.wrap&&d?y=Xg(f):s&&Qg(f)?y=Yg(f):y=f,(i.sham||f&&f.sham||b&&b.sham)&&nr(y,"sham",!0),nr(o,p,y),s&&(l=t+"Prototype",_c(sr,l)||nr(sr,l,{}),nr(sr[l],p,f),i.real&&c&&(u||!c[p])&&nr(c,p,f)))}});var Uc=m((KP,qc)=>{"use strict";var sn=Le(),Zg=He(),Fc=Function.prototype,eS=sn&&Object.getOwnPropertyDescriptor,nn=Zg(Fc,"name"),tS=nn&&function(){}.name==="something",rS=nn&&(!sn||sn&&eS(Fc,"name").configurable);qc.exports={EXISTS:nn,PROPER:tS,CONFIGURABLE:rS}});var jc=m((JP,Hc)=>{"use strict";var iS=Math.ceil,aS=Math.floor;Hc.exports=Math.trunc||function(e){var t=+e;return(t>0?aS:iS)(t)}});var va=m((XP,Gc)=>{"use strict";var sS=jc();Gc.exports=function(i){var e=+i;return e!==e||e===0?0:sS(e)}});var Yc=m((ZP,Wc)=>{"use strict";var nS=va(),oS=Math.max,uS=Math.min;Wc.exports=function(i,e){var t=nS(i);return t<0?oS(t+e,0):uS(t,e)}});var zc=m((eA,Qc)=>{"use strict";var cS=va(),lS=Math.min;Qc.exports=function(i){var e=cS(i);return e>0?lS(e,9007199254740991):0}});var ya=m((tA,Kc)=>{"use strict";var dS=zc();Kc.exports=function(i){return dS(i.length)}});var Zc=m((rA,Xc)=>{"use strict";var pS=tr(),hS=Yc(),fS=ya(),Jc=function(i){return function(e,t,r){var a=pS(e),s=fS(a);if(s===0)return!i&&-1;var n=hS(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}};Xc.exports={includes:Jc(!0),indexOf:Jc(!1)}});var rl=m((iA,tl)=>{"use strict";var mS=be(),on=He(),bS=tr(),gS=Zc().indexOf,SS=ba(),el=mS([].push);tl.exports=function(i,e){var t=bS(i),r=0,a=[],s;for(s in t)!on(SS,s)&&on(t,s)&&el(a,s);for(;e.length>r;)on(t,s=e[r++])&&(~gS(a,s)||el(a,s));return a}});var un=m((aA,il)=>{"use strict";il.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var sl=m((sA,al)=>{"use strict";var vS=rl(),yS=un();al.exports=Object.keys||function(e){return vS(e,yS)}});var ol=m(nl=>{"use strict";var TS=Le(),IS=Ms(),ES=Mt(),xS=ze(),PS=tr(),AS=sl();nl.f=TS&&!IS?Object.defineProperties:function(e,t){xS(e);for(var r=PS(t),a=AS(t),s=a.length,n=0,o;s>n;)ES.f(e,o=a[n++],r[o]);return e}});var cn=m((oA,ul)=>{"use strict";var kS=rt();ul.exports=kS("document","documentElement")});var hn=m((uA,ml)=>{"use strict";var wS=ze(),RS=ol(),cl=un(),$S=ba(),LS=cn(),MS=la(),CS=ma(),ll=">",dl="<",dn="prototype",pn="script",hl=CS("IE_PROTO"),ln=function(){},fl=function(i){return dl+pn+ll+i+dl+"/"+pn+ll},pl=function(i){i.write(fl("")),i.close();var e=i.parentWindow.Object;return i=null,e},DS=function(){var i=MS("iframe"),e="java"+pn+":",t;return i.style.display="none",LS.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(fl("document.F=Object")),t.close(),t.F},Ta,Ia=function(){try{Ta=new ActiveXObject("htmlfile")}catch{}Ia=typeof document<"u"?document.domain&&Ta?pl(Ta):DS():pl(Ta);for(var i=cl.length;i--;)delete Ia[dn][cl[i]];return Ia()};$S[hl]=!0;ml.exports=Object.create||function(e,t){var r;return e!==null?(ln[dn]=wS(e),r=new ln,ln[dn]=null,r[hl]=e):r=Ia(),t===void 0?r:RS.f(r,t)}});var gl=m((cA,bl)=>{"use strict";var BS=Pe();bl.exports=!BS(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var mn=m((lA,vl)=>{"use strict";var VS=He(),OS=re(),_S=Nr(),NS=ma(),FS=gl(),Sl=NS("IE_PROTO"),fn=Object,qS=fn.prototype;vl.exports=FS?fn.getPrototypeOf:function(i){var e=_S(i);if(VS(e,Sl))return e[Sl];var t=e.constructor;return OS(t)&&e instanceof t?t.prototype:e instanceof fn?qS:null}});var or=m((dA,yl)=>{"use strict";var US=ar();yl.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:US(i,e,t),i}});var vn=m((pA,El)=>{"use strict";var HS=Pe(),jS=re(),GS=$e(),WS=hn(),Tl=mn(),YS=or(),QS=pe(),zS=Ue(),Sn=QS("iterator"),Il=!1,at,bn,gn;[].keys&&(gn=[].keys(),"next"in gn?(bn=Tl(Tl(gn)),bn!==Object.prototype&&(at=bn)):Il=!0);var KS=!GS(at)||HS(function(){var i={};return at[Sn].call(i)!==i});KS?at={}:zS&&(at=WS(at));jS(at[Sn])||YS(at,Sn,function(){return this});El.exports={IteratorPrototype:at,BUGGY_SAFARI_ITERATORS:Il}});var Ea=m((hA,Pl)=>{"use strict";var JS=pe(),XS=JS("toStringTag"),xl={};xl[XS]="z";Pl.exports=String(xl)==="[object z]"});var Gr=m((fA,Al)=>{"use strict";var ZS=Ea(),ev=re(),xa=Zt(),tv=pe(),rv=tv("toStringTag"),iv=Object,av=xa(function(){return arguments}())==="Arguments",sv=function(i,e){try{return i[e]}catch{}};Al.exports=ZS?xa:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=sv(e=iv(i),rv))=="string"?t:av?xa(e):(r=xa(e))==="Object"&&ev(e.callee)?"Arguments":r}});var wl=m((mA,kl)=>{"use strict";var nv=Ea(),ov=Gr();kl.exports=nv?{}.toString:function(){return"[object "+ov(this)+"]"}});var Wr=m((bA,$l)=>{"use strict";var uv=Ea(),cv=Mt().f,lv=ar(),dv=He(),pv=wl(),hv=pe(),Rl=hv("toStringTag");$l.exports=function(i,e,t,r){var a=t?i:i&&i.prototype;a&&(dv(a,Rl)||cv(a,Rl,{configurable:!0,value:e}),r&&!uv&&lv(a,"toString",pv))}});var Ml=m((gA,Ll)=>{"use strict";var fv=vn().IteratorPrototype,mv=hn(),bv=Fr(),gv=Wr(),Sv=Lt(),vv=function(){return this};Ll.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=mv(fv,{next:bv(+!r,t)}),gv(i,a,!1,!0),Sv[a]=vv,i}});var Dl=m((SA,Cl)=>{"use strict";var yv=be(),Tv=it();Cl.exports=function(i,e,t){try{return yv(Tv(Object.getOwnPropertyDescriptor(i,e)[t]))}catch{}}});var Vl=m((vA,Bl)=>{"use strict";var Iv=$e();Bl.exports=function(i){return Iv(i)||i===null}});var _l=m((yA,Ol)=>{"use strict";var Ev=Vl(),xv=String,Pv=TypeError;Ol.exports=function(i){if(Ev(i))return i;throw new Pv("Can't set "+xv(i)+" as a prototype")}});var yn=m((TA,Nl)=>{"use strict";var Av=Dl(),kv=$e(),wv=Cr(),Rv=_l();Nl.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=Av(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch{}return function(a,s){return wv(a),Rv(s),kv(a)&&(i?t(a,s):a.__proto__=s),a}}():void 0)});var Kl=m((IA,zl)=>{"use strict";var $v=Me(),Lv=Ae(),Pa=Ue(),Yl=Uc(),Mv=re(),Cv=Ml(),Fl=mn(),ql=yn(),Dv=Wr(),Bv=ar(),Tn=or(),Vv=pe(),Ul=Lt(),Ql=vn(),Ov=Yl.PROPER,_v=Yl.CONFIGURABLE,Hl=Ql.IteratorPrototype,Aa=Ql.BUGGY_SAFARI_ITERATORS,Yr=Vv("iterator"),jl="keys",Qr="values",Gl="entries",Wl=function(){return this};zl.exports=function(i,e,t,r,a,s,n){Cv(t,e,r);var o=function(E){if(E===a&&p)return p;if(!Aa&&E&&E in d)return d[E];switch(E){case jl:return function(){return new t(this,E)};case Qr:return function(){return new t(this,E)};case Gl:return function(){return new t(this,E)}}return function(){return new t(this)}},c=e+" Iterator",u=!1,d=i.prototype,l=d[Yr]||d["@@iterator"]||a&&d[a],p=!Aa&&l||o(a),f=e==="Array"&&d.entries||l,b,g,y;if(f&&(b=Fl(f.call(new i)),b!==Object.prototype&&b.next&&(!Pa&&Fl(b)!==Hl&&(ql?ql(b,Hl):Mv(b[Yr])||Tn(b,Yr,Wl)),Dv(b,c,!0,!0),Pa&&(Ul[c]=Wl))),Ov&&a===Qr&&l&&l.name!==Qr&&(!Pa&&_v?Bv(d,"name",Qr):(u=!0,p=function(){return Lv(l,this)})),a)if(g={values:o(Qr),keys:s?p:o(jl),entries:o(Gl)},n)for(y in g)(Aa||u||!(y in d))&&Tn(d,y,g[y]);else $v({target:e,proto:!0,forced:Aa||u},g);return(!Pa||n)&&d[Yr]!==p&&Tn(d,Yr,p,{name:a}),Ul[e]=p,g}});var Xl=m((EA,Jl)=>{"use strict";Jl.exports=function(i,e){return{value:i,done:e}}});var En=m((xA,id)=>{"use strict";var Nv=tr(),In=ks(),Zl=Lt(),td=en(),Fv=Mt().f,qv=Kl(),ka=Xl(),Uv=Ue(),Hv=Le(),rd="Array Iterator",jv=td.set,Gv=td.getterFor(rd);id.exports=qv(Array,"Array",function(i,e){jv(this,{type:rd,target:Nv(i),index:0,kind:e})},function(){var i=Gv(this),e=i.target,t=i.index++;if(!e||t>=e.length)return i.target=void 0,ka(void 0,!0);switch(i.kind){case"keys":return ka(t,!1);case"values":return ka(e[t],!1)}return ka([t,e[t]],!1)},"values");var ed=Zl.Arguments=Zl.Array;In("keys");In("values");In("entries");if(!Uv&&Hv&&ed.name!=="values")try{Fv(ed,"name",{value:"values"})}catch{}});var sd=m((PA,ad)=>{"use strict";var Wv=pe(),Yv=Lt(),Qv=Wv("iterator"),zv=Array.prototype;ad.exports=function(i){return i!==void 0&&(Yv.Array===i||zv[Qv]===i)}});var xn=m((AA,od)=>{"use strict";var Kv=Gr(),nd=Or(),Jv=er(),Xv=Lt(),Zv=pe(),ey=Zv("iterator");od.exports=function(i){if(!Jv(i))return nd(i,ey)||nd(i,"@@iterator")||Xv[Kv(i)]}});var cd=m((kA,ud)=>{"use strict";var ty=Ae(),ry=it(),iy=ze(),ay=Vr(),sy=xn(),ny=TypeError;ud.exports=function(i,e){var t=arguments.length<2?sy(i):e;if(ry(t))return iy(ty(t,i));throw new ny(ay(i)+" is not iterable")}});var pd=m((wA,dd)=>{"use strict";var oy=Ae(),ld=ze(),uy=Or();dd.exports=function(i,e,t){var r,a;ld(i);try{if(r=uy(i,"return"),!r){if(e==="throw")throw t;return t}r=oy(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return ld(r),t}});var Ra=m((RA,bd)=>{"use strict";var cy=Hr(),ly=Ae(),dy=ze(),py=Vr(),hy=sd(),fy=ya(),hd=Br(),my=cd(),by=xn(),fd=pd(),gy=TypeError,wa=function(i,e){this.stopped=i,this.result=e},md=wa.prototype;bd.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=cy(e,r),u,d,l,p,f,b,g,y=function(M){return u&&fd(u,"normal",M),new wa(!0,M)},E=function(M){return a?(dy(M),o?c(M[0],M[1],y):c(M[0],M[1])):o?c(M,y):c(M)};if(s)u=i.iterator;else if(n)u=i;else{if(d=by(i),!d)throw new gy(py(i)+" is not iterable");if(hy(d)){for(l=0,p=fy(i);p>l;l++)if(f=E(i[l]),f&&hd(md,f))return f;return new wa(!1)}u=my(i,d)}for(b=s?i.next:u.next;!(g=ly(b,u)).done;){try{f=E(g.value)}catch(M){fd(u,"throw",M)}if(typeof f=="object"&&f&&hd(md,f))return f}return new wa(!1)}});var Sd=m(($A,gd)=>{"use strict";var Sy=Le(),vy=Mt(),yy=Fr();gd.exports=function(i,e,t){Sy?vy.f(i,e,yy(0,t)):i[e]=t}});var vd=m(()=>{"use strict";var Ty=Me(),Iy=Ra(),Ey=Sd();Ty({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Iy(e,function(r,a){Ey(t,r,a)},{AS_ENTRIES:!0}),t}})});var Td=m((CA,yd)=>{"use strict";En();vd();var xy=pa();yd.exports=xy.Object.fromEntries});var Ed=m((DA,Id)=>{"use strict";Id.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 Pd=m(()=>{"use strict";En();var Py=Ed(),Ay=ie(),ky=Wr(),xd=Lt();for($a in Py)ky(Ay[$a],$a),xd[$a]=xd.Array;var $a});var kd=m((OA,Ad)=>{"use strict";var wy=Td();Pd();Ad.exports=wy});var Pn=m((_A,wd)=>{"use strict";var Ry=kd();wd.exports=Ry});var Rd=m(()=>{"use strict"});var An=m((qA,$d)=>{"use strict";var zr=ie(),$y=rr(),Ly=Zt(),La=function(i){return $y.slice(0,i.length)===i};$d.exports=function(){return La("Bun/")?"BUN":La("Cloudflare-Workers")?"CLOUDFLARE":La("Deno/")?"DENO":La("Node.js/")?"NODE":zr.Bun&&typeof Bun.version=="string"?"BUN":zr.Deno&&typeof Deno.version=="object"?"DENO":Ly(zr.process)==="process"?"NODE":zr.window&&zr.document?"BROWSER":"REST"}()});var Ma=m((UA,Ld)=>{"use strict";var My=An();Ld.exports=My==="NODE"});var Cd=m((HA,Md)=>{"use strict";var Cy=Mt();Md.exports=function(i,e,t){return Cy.f(i,e,t)}});var Vd=m((jA,Bd)=>{"use strict";var Dy=rt(),By=Cd(),Vy=pe(),Oy=Le(),Dd=Vy("species");Bd.exports=function(i){var e=Dy(i);Oy&&e&&!e[Dd]&&By(e,Dd,{configurable:!0,get:function(){return this}})}});var _d=m((GA,Od)=>{"use strict";var _y=Br(),Ny=TypeError;Od.exports=function(i,e){if(_y(e,i))return i;throw new Ny("Incorrect invocation")}});var wn=m((WA,Nd)=>{"use strict";var Fy=be(),qy=re(),kn=_r(),Uy=Fy(Function.toString);qy(kn.inspectSource)||(kn.inspectSource=function(i){return Uy(i)});Nd.exports=kn.inspectSource});var Gd=m((YA,jd)=>{"use strict";var Hy=be(),jy=Pe(),Fd=re(),Gy=Gr(),Wy=rt(),Yy=wn(),qd=function(){},Ud=Wy("Reflect","construct"),Rn=/^\s*(?:class|function)\b/,Qy=Hy(Rn.exec),zy=!Rn.test(qd),Kr=function(e){if(!Fd(e))return!1;try{return Ud(qd,[],e),!0}catch{return!1}},Hd=function(e){if(!Fd(e))return!1;switch(Gy(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return zy||!!Qy(Rn,Yy(e))}catch{return!0}};Hd.sham=!0;jd.exports=!Ud||jy(function(){var i;return Kr(Kr.call)||!Kr(Object)||!Kr(function(){i=!0})||i})?Hd:Kr});var Yd=m((QA,Wd)=>{"use strict";var Ky=Gd(),Jy=Vr(),Xy=TypeError;Wd.exports=function(i){if(Ky(i))return i;throw new Xy(Jy(i)+" is not a constructor")}});var $n=m((zA,zd)=>{"use strict";var Qd=ze(),Zy=Yd(),eT=er(),tT=pe(),rT=tT("species");zd.exports=function(i,e){var t=Qd(i).constructor,r;return t===void 0||eT(r=Qd(t)[rT])?e:Zy(r)}});var Jd=m((KA,Kd)=>{"use strict";var iT=be();Kd.exports=iT([].slice)});var Zd=m((JA,Xd)=>{"use strict";var aT=TypeError;Xd.exports=function(i,e){if(i<e)throw new aT("Not enough arguments");return i}});var Ln=m((XA,ep)=>{"use strict";var sT=rr();ep.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(sT)});var Fn=m((ZA,cp)=>{"use strict";var ke=ie(),nT=tn(),oT=Hr(),tp=re(),uT=He(),up=Pe(),rp=cn(),cT=Jd(),ip=la(),lT=Zd(),dT=Ln(),pT=Ma(),On=ke.setImmediate,_n=ke.clearImmediate,hT=ke.process,Mn=ke.Dispatch,fT=ke.Function,ap=ke.MessageChannel,mT=ke.String,Cn=0,Jr={},sp="onreadystatechange",Xr,Dt,Dn,Bn;up(function(){Xr=ke.location});var Nn=function(i){if(uT(Jr,i)){var e=Jr[i];delete Jr[i],e()}},Vn=function(i){return function(){Nn(i)}},np=function(i){Nn(i.data)},op=function(i){ke.postMessage(mT(i),Xr.protocol+"//"+Xr.host)};(!On||!_n)&&(On=function(e){lT(arguments.length,1);var t=tp(e)?e:fT(e),r=cT(arguments,1);return Jr[++Cn]=function(){nT(t,void 0,r)},Dt(Cn),Cn},_n=function(e){delete Jr[e]},pT?Dt=function(i){hT.nextTick(Vn(i))}:Mn&&Mn.now?Dt=function(i){Mn.now(Vn(i))}:ap&&!dT?(Dn=new ap,Bn=Dn.port2,Dn.port1.onmessage=np,Dt=oT(Bn.postMessage,Bn)):ke.addEventListener&&tp(ke.postMessage)&&!ke.importScripts&&Xr&&Xr.protocol!=="file:"&&!up(op)?(Dt=op,ke.addEventListener("message",np,!1)):sp in ip("script")?Dt=function(i){rp.appendChild(ip("script"))[sp]=function(){rp.removeChild(this),Nn(i)}}:Dt=function(i){setTimeout(Vn(i),0)});cp.exports={set:On,clear:_n}});var pp=m((ek,dp)=>{"use strict";var lp=ie(),bT=Le(),gT=Object.getOwnPropertyDescriptor;dp.exports=function(i){if(!bT)return lp[i];var e=gT(lp,i);return e&&e.value}});var qn=m((tk,fp)=>{"use strict";var hp=function(){this.head=null,this.tail=null};hp.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}}};fp.exports=hp});var bp=m((rk,mp)=>{"use strict";var ST=rr();mp.exports=/ipad|iphone|ipod/i.test(ST)&&typeof Pebble<"u"});var Sp=m((ik,gp)=>{"use strict";var vT=rr();gp.exports=/web0s(?!.*chrome)/i.test(vT)});var Pp=m((ak,xp)=>{"use strict";var cr=ie(),yT=pp(),vp=Hr(),Un=Fn().set,TT=qn(),IT=Ln(),ET=bp(),xT=Sp(),Hn=Ma(),yp=cr.MutationObserver||cr.WebKitMutationObserver,Tp=cr.document,Ip=cr.process,Ca=cr.Promise,Wn=yT("queueMicrotask"),ur,jn,Gn,Da,Ep;Wn||(Zr=new TT,ei=function(){var i,e;for(Hn&&(i=Ip.domain)&&i.exit();e=Zr.get();)try{e()}catch(t){throw Zr.head&&ur(),t}i&&i.enter()},!IT&&!Hn&&!xT&&yp&&Tp?(jn=!0,Gn=Tp.createTextNode(""),new yp(ei).observe(Gn,{characterData:!0}),ur=function(){Gn.data=jn=!jn}):!ET&&Ca&&Ca.resolve?(Da=Ca.resolve(void 0),Da.constructor=Ca,Ep=vp(Da.then,Da),ur=function(){Ep(ei)}):Hn?ur=function(){Ip.nextTick(ei)}:(Un=vp(Un,cr),ur=function(){Un(ei)}),Wn=function(i){Zr.head||ur(),Zr.add(i)});var Zr,ei;xp.exports=Wn});var kp=m((sk,Ap)=>{"use strict";Ap.exports=function(i,e){try{arguments.length===1?console.error(i):console.error(i,e)}catch{}}});var Ba=m((nk,wp)=>{"use strict";wp.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var Bt=m((ok,Rp)=>{"use strict";var PT=ie();Rp.exports=PT.Promise});var lr=m((uk,Cp)=>{"use strict";var AT=ie(),ti=Bt(),kT=re(),wT=an(),RT=wn(),$T=pe(),$p=An(),LT=Ue(),Yn=Vs(),Lp=ti&&ti.prototype,MT=$T("species"),Qn=!1,Mp=kT(AT.PromiseRejectionEvent),CT=wT("Promise",function(){var i=RT(ti),e=i!==String(ti);if(!e&&Yn===66||LT&&!(Lp.catch&&Lp.finally))return!0;if(!Yn||Yn<51||!/native code/.test(i)){var t=new ti(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[MT]=r,Qn=t.then(function(){})instanceof r,!Qn)return!0}return!e&&($p==="BROWSER"||$p==="DENO")&&!Mp});Cp.exports={CONSTRUCTOR:CT,REJECTION_EVENT:Mp,SUBCLASSING:Qn}});var dr=m((ck,Bp)=>{"use strict";var Dp=it(),DT=TypeError,BT=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw new DT("Bad Promise constructor");e=r,t=a}),this.resolve=Dp(e),this.reject=Dp(t)};Bp.exports.f=function(i){return new BT(i)}});var eh=m(()=>{"use strict";var VT=Me(),OT=Ue(),Na=Ma(),yt=ie(),mr=Ae(),Vp=or(),Op=yn(),_T=Wr(),NT=Vd(),FT=it(),_a=re(),qT=$e(),UT=_d(),HT=$n(),Up=Fn().set,Zn=Pp(),jT=kp(),GT=Ba(),WT=qn(),Hp=en(),Fa=Bt(),eo=lr(),jp=dr(),qa="Promise",Gp=eo.CONSTRUCTOR,YT=eo.REJECTION_EVENT,QT=eo.SUBCLASSING,zn=Hp.getterFor(qa),zT=Hp.set,pr=Fa&&Fa.prototype,Vt=Fa,Va=pr,Wp=yt.TypeError,Kn=yt.document,to=yt.process,Jn=jp.f,KT=Jn,JT=!!(Kn&&Kn.createEvent&&yt.dispatchEvent),Yp="unhandledrejection",XT="rejectionhandled",_p=0,Qp=1,ZT=2,ro=1,zp=2,Oa,Np,eI,Fp,Kp=function(i){var e;return qT(i)&&_a(e=i.then)?e:!1},Jp=function(i,e){var t=e.value,r=e.state===Qp,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,c,u,d;try{a?(r||(e.rejection===zp&&rI(e),e.rejection=ro),a===!0?c=t:(o&&o.enter(),c=a(t),o&&(o.exit(),d=!0)),c===i.promise?n(new Wp("Promise-chain cycle")):(u=Kp(c))?mr(u,c,s,n):s(c)):n(t)}catch(l){o&&!d&&o.exit(),n(l)}},Xp=function(i,e){i.notified||(i.notified=!0,Zn(function(){for(var t=i.reactions,r;r=t.get();)Jp(r,i);i.notified=!1,e&&!i.rejection&&tI(i)}))},Zp=function(i,e,t){var r,a;JT?(r=Kn.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),yt.dispatchEvent(r)):r={promise:e,reason:t},!YT&&(a=yt["on"+i])?a(r):i===Yp&&jT("Unhandled promise rejection",t)},tI=function(i){mr(Up,yt,function(){var e=i.facade,t=i.value,r=qp(i),a;if(r&&(a=GT(function(){Na?to.emit("unhandledRejection",t,e):Zp(Yp,e,t)}),i.rejection=Na||qp(i)?zp:ro,a.error))throw a.value})},qp=function(i){return i.rejection!==ro&&!i.parent},rI=function(i){mr(Up,yt,function(){var e=i.facade;Na?to.emit("rejectionHandled",e):Zp(XT,e,i.value)})},hr=function(i,e,t){return function(r){i(e,r,t)}},fr=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=ZT,Xp(i,!0))},Xn=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw new Wp("Promise can't be resolved itself");var r=Kp(e);r?Zn(function(){var a={done:!1};try{mr(r,e,hr(Xn,a,i),hr(fr,a,i))}catch(s){fr(a,s,i)}}):(i.value=e,i.state=Qp,Xp(i,!1))}catch(a){fr({done:!1},a,i)}}};if(Gp&&(Vt=function(e){UT(this,Va),FT(e),mr(Oa,this);var t=zn(this);try{e(hr(Xn,t),hr(fr,t))}catch(r){fr(t,r)}},Va=Vt.prototype,Oa=function(e){zT(this,{type:qa,done:!1,notified:!1,parent:!1,reactions:new WT,rejection:!1,state:_p,value:void 0})},Oa.prototype=Vp(Va,"then",function(e,t){var r=zn(this),a=Jn(HT(this,Vt));return r.parent=!0,a.ok=_a(e)?e:!0,a.fail=_a(t)&&t,a.domain=Na?to.domain:void 0,r.state===_p?r.reactions.add(a):Zn(function(){Jp(a,r)}),a.promise}),Np=function(){var i=new Oa,e=zn(i);this.promise=i,this.resolve=hr(Xn,e),this.reject=hr(fr,e)},jp.f=Jn=function(i){return i===Vt||i===eI?new Np(i):KT(i)},!OT&&_a(Fa)&&pr!==Object.prototype)){Fp=pr.then,QT||Vp(pr,"then",function(e,t){var r=this;return new Vt(function(a,s){mr(Fp,r,a,s)}).then(e,t)},{unsafe:!0});try{delete pr.constructor}catch{}Op&&Op(pr,Va)}VT({global:!0,constructor:!0,wrap:!0,forced:Gp},{Promise:Vt});_T(Vt,qa,!1,!0);NT(qa)});var sh=m((pk,ah)=>{"use strict";var iI=pe(),rh=iI("iterator"),ih=!1;try{th=0,io={next:function(){return{done:!!th++}},return:function(){ih=!0}},io[rh]=function(){return this},Array.from(io,function(){throw 2})}catch{}var th,io;ah.exports=function(i,e){try{if(!e&&!ih)return!1}catch{return!1}var t=!1;try{var r={};r[rh]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch{}return t}});var ao=m((hk,nh)=>{"use strict";var aI=Bt(),sI=sh(),nI=lr().CONSTRUCTOR;nh.exports=nI||!sI(function(i){aI.all(i).then(void 0,function(){})})});var oh=m(()=>{"use strict";var oI=Me(),uI=Ae(),cI=it(),lI=dr(),dI=Ba(),pI=Ra(),hI=ao();oI({target:"Promise",stat:!0,forced:hI},{all:function(e){var t=this,r=lI.f(t),a=r.resolve,s=r.reject,n=dI(function(){var o=cI(t.resolve),c=[],u=0,d=1;pI(e,function(l){var p=u++,f=!1;d++,uI(o,t,l).then(function(b){f||(f=!0,c[p]=b,--d||a(c))},s)}),--d||a(c)});return n.error&&s(n.value),r.promise}})});var ch=m(()=>{"use strict";var fI=Me(),mI=Ue(),bI=lr().CONSTRUCTOR,no=Bt(),gI=rt(),SI=re(),vI=or(),uh=no&&no.prototype;fI({target:"Promise",proto:!0,forced:bI,real:!0},{catch:function(i){return this.then(void 0,i)}});!mI&&SI(no)&&(so=gI("Promise").prototype.catch,uh.catch!==so&&vI(uh,"catch",so,{unsafe:!0}));var so});var lh=m(()=>{"use strict";var yI=Me(),TI=Ae(),II=it(),EI=dr(),xI=Ba(),PI=Ra(),AI=ao();yI({target:"Promise",stat:!0,forced:AI},{race:function(e){var t=this,r=EI.f(t),a=r.reject,s=xI(function(){var n=II(t.resolve);PI(e,function(o){TI(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var dh=m(()=>{"use strict";var kI=Me(),wI=dr(),RI=lr().CONSTRUCTOR;kI({target:"Promise",stat:!0,forced:RI},{reject:function(e){var t=wI.f(this),r=t.reject;return r(e),t.promise}})});var oo=m((Ik,ph)=>{"use strict";var $I=ze(),LI=$e(),MI=dr();ph.exports=function(i,e){if($I(i),LI(e)&&e.constructor===i)return e;var t=MI.f(i),r=t.resolve;return r(e),t.promise}});var mh=m(()=>{"use strict";var CI=Me(),DI=rt(),hh=Ue(),BI=Bt(),fh=lr().CONSTRUCTOR,VI=oo(),OI=DI("Promise"),_I=hh&&!fh;CI({target:"Promise",stat:!0,forced:hh||fh},{resolve:function(e){return VI(_I&&this===OI?BI:this,e)}})});var bh=m(()=>{"use strict";eh();oh();ch();lh();dh();mh()});var yh=m(()=>{"use strict";var NI=Me(),FI=Ue(),Ua=Bt(),qI=Pe(),Sh=rt(),vh=re(),UI=$n(),gh=oo(),HI=or(),co=Ua&&Ua.prototype,jI=!!Ua&&qI(function(){co.finally.call({then:function(){}},function(){})});NI({target:"Promise",proto:!0,real:!0,forced:jI},{finally:function(i){var e=UI(this,Sh("Promise")),t=vh(i);return this.then(t?function(r){return gh(e,i()).then(function(){return r})}:i,t?function(r){return gh(e,i()).then(function(){throw r})}:i)}});!FI&&vh(Ua)&&(uo=Sh("Promise").prototype.finally,co.finally!==uo&&HI(co,"finally",uo,{unsafe:!0}));var uo});var Ha=m((Rk,Th)=>{"use strict";var GI=rt();Th.exports=GI});var Eh=m(($k,Ih)=>{"use strict";Rd();bh();yh();var WI=Ha();Ih.exports=WI("Promise","finally")});var Ph=m((Lk,xh)=>{"use strict";var YI=Eh();xh.exports=YI});var ja=m((Mk,Ah)=>{"use strict";var QI=Ph();Ah.exports=QI});var Vh=m(()=>{"use strict";var rE=Me(),iE=Nr(),aE=ya(),sE=va(),nE=ks();rE({target:"Array",proto:!0},{at:function(e){var t=iE(this),r=aE(t),a=sE(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});nE("at")});var _h=m(($w,Oh)=>{"use strict";Vh();var oE=Ha();Oh.exports=oE("Array","at")});var Fh=m((Lw,Nh)=>{"use strict";var uE=_h();Nh.exports=uE});var ii=m((Mw,qh)=>{"use strict";var cE=Fh();qh.exports=cE});var Ef=m(()=>{"use strict"});var xf=m(()=>{"use strict"});var Af=m((yM,Pf)=>{"use strict";var HE=$e(),jE=Zt(),GE=pe(),WE=GE("match");Pf.exports=function(i){var e;return HE(i)&&((e=i[WE])!==void 0?!!e:jE(i)==="RegExp")}});var wf=m((TM,kf)=>{"use strict";var YE=Gr(),QE=String;kf.exports=function(i){if(YE(i)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return QE(i)}});var $f=m((IM,Rf)=>{"use strict";var zE=ze();Rf.exports=function(){var i=zE(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 Cf=m((EM,Mf)=>{"use strict";var KE=Ae(),JE=He(),XE=Br(),ZE=$f(),Lf=RegExp.prototype;Mf.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in Lf)&&!JE(i,"flags")&&XE(Lf,i)?KE(ZE,i):e}});var Bf=m((xM,Df)=>{"use strict";var Co=be(),ex=Nr(),tx=Math.floor,Lo=Co("".charAt),rx=Co("".replace),Mo=Co("".slice),ix=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,ax=/\$([$&'`]|\d{1,2})/g;Df.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,c=ax;return a!==void 0&&(a=ex(a),c=ix),rx(s,c,function(u,d){var l;switch(Lo(d,0)){case"$":return"$";case"&":return i;case"`":return Mo(e,0,t);case"'":return Mo(e,n);case"<":l=a[Mo(d,1,-1)];break;default:var p=+d;if(p===0)return u;if(p>o){var f=tx(p/10);return f===0?u:f<=o?r[f-1]===void 0?Lo(d,1):r[f-1]+Lo(d,1):u}l=r[p-1]}return l===void 0?"":l})}});var _f=m(()=>{"use strict";var sx=Me(),nx=Ae(),Bo=be(),Vf=Cr(),ox=re(),ux=er(),cx=Af(),xr=wf(),lx=Or(),dx=Cf(),px=Bf(),hx=pe(),fx=Ue(),mx=hx("replace"),bx=TypeError,Do=Bo("".indexOf),gx=Bo("".replace),Of=Bo("".slice),Sx=Math.max;sx({target:"String",proto:!0},{replaceAll:function(e,t){var r=Vf(this),a,s,n,o,c,u,d,l,p,f,b=0,g="";if(!ux(e)){if(a=cx(e),a&&(s=xr(Vf(dx(e))),!~Do(s,"g")))throw new bx("`.replaceAll` does not allow non-global regexes");if(n=lx(e,mx),n)return nx(n,e,r,t);if(fx&&a)return gx(xr(r),e,t)}for(o=xr(r),c=xr(e),u=ox(t),u||(t=xr(t)),d=c.length,l=Sx(1,d),p=Do(o,c);p!==-1;)f=u?xr(t(c,p,o)):px(c,o,p,[],void 0,t),g+=Of(o,b,p)+f,b=p+d,p=p+l>o.length?-1:Do(o,c,p+l);return b<o.length&&(g+=Of(o,b)),g}})});var Ff=m((kM,Nf)=>{"use strict";Ef();xf();_f();var vx=Ha();Nf.exports=vx("String","replaceAll")});var Uf=m((wM,qf)=>{"use strict";var yx=Ff();qf.exports=yx});var jf=m((RM,Hf)=>{"use strict";var Tx=Uf();Hf.exports=Tx});var Vx={};_m(Vx,{ChromecastState:()=>Lr,HttpConnectionType:()=>oa,Observable:()=>et.Observable,PlaybackState:()=>de,Player:()=>ea,SDK_VERSION:()=>Bx,Subject:()=>et.Subject,Subscription:()=>et.Subscription,Surface:()=>ua,VERSION:()=>xs,ValueSubject:()=>et.ValueSubject,VideoFormat:()=>tt,VideoQuality:()=>et.VideoQuality});module.exports=Nm(Vx);var xs="2.0.108-dev.3ff897f5.0";var de=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(de||{}),tt=(x=>(x.MPEG="MPEG",x.DASH="DASH",x.DASH_SEP="DASH_SEP",x.DASH_SEP_VK="DASH_SEP",x.DASH_WEBM="DASH_WEBM",x.DASH_WEBM_AV1="DASH_WEBM_AV1",x.DASH_STREAMS="DASH_STREAMS",x.DASH_WEBM_VK="DASH_WEBM",x.DASH_ONDEMAND="DASH_ONDEMAND",x.DASH_ONDEMAND_VK="DASH_ONDEMAND",x.DASH_LIVE="DASH_LIVE",x.DASH_LIVE_CMAF="DASH_LIVE_CMAF",x.DASH_LIVE_WEBM="DASH_LIVE_WEBM",x.HLS="HLS",x.HLS_ONDEMAND="HLS_ONDEMAND",x.HLS_JS="HLS",x.HLS_LIVE="HLS_LIVE",x.HLS_LIVE_CMAF="HLS_LIVE_CMAF",x.WEB_RTC_LIVE="WEB_RTC_LIVE",x))(tt||{});var Lr=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(Lr||{}),oa=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(oa||{});var ua=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(ua||{});var F=require("@vkontakte/videoplayer-shared");var Xo=i=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",i),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var ca=class{constructor(e){this.connection$=new F.ValueSubject(void 0);this.castState$=new F.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new F.Subject;this.realCastState$=new F.ValueSubject("NOT_AVAILABLE");this.subscription=new F.Subscription;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=(0,F.isNonNullable)(window.chrome?.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},a||Xo("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:F.ErrorCategory.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(){(0,F.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,F.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,F.isNullable)(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((0,F.fromEvent)(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(0,F.assertNever)(a.sessionState)}})).add((0,F.merge)((0,F.fromEvent)(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,F.tap)(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),(0,F.map)(a=>a.castState)),(0,F.observableFrom)([r.getCastState()])).pipe((0,F.filterChanged)(),(0,F.map)(Fm),(0,F.tap)(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=(0,F.isNonNullable)(this.connection$.getValue());if(s&&!n){let o=r.getCurrentSession();(0,F.assertNonNullable)(o);let c=o.getCastDevice(),u=o.getMediaSession()?.media?.contentId;((0,F.isNullable)(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"?(0,F.isNonNullable)(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:F.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},Fm=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(0,F.assertNever)(i)}};var hm=Fe(Pn(),1);var $h=Fe(ja(),1);var lo=require("@vkontakte/videoplayer-shared");var le=(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:(0,lo.assertNever)(t)}return i},po=(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:(0,lo.assertNever)(e)}};var A=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};var Ke=require("@vkontakte/videoplayer-shared"),H=class{constructor(e){this.transitionStarted$=new Ke.Subject;this.transitionEnded$=new Ke.Subject;this.transitionUpdated$=new Ke.Subject;this.forceChanged$=new Ke.Subject;this.stateChangeStarted$=(0,Ke.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,Ke.merge)(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||(0,Ke.isNonNullable)(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}};var kh=require("@vkontakte/videoplayer-shared"),wh=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(0,kh.assertNever)(i)}};var R=require("@vkontakte/videoplayer-shared");var zI=5,KI=5,JI=500,Rh=7e3,ri=class{constructor(e){this.subscription=new R.Subscription;this.loadMediaTimeoutSubscription=new R.Subscription;this.videoState=new H("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:(0,R.assertNever)(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:(0,R.assertNever)(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:(0,R.assertNever)(e)}break}default:(0,R.assertNever)(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(wh(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 R.Subscription;this.subscription.add(e),this.subscription.add((0,R.merge)(this.videoState.stateChangeStarted$.pipe((0,R.map)(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe((0,R.map)(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 R.Subject;e.add(a.pipe((0,R.debounce)(JI)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,R.fromEvent)(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)>zI)&&a.next(o),s=o})),e.add((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,R.fromEvent)(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<KI&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),A(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:(0,R.assertNever)(n)}}),t((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=(0,R.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,R.observableFrom)(["init"])).pipe((0,R.debounce)(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"),A(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),A(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"),A(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),A(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&A(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];(0,R.assertNonNullable)(u);let d=(0,R.getHighestQuality)(Object.keys(u));(0,R.assertNonNullable)(d);let l=u[d];(0,R.assertNonNullable)(l),r=l,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let u=t[e];(0,R.assertNonNullable)(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];(0,R.assertNonNullable)(u),r=u.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let u=t[e];(0,R.assertNonNullable)(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];(0,R.assertNonNullable)(u),r=le(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:R.ErrorCategory.VIDEO_PIPELINE,message:u,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,R.assertNever)(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(0,R.isNonNullable)(o)&&(n.metadata.title=o),(0,R.isNonNullable)(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((0,R.timeout)(Rh).subscribe(()=>s(`timeout(${Rh})`)))});(0,$h.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:R.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var bo=require("@vkontakte/videoplayer-shared");var Lh=require("@vkontakte/videoplayer-shared"),Mh=i=>{try{i.pause(),i.playbackRate=0,(0,Lh.clearVideoElement)(i),i.remove()}catch(e){console.error(e)}};var Ga=require("@vkontakte/videoplayer-shared"),ho=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)}},fo=window.WeakMap?new WeakMap:new ho,mo=window.WeakMap?new WeakMap:new Map,XI=(i,e=20)=>{let t=0;return(0,Ga.fromEvent)(i,"ratechange").subscribe(r=>{t++,t>=e&&(i.currentTime=i.currentTime,t=0)})},ge=(i,{audioVideoSyncRate:e})=>{let t=i.querySelector("video"),r=!!t;t?(0,bo.clearVideoElement)(t):(t=document.createElement("video"),i.appendChild(t)),fo.set(t,r);let a=new Ga.Subscription;return a.add(XI(t,e)),mo.set(t,a),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},Se=i=>{mo.get(i)?.unsubscribe(),mo.delete(i);let t=fo.get(i);fo.delete(i),t?(0,bo.clearVideoElement)(i):Mh(i)};var $=require("@vkontakte/videoplayer-shared");var Tt=require("@vkontakte/videoplayer-shared"),Wa=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),c=(0,Tt.isNullable)(a),u=new Tt.Subscription;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},Je=(i,e,t)=>Wa(e,()=>i.loop,r=>{(0,Tt.isNonNullable)(r)&&(i.loop=r)},{onError:t}),ve=(i,e,t,r)=>Wa(e,()=>({muted:i.muted,volume:i.volume}),a=>{(0,Tt.isNonNullable)(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}),Ce=(i,e,t,r)=>Wa(e,()=>i.playbackRate,a=>{(0,Tt.isNonNullable)(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),It=Wa;var ZI=i=>["__",i.language,i.label].join("|"),eE=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},go=class i{constructor(){this.available$=new $.Subject;this.current$=new $.ValueSubject(void 0);this.error$=new $.Subject;this.subscription=new $.Subscription;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:$.ErrorCategory.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=>{(0,$.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,$.isNonNullable)(s)&&(0,$.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},c)=>o===n[c].id),changed$:this.available$.pipe((0,$.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(It(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{(0,$.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,$.isNonNullable)(s)&&(0,$.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},c)=>o===n[c].id),changed$:this.available$.pipe((0,$.map)(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(){(0,$.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,$.fromEvent)(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add((0,$.merge)((0,$.fromEvent)(e,"addtrack"),(0,$.fromEvent)(e,"removetrack"),(0,$.observableFrom)(["init"])).pipe((0,$.map)(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),(0,$.filterChanged)((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add((0,$.merge)((0,$.fromEvent)(e,"change"),(0,$.observableFrom)(["init"])).pipe((0,$.map)(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),(0,$.map)(r=>r&&this.htmlTextTrackToITextTrack(r).id),(0,$.filterChanged)()).subscribe(this.current$));let t=r=>this.applyCueSettings(r.target?.activeCues??null);this.subscription.add((0,$.fromEvent)(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((0,$.fromEvent)(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;(0,$.isNonNullable)(t.align)&&(a.align=t.align),(0,$.isNonNullable)(t.position)&&(a.position=t.position),(0,$.isNonNullable)(t.size)&&(a.size=t.size),(0,$.isNonNullable)(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,$.assertNonNullable)(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:ZI(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){(0,$.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,$.isNullable)(e)||!eE(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){(0,$.assertNonNullable)(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){(0,$.assertNonNullable)(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},De=go;var nt=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var Ch=i=>{let e=i;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},So=i=>{let e=Ch(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},Dh=i=>{let e=Ch(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};var L=require("@vkontakte/videoplayer-shared");var tE=3,Bh=(i,e,t=tE)=>{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 ye=i=>{let e=x=>(0,L.fromEvent)(i,x).pipe((0,L.mapTo)(void 0)),r=(0,L.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(x=>(0,L.fromEvent)(i,x))).pipe((0,L.map)(x=>x.type==="ended"?i.readyState<2:i.readyState<3),(0,L.filterChanged)()),a=(0,L.merge)((0,L.fromEvent)(i,"progress"),(0,L.fromEvent)(i,"timeupdate")).pipe((0,L.map)(()=>Bh(i.buffered,i.currentTime))),s=L.clientChecker.isSafari?(0,L.combine)({play:e("play").pipe((0,L.once)()),playing:e("playing")}).pipe((0,L.mapTo)(void 0)):e("playing"),n=(0,L.fromEvent)(i,"volumechange").pipe((0,L.map)(()=>({muted:i.muted,volume:i.volume}))),o=(0,L.fromEvent)(i,"ratechange").pipe((0,L.map)(()=>i.playbackRate)),c=(0,L.fromEvent)(i,"error").pipe((0,L.filter)(()=>!!(i.error||i.played.length)),(0,L.map)(()=>{let x=i.error;return{id:x?`MediaError#${x.code}`:"HtmlVideoError",category:L.ErrorCategory.VIDEO_PIPELINE,message:x?x.message:"Error event from HTML video element",thrown:i.error??void 0}})),u=(0,L.fromEvent)(i,"timeupdate").pipe((0,L.map)(()=>i.currentTime)),d=new L.Subject,l=.3,p;u.subscribe(x=>{i.loop&&(0,L.isNonNullable)(p)&&(0,L.isNonNullable)(x)&&p>=i.duration-l&&x<=l&&d.next(p),p=x});let f=e("pause").pipe((0,L.filter)(()=>!i.error&&p!==i.duration)),b=(0,L.fromEvent)(i,"enterpictureinpicture"),g=(0,L.fromEvent)(i,"leavepictureinpicture"),y=new L.ValueSubject(Dh(i));b.subscribe(()=>y.next(!0)),g.subscribe(()=>y.next(!1));let E=new L.ValueSubject(So(i));return(0,L.fromEvent)(i,"fullscreenchange").pipe((0,L.map)(()=>So(i))).subscribe(E),{playing$:s,pause$:f,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$:(0,L.fromEvent)(i,"durationchange").pipe((0,L.map)(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:n,playbackRateState$:o,inPiP$:y,inFullscreen$:E}};var ot=require("@vkontakte/videoplayer-shared"),Et=i=>{switch(i){case"mobile":return ot.VideoQuality.Q_144P;case"lowest":return ot.VideoQuality.Q_240P;case"low":return ot.VideoQuality.Q_360P;case"sd":case"medium":return ot.VideoQuality.Q_480P;case"hd":case"high":return ot.VideoQuality.Q_720P;case"fullhd":case"full":return ot.VideoQuality.Q_1080P;case"quadhd":case"quad":return ot.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return ot.VideoQuality.Q_2160P}};var Ot=Fe(ii(),1),B=require("@vkontakte/videoplayer-shared");var vo=!1,ut={},Uh=i=>{vo=i},Hh=()=>{ut={}},jh=i=>{i(ut)},ai=(i,e)=>{vo&&(ut.meta=ut.meta??{},ut.meta[i]=e)},he=class{constructor(e){this.name=e}next(e){if(!vo)return;ut.series=ut.series??{};let t=ut.series[this.name]??[];t.push([Date.now(),e]),ut.series[this.name]=t}};var lE=new he("best_bitrate"),Wh=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;var yo=i=>(e,t)=>i*(Number(e.bitrate)-Number(t.bitrate)),si=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,B.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Yh='Assertion "ABR Tracks is empty array" failed',Ya=(i,e,t,r)=>{let a=[...e].sort(yo(1)),s=[...t].sort(yo(1)),n=s.filter(c=>(0,B.isNonNullable)(c.bitrate)&&(0,B.isNonNullable)(i.bitrate)?i.bitrate/c.bitrate>r:!0),o=(0,Ot.default)(s,Math.round(s.length*a.indexOf(i)/(a.length+1)))??(0,Ot.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,Ot.default)(n,-1):(0,Ot.default)(s,0)},Gh=i=>"quality"in i,Qh=(i,e,t,r)=>{let a=t&&r&&r.history[t.id]&&(0,B.now)()-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=Gh(s)?"video":"audio",o=Gh(s)?s.quality:s.bitrate;return e({message:`
7
+ [last ${n} selected] ${o}
8
+ `}),s}return r?.recordSwitch(t),t},xt=(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})=>{(0,B.assertNotEmptyArray)(i,Yh);let f=r.usePixelRatio?window.devicePixelRatio??1:1,b=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*f*r.containerSizeFactor,height:e.height*f*r.containerSizeFactor},g=b&&(0,B.videoSizeToQuality)(b),y=r.considerPlaybackRate&&(0,B.isNonNullable)(o)?o:1,E=i.filter(C=>!(0,B.isInvariantQuality)(C.quality)).sort((C,D)=>(0,B.isHigher)(C.quality,D.quality)?-1:1),M=(0,Ot.default)(E,-1)?.quality,x=(0,Ot.default)(E,0)?.quality,T=(0,B.isNullable)(a)||(0,B.isNonNullable)(a.min)&&(0,B.isNonNullable)(a.max)&&(0,B.isLower)(a.max,a.min)||(0,B.isNonNullable)(a.min)&&x&&(0,B.isHigher)(a.min,x)||(0,B.isNonNullable)(a.max)&&M&&(0,B.isLower)(a.max,M),P=y*Wh(n??.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),k={},z=E.filter(C=>{if(!(g?(0,B.isLower)(C.quality,g):!0))return k[C.quality]="FitsContainer",!1;if(!((0,B.isNonNullable)(t)&&isFinite(t)&&(0,B.isNonNullable)(C.bitrate)?t-s>=C.bitrate*P:!0))return k[C.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&(0,B.isNonNullable)(r.minBufferToSwitchUp)&&c&&!(0,B.isInvariantQuality)(c.quality)&&(n??0)<r.minBufferToSwitchUp&&(0,B.isHigher)(C.quality,c.quality))return k[C.quality]="Buffer",!1;if(!!l&&(0,B.isHigherOrEqual)(C.quality,l))return k[C.quality]="DroppedFramesLimit",!1;let fe=T||((0,B.isNullable)(a.max)||(0,B.isLowerOrEqual)(C.quality,a.max))&&((0,B.isNullable)(a.min)||(0,B.isHigherOrEqual)(C.quality,a.min)),w=(0,B.isNonNullable)(d)&&!d?(0,B.isLowerOrEqual)(C.quality,r.backgroundVideoQualityLimit):!0;return!fe||!w?(k[C.quality]="FitsQualityLimits",!1):!0})[0];z&&z.bitrate&&lE.next(z.bitrate);let X=z??E[Math.ceil((E.length-1)/2)]??i[0];return X.quality!==u?.last?.quality&&p({message:`
9
+ [VIDEO TRACKS ABR]
10
+ [available video tracks]
11
+ ${i.map(C=>`{ id: ${C.id}, quality: ${C.quality}, bitrate: ${C.bitrate} }`).join(`
9
12
  `)}
10
13
 
11
14
  [tuning]
12
- ${Object.entries(r??{}).map(([A,Q])=>`${A}: ${Q}`).join(`
15
+ ${Object.entries(r??{}).map(([C,D])=>`${C}: ${D}`).join(`
13
16
  `)}
14
17
 
15
18
  [limit params]
16
- containerQualityLimit: ${b},
19
+ containerQualityLimit: ${g},
17
20
  throughput: ${t},
18
21
  reserve: ${s},
19
22
  playbackRate: ${o},
20
- playbackRateFactor: ${g},
23
+ playbackRateFactor: ${y},
21
24
  forwardBufferHealth: ${n},
22
- bitrateFactor: ${T},
25
+ bitrateFactor: ${P},
23
26
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
24
- droppedVideoMaxQualityLimit: ${c},
25
- limitsAreInvalid: ${x},
27
+ droppedVideoMaxQualityLimit: ${l},
28
+ limitsAreInvalid: ${T},
26
29
  maxQualityLimit: ${a?.max},
27
30
  minQualityLimit: ${a?.min},
28
31
 
29
- [limited tracks]
30
- ${Object.entries(P).map(([A,Q])=>`${A}: ${Q}`).join(`
32
+ [limited video tracks]
33
+ ${Object.entries(k).map(([C,D])=>`${C}: ${D}`).join(`
31
34
  `)||"All tracks are available"}
32
35
 
33
- [best track] ${w?.quality}
34
- [selected track] ${_?.quality}
35
- `});let W=_&&u&&u.history[_.id]&&(0,H.now)()-u.history[_.id]<=r.trackCooldown&&(!u.last||_.id!==u.last.id);if(_?.id&&u&&!W&&u.recordSelection(_),W&&u?.last){let A=u.last;return u?.recordSwitch(A),d({message:`
36
- [last selected] ${A?.quality}
37
- `}),A}return u?.recordSwitch(_),_},Dt=uE;var ue=i=>new URL(i).hostname;var V=require("@vkontakte/videoplayer-shared");var Jh=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"))},Ie=async i=>{let e=i.muted;try{await i.play()}catch(t){if(!Jh(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{await i.play()}catch(r){return Jh(r)&&(i.muted=!1,console.warn(r)),!1}}return!0};var Le=require("@vkontakte/videoplayer-shared");var st=require("@vkontakte/videoplayer-shared");function le(){return(0,st.now)()}function ko(i){return le()-i}function wo(i){let e=i.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,a=n=>r.test(n);return{resolve:(n,o,l=!1)=>{a(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let u=n.indexOf("?")>-1?"&":"?";return l&&(n+=u+"lowLat=1",u="&"),o&&(n+=u+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Xh(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function xr(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,l=!1,u=0,c,d,p=!1,m="arraybuffer",b=7e3,g=2e3,y=()=>{if(l)return;(0,st.assertNonNullable)(c);let z=ko(c),ne;if(z<g){ne=g-z,setTimeout(y,ne);return}g*=2,g>b&&(g=b),n&&n.abort(),n=new a,j()},I=z=>(s=z,Q),D=z=>(d=z,Q),x=()=>(m="json",Q),T=()=>{if(!l){if(--u>=0){y(),r&&r();return}l=!0,d&&d(),t&&t()}},P=z=>(p=z,Q),j=()=>{c=le(),n=new a,n.open("get",i);let z=0,ne,qe=0,Pe=()=>((0,st.assertNonNullable)(c),Math.max(c,Math.max(ne||0,qe||0)));if(s&&n.addEventListener("progress",R=>{let M=le();s.updateChunk&&R.loaded>z&&(s.updateChunk(Pe(),R.loaded-z),z=R.loaded,ne=M)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>T())),n.addEventListener("load",()=>{if(l)return;(0,st.assertNonNullable)(n);let R=n.status;if(R>=200&&R<300){if(n.response.byteLength&&s){let M=n.response.byteLength-z;M&&s.updateChunk&&s.updateChunk(Pe(),M)}n.responseType==="json"&&!Object.values(n.response).length?T():(d&&d(),e(n.response))}else T()}),n.addEventListener("error",()=>{T()}),p){let R=()=>{(0,st.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(qe=le(),n.removeEventListener("readystatechange",R))};n.addEventListener("readystatechange",R)}return n.responseType=m,n.send(),Q},Q={withBitrateReporting:I,withParallel:P,withJSONResponse:x,withRetryCount:z=>(u=z,Q),withRetryInterval:(z,ne)=>((0,st.isNonNullable)(z)&&(g=z),(0,st.isNonNullable)(ne)&&(b=ne),Q),withTimeout:z=>(o=z,Q),withFinally:D,send:j,abort:()=>{n&&(n.abort(),n=void 0),l=!0,d&&d()}};return Q}var hi=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 mi=class{constructor(e,t,r,a,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=a,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=le(),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=le()-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=xr(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=le()}_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=le();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,a){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=a,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=a,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var is=1e4,Ao=3;var cE=6e4,dE=10,pE=1,hE=500,fi=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 hi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=wo(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=wo(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,a;r!==0&&(a=t.buffered.start(r-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){let{videoElement:t}=this.params,r,a,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!a||s.bitrate>a.bitrate)&&(a=s):(!r||r.bitrate>s.bitrate)&&(r=s));return a||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,Le.isNonNullable)(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=()=>{Xh(a,"progress",()=>{a.buffered.length?(a.currentTime=a.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new mi(Ao,is,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:a}=this.params,s=!1,n=null,o=null,l=null,u=null,c=!1,d=()=>{let T=s&&(!c||c===this.rep);return T||t("Not running!"),T},p=(T,P,j)=>{l&&l.abort(),l=xr(this.urlResolver.resolve(T,!1),P,j,()=>this._retryCallback()).withTimeout(is).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ao).withFinally(()=>{l=null}).send()},m=(T,P,j)=>{(0,Le.assertNonNullable)(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(T,!1),P,j,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},b=T=>{let P=r.playbackRate;r.playbackRate!==T&&(t(`Playback rate switch: ${P}=>${T}`),r.playbackRate=T)},g=T=>{this.lowLatency=T,t(`lowLatency changed to ${T}`),y()},y=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)b(1);else{let T=this._getBufferSizeSec();if(this.bufferStates.length<5){b(1);return}let j=le()-1e4,w=0;for(let W=0;W<this.bufferStates.length;W++){let A=this.bufferStates[W];T=Math.min(T,A.buf),A.ts<j&&w++}this.bufferStates.splice(0,w),t(`update playback rate; minBuffer=${T} drop=${w} jitter=${this.sourceJitter}`);let _=T-pE;this.sourceJitter>=0?_-=this.sourceJitter/2:this.sourceJitter-=1,_>3?b(1.15):_>1?b(1.1):_>.3?b(1.05):b(1)}},I=T=>{let P,j=()=>P&&P.start?P.start.length:0,w=R=>P.start[R]/1e3,_=R=>P.dur[R]/1e3,W=R=>P.fragIndex+R,A=(R,M)=>({chunkIdx:W(R),startTS:w(R),dur:_(R),discontinuity:M}),Q=()=>{let R=0;if(P&&P.dur){let M=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,ae=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ce=M;this.sourceJitter>1&&(ce+=this.sourceJitter-1);let ke=P.dur.length-1;for(;ke>=0&&(ce-=P.dur[ke],!(ce<=0));--ke);R=Math.min(ke,P.dur.length-1-ae),R=Math.max(R,0)}return A(R,!0)},z=R=>{let M=j();if(!(M<=0)){if((0,Le.isNonNullable)(R)){for(let ae=0;ae<M;ae++)if(w(ae)>R)return A(ae)}return Q()}},ne=R=>{let M=j(),ae=R?R.chunkIdx+1:0,ce=ae-P.fragIndex;if(!(M<=0)){if(!R||ce<0||ce-M>dE)return t(`Resync: offset=${ce} bChunks=${M} chunk=`+JSON.stringify(R)),Q();if(!(ce>=M))return A(ae-P.fragIndex,!1)}},qe=(R,M,ae)=>{u&&u.abort(),u=xr(this.urlResolver.resolve(R,!0,this.lowLatency),M,ae,()=>this._retryCallback()).withTimeout(is).withRetryCount(Ao).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(R,M)=>{qe(T,ae=>{if(!d())return;P=ae;let ce=!!P.lowLatency;ce!==this.lowLatency&&g(ce);let ke=0;for(let Ue=0;Ue<P.dur.length;++Ue)ke+=P.dur[Ue];ke>0&&((0,Le.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ke/P.dur.length)),a({name:"index",zeroTime:P.zeroTime,shiftDuration:P.shiftDuration}),this.sourceJitter=P.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,P.jitter/1e3)):1,R(z(M))},()=>this._handleNetworkError())},nextChunk:ne}},D=()=>{s=!1,o&&o.abort(),l&&l.abort(),u&&u.abort(),(0,Le.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:T=>{let{videoElement:P,logger:j}=this.params,w=I(e.jidxUrl),_,W,A,Q,z=0,ne,qe,Pe,R=()=>{ne&&(clearTimeout(ne),ne=void 0);let Y=Math.max(hE,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),se=z+Y,pe=le(),oe=Math.min(1e4,se-pe);z=pe;let Me=()=>{u||d()&&w.seek(()=>{d()&&(z=le(),M(),R())})};oe>0?ne=window.setTimeout(()=>{this.paused?R():Me()},oe):Me()},M=()=>{let Y;for(;Y=w.nextChunk(Q);)Q=Y,rr(Y);let se=w.nextChunk(A);if(se){if(A&&se.discontinuity){j("Detected discontinuity; restarting playback"),this.paused?R():(D(),this._initPlayerWith(e));return}Ue(se)}else R()},ae=(Y,se)=>{if(!d()||!this.sourceBuffer)return;let pe,oe,Me,wt=Ze=>{window.setTimeout(()=>{d()&&ae(Y,se)},Ze)};if(this.sourceBuffer.updating)j("Source buffer is updating; delaying appendBuffer"),wt(100);else{let Ze=le(),He=P.currentTime;!this.paused&&P.buffered.length>1&&qe===He&&Ze-Pe>500&&(j("Stall suspected; trying to fix"),this._fixupStall()),qe!==He&&(qe=He,Pe=Ze);let Bt=this._getBufferSizeSec();if(Bt>30)j(`Buffered ${Bt} seconds; delaying appendBuffer`),wt(2e3);else try{this.sourceBuffer.appendBuffer(Y),this.videoPlayStarted?(this.bufferStates.push({ts:Ze,buf:Bt}),y(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),se&&se()}catch(ut){if(ut.name==="QuotaExceededError")j("QuotaExceededError; delaying appendBuffer"),Me=this.sourceBuffer.buffered.length,Me!==0&&(pe=this.sourceBuffer.buffered.start(0),oe=He,oe-pe>4&&this.sourceBuffer.remove(pe,oe-3)),wt(1e3);else throw ut}}},ce=()=>{W&&_&&(j([`Appending chunk, sz=${W.byteLength}:`,JSON.stringify(A)]),ae(W,function(){W=null,M()}))},ke=Y=>e.fragUrlTemplate.replace("%%id%%",Y.chunkIdx),Ue=Y=>{d()&&m(ke(Y),(se,pe)=>{if(d()){if(pe/=1e3,W=se,A=Y,n=Y.startTS,pe){let oe=Math.min(10,Y.dur/pe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*oe:oe}ce()}},()=>this._handleNetworkError())},rr=Y=>{d()&&((0,Le.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ke(Y),!1)))},Vt=Y=>{d()&&(e.cachedHeader=Y,ae(Y,()=>{_=!0,ce()}))};s=!0,w.seek(Y=>{if(d()){if(z=le(),!Y){R();return}Q=Y,!(0,Le.isNullable)(T)||Y.startTS>T?Ue(Y):(A=Y,M())}},T),e.cachedHeader?Vt(e.cachedHeader):p(e.headerUrl,Vt,()=>this._handleNetworkError())},stop:D,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),(0,Le.isNonNullable)(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,(0,Le.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,Le.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,m,b;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(m=this._getBufferSizeSec(),b=d/this.bitrate,m>10&&b>.8||m>15&&b>.5||m>20&&b>.3)){e(`Not switching: buffer=${Math.floor(m)}; 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,m)=>{let b=le();if(this.chunkRateEstimator.addInterval(p,b,m)){let y=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:m,duration:b-p,speed:y}),!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&&ko(n)<3e4)return;r(d)}l=this.autoQuality};return{updateChunk:(d,p)=>{let m=s.updateChunk(d,p);return m&&u(),m},notifySwitch:d=>{let p=le();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=xr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(is).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;Ie(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))},cE))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var ee=require("@vkontakte/videoplayer-shared"),Ro=class{constructor(){this.onDroopedVideoFramesLimit$=new ee.Subject;this.subscription=new ee.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new ee.Subject;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&&!(0,ee.isInvariantQuality)(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&&(0,ee.isHigher)(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((0,ee.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,ee.interval)(this.droppedFramesChecker.checkTime).pipe((0,ee.filter)(()=>this.playing),(0,ee.filter)(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe((0,ee.debounce)(this.droppedFramesChecker.checkTime)),r=(0,ee.merge)(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])=>(0,ee.isLower)(r,a)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},as=Ro;var ss=require("@vkontakte/videoplayer-shared"),Zh=require("@vkontakte/videoplayer-shared");var bi=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var mE=(i,e)=>new ss.Observable(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(l=>t.next(l.isIntersecting||bi()))},{...r,...e});a.observe(i);let s=(0,Zh.fromEvent)(document,"visibilitychange").pipe((0,ss.map)(n=>!document.hidden||bi())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),Ne=mE;var fE=["paused","playing","ready"],bE=["paused","playing","ready"],Si=class{constructor(e){this.subscription=new V.Subscription;this.videoState=new q("stopped");this.representations$=new V.ValueSubject([]);this.textTracksManager=new _e;this.droppedFramesManager=new as;this.maxSeekBackTime$=new V.ValueSubject(1/0);this.zeroTime$=new V.ValueSubject(void 0);this.liveOffset=new ft;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:V.ErrorCategory.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)??(0,V.videoSizeToQuality)(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),(0,V.isNonNullable)(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(bE.includes(e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&fE.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(de(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(de(this.params.source.url,l))}return;default:return(0,V.assertNever)(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:V.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:a})};(0,V.merge)(this.videoState.stateChangeStarted$.pipe((0,V.map)(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,V.map)(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=ge(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(ue(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=Te(this.video);this.subscription.add(this.representations$.pipe((0,V.map)(a=>a.map(({track:s})=>s)),(0,V.filter)(a=>!!a.length),(0,V.once)()).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((0,V.filterChanged)(),(0,V.map)(a=>-a/1e3)).subscribe(this.params.output.duration$)).add((0,V.combine)({zeroTime:this.zeroTime$.pipe((0,V.filter)(V.isNonNullable)),position:r.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(at(this.video,this.params.desiredState.isLooped,t)).add(ye(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Be(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(Ne(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&(0,V.videoQualityToHeight)(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(0,V.assertNever)(a.to)}},t)).add((0,V.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,V.observableFrom)(["init"])).pipe((0,V.debounce)(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),ve(this.video)}createLiveDashPlayer(){let e=new fi({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&&(0,V.isNonNullable)(t)?t:Dt(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;(0,V.assertNonNullable)(u,"Representations missing"),this.dash.startPlay(u,r)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:r})=>r.id===e.id)?.representation;(0,V.assertNonNullable)(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(de(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var em=Si;var gt=(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)};var O=require("@vkontakte/videoplayer-shared");var ns=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let a=0,s=r.length;a<s;a++)if(r[a].callback===t){r.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let a=0,s=r.length;a<s;a++){let n=r[a];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Pr=class extends ns{constructor(){super(),this.listeners||ns.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},gi=class{constructor(){Object.defineProperty(this,"signal",{value:new Pr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document>"u")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch{r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(gi.prototype[Symbol.toStringTag]="AbortController",Pr.prototype[Symbol.toStringTag]="AbortSignal");function os(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function Lo(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!os({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||a)&&(s=function(u,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(u,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(l,u)=>{let c=s&&s.prototype.isPrototypeOf(l)?l.signal:u?u.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch{d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((m,b)=>{c.addEventListener("abort",()=>b(d),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([p,n(l,u)])}return n(l,u)},Request:s}}var vi=os({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),tm=vi?Lo({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,vt=vi?tm.fetch:window.fetch,GR=vi?tm.Request:window.Request,yt=vi?gi:window.AbortController,YR=vi?Pr:window.AbortSignal;var am=Ye(di(),1);var Tt=()=>window.ManagedMediaSource||window.MediaSource,us=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),rm=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),im=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var nt=require("@vkontakte/videoplayer-shared"),cs=document.createElement("video"),vE='video/mp4; codecs="avc1.42000a,mp4a.40.2"',yE='video/mp4; codecs="hev1.1.6.L93.B0"',sm='video/webm; codecs="vp09.00.10.08"',nm='video/webm; codecs="av01.0.00M.08"',TE='audio/mp4; codecs="mp4a.40.2"',IE='audio/webm; codecs="opus"',Wt={mms:us(),mse:rm(),hls:!!(cs.canPlayType?.("application/x-mpegurl")||cs.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Ee={mp4:!!cs.canPlayType?.("video/mp4"),webm:!!cs.canPlayType?.("video/webm"),cmaf:!0},xe={h264:!!Tt()?.isTypeSupported?.(vE),h265:!!Tt()?.isTypeSupported?.(yE),vp9:!!Tt()?.isTypeSupported?.(sm),av1:!!Tt()?.isTypeSupported?.(nm),aac:!!Tt()?.isTypeSupported?.(TE),opus:!!Tt()?.isTypeSupported?.(IE)},kr=(xe.h264||xe.h265)&&xe.aac,Qt,EE=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:nm}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:sm}})]);Qt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{EE()}catch(i){console.error(i)}var wr=Wt.hls&&Ee.mp4,om=()=>Object.keys(xe).filter(i=>xe[i]),um=(i,e=!1,t=!1)=>{let r=Wt.mse||Wt.mms&&t;return i.filter(a=>{switch(a){case"DASH_SEP":return r&&Ee.mp4&&kr;case"DASH_WEBM":return r&&Ee.webm&&xe.vp9&&xe.opus;case"DASH_WEBM_AV1":return r&&Ee.webm&&xe.av1&&xe.opus;case"DASH_STREAMS":return r&&(Ee.mp4&&kr||Ee.webm&&(xe.vp9||xe.av1)&&(xe.opus||xe.aac));case"DASH_LIVE":return Wt.mse&&Ee.mp4&&kr;case"DASH_LIVE_CMAF":return r&&Ee.mp4&&kr&&Ee.cmaf;case"DASH_ONDEMAND":return r&&Ee.mp4&&kr;case"HLS":case"HLS_ONDEMAND":return wr||e&&Wt.mse&&Ee.mp4&&kr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return wr;case"MPEG":return Ee.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Wt.webrtc&&Wt.ws&&xe.h264&&(Ee.mp4||Ee.webm);default:return(0,nt.assertNever)(a)}})},ls=i=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(i){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return Qt?Qt[t].smooth?[t,e]:Qt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Qt?Qt[t].powerEfficient?[t,e]:Qt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:(0,nt.assertNever)(i)}return[e,t]},lm=({webmCodec:i,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...ls(i),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],a=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(nt.clientChecker.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...a,"MPEG",...ls(i),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...ls(i),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...ls(i),...a,"HLS","HLS_ONDEMAND"];default:(0,nt.assertNever)(e)}return wr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},cm=({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=nt.clientChecker.isMac&&nt.clientChecker.isSafari;if(nt.clientChecker.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:(0,nt.assertNever)(i)}else wr&&!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"]},$o=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],dm=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,am.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return i.values().next().value.split(".").at(0)}};var Ar=require("@vkontakte/videoplayer-shared"),pm=i=>{if(!i)return{id:"EmptyResponse",category:Ar.ErrorCategory.PARSER,message:"Empty response"};if(i.length<=2&&i.match(/^\d+$/))return{id:`UVError#${i}`,category:Ar.ErrorCategory.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:Ar.ErrorCategory.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:Ar.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Ar.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var yi=(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};var S=require("@vkontakte/videoplayer-shared");var Dr=Ye(di(),1);var xE=(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)},PE=i=>window.clearTimeout(i),hm=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Mo=hm?xE:window.requestIdleCallback,aL=hm?PE:window.cancelIdleCallback;var Jm=Ye(Za(),1);var Fe=require("@vkontakte/videoplayer-shared"),kE=16,mm=!1;try{mm=Fe.clientChecker.isSafari&&!!Fe.clientChecker.macVersion&&Fe.clientChecker.macVersion<=kE}catch(i){console.error(i)}var Co=class{constructor(e){this.bufferFull$=new Fe.Subject;this.error$=new Fe.Subject;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:Fe.ErrorCategory.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;mm&&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:Fe.ErrorCategory.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:(0,Fe.assertNever)(t)}}},fm=Co;var Do=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};var E=require("@vkontakte/videoplayer-shared");var K=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 Rr=class extends K{};var Ti=class extends K{};var Ii=class extends K{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 Ei=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var xi=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Pi=class extends K{constructor(e,t){super(e,t),this.data=this.content}};var ie=class extends K{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var zt=class extends ie{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 ki=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var wi=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ai=class extends ie{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 Ri=class extends ie{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Li=class extends ie{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var $i=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Mi=class extends ie{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 Ci=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Di=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Oi=class extends ie{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Vi=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Bi=class extends ie{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 _i=class extends ie{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 Ni=class extends ie{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 AE={ftyp:Ii,moov:Ei,moof:xi,mdat:Pi,sidx:zt,trak:ki,mdia:$i,mfhd:Oi,tkhd:Mi,traf:Vi,tfhd:Bi,tfdt:_i,trun:Ni,minf:Ci,sv3d:wi,st3d:Ai,prhd:Ri,proj:Di,equi:Li,uuid:Ti,unknown:Rr},Kt=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=AE[e];return r?new r(t,new i):new Rr(t,new i)}};var Lr=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 LE=new TextDecoder("ascii"),$E=i=>LE.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",ME=i=>{let e=new zt(i,new Kt),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})},CE=(i,e)=>{let r=new Kt().parse(i),a=new Lr(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)},DE=(i,e)=>{let r=new Kt().parse(i),s=new Lr(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},OE=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 Kt().parse(i),a=new Lr(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},bm={validateData:$E,parseInit:OE,getIndexRange:()=>{},parseSegments:ME,parseFeedableSegmentChunk:CE,getSegmentEndTime:DE};var It=require("@vkontakte/videoplayer-shared");var gm=require("@vkontakte/videoplayer-shared");var Sm={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"}},vm=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=Fi(i,t),a=r in Sm,s=a?Sm[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=Fi(l),d=u*2**((o-1)*8)+c,p=t+o,m;return p+d>i.byteLength?m=new DataView(i.buffer,i.byteOffset+p):m=new DataView(i.buffer,i.byteOffset+p,d),{tag:a?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:m,valueSize:d}},Fi=(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},Je=(i,e)=>{switch(e){case"int":return i.getInt8(0);case"uint":return Fi(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:(0,gm.assertNever)(e)}},Jt=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=vm(r);if(!e(a))return;a.type==="master"&&Jt(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},ym=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=vm(i);return Jt(a.value,({tag:s,type:n,value:o})=>(s===17143?e=Je(o,n):s===17026?t=Je(o,n):s===17029&&(r=Je(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Tm=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],VE=[231,22612,22743,167,171,163,160,175],BE=i=>{let e,t,r,a,s=!1,n=!1,o=!1,l,u,c=!1,d=0;return Jt(i,({tag:p,type:m,value:b,valueSize:g})=>{if(p===21419){let y=Je(b,m);u=Fi(y)}else p!==21420&&(u=void 0);return p===408125543?(e=b.byteOffset,t=b.byteOffset+g):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=Je(b,m):p===17545?a=Je(b,m):p===21420&&u===475249515?l=Je(b,m):p===374648427?Jt(b,({tag:y,type:I,value:D})=>y===30321?(c=Je(D,I)===1,!1):!0):s&&n&&Tm.includes(p)&&(o=!0),!o}),(0,It.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,It.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,It.assertNonNullable)(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}}}},_E=i=>{if((0,It.isNullable)(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},NE=(i,e)=>{let t=!1,r=!1,a=o=>(0,It.isNonNullable)(o.time)&&(0,It.isNonNullable)(o.position),s=[],n;return Jt(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=Je(u,l));break;case 183:break;case 241:n&&(n.position=Je(u,l));break;default:t&&Tm.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}}})},FE=i=>{let e=0,t=!1;try{Jt(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):VE.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},Im={validateData:ym,parseInit:BE,getIndexRange:_E,parseSegments:NE,parseFeedableSegmentChunk:FE};var $r=i=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(i);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return Im;case"mp4":return bm}}throw new ReferenceError(`Unsupported mime type ${i}`)};var Uo=Ye(jm(),1);var qo=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};var Cr=require("@vkontakte/videoplayer-shared");var Gm=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var Ym=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},Et=(i,e)=>{let t=i;t=(0,Uo.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,Uo.default)(t,n,(o,l)=>(0,Cr.isNullable)(s)?o:(0,Cr.isNullable)(l)?s:s.padStart(parseInt(l,10),"0"))}return t},Wm=(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,m=s.getAttribute("mediaPresentationDuration"),b=n.getAttribute("duration"),y=s.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(m)p=Ym(m);else if(b){let T=Ym(b);(0,Cr.isNonNullable)(T)&&(p=T)}else y&&(p=parseInt(y,10));let I=0,D=s.getAttribute("profiles")?.split(",")??[];for(let T of l){let P=T.getAttribute("id")??"id"+(I++).toString(10),j=T.getAttribute("mimeType")??"",w=T.getAttribute("codecs")??"",_=T.getAttribute("contentType")??j?.split("/")[0],W=T.getAttribute("profiles")?.split(",")??[],A=T.getAttribute("lang")??void 0,Q=T.querySelector("Label")?.textContent?.trim()??void 0,z=T.querySelectorAll("Representation"),ne=T.querySelector("SegmentTemplate"),qe=T.querySelector("Role")?.getAttribute("value")??void 0,Pe=_,R={id:P,language:A,isDefault:qe==="main",label:Q,codecs:w,hdr:Pe==="video"&&qo(w),mime:j,representations:[]};for(let M of z){let ae=M.getAttribute("lang")??void 0,ce=M.getAttribute("label")??void 0,ke=M.querySelector("BaseURL")?.textContent?.trim()??"",Ue=new URL(ke||o,e).toString(),rr=M.getAttribute("mimeType")??j,Vt=M.getAttribute("codecs")??w??"",Y;if(_==="text"){let se=M.getAttribute("id")||"",pe=se.includes("_auto"),oe=M.querySelector("SegmentTemplate");if(oe){let Me={representationId:M.getAttribute("id")??void 0,bandwidth:M.getAttribute("bandwidth")??void 0},wt=parseInt(M.getAttribute("bandwidth")??"",10)/1e3,Ze=parseInt(oe.getAttribute("startNumber")??"",10)??1,He=parseInt(oe.getAttribute("timescale")??"",10),Bt=oe.querySelectorAll("SegmentTimeline S")??[],ut=oe.getAttribute("media");if(!ut)throw new ReferenceError("No media attribute in SegmentTemplate");let la=[],ca=0,da="",ir=0,Vr=Ze,he=0;for(let je of Bt){let _t=parseInt(je.getAttribute("d")??"",10),Ce=parseInt(je.getAttribute("r")??"",10)||0,At=parseInt(je.getAttribute("t")??"",10);he=Number.isFinite(At)?At:he;let Nt=_t/He*1e3,ar=he/He*1e3;for(let et=0;et<Ce+1;et++){let Rt=Et(ut,{...Me,segmentNumber:Vr.toString(10),segmentTime:(he+et*_t).toString(10)}),sr=(ar??0)+et*Nt,_r=sr+Nt;Vr++,la.push({time:{from:sr,to:_r},url:Rt})}he+=(Ce+1)*_t,ca+=(Ce+1)*Nt}ir=he/He*1e3,da=Et(ut,{...Me,segmentNumber:Vr.toString(10),segmentTime:he.toString(10)});let Br={time:{from:ir,to:1/0},url:da},lt={type:"template",baseUrl:Ue,segmentTemplateUrl:ut,initUrl:"",totalSegmentsDurationMs:ca,segments:la,nextSegmentBeyondManifest:Br,timescale:He};Y={id:se,kind:"text",segmentReference:lt,profiles:[],duration:p,bitrate:wt,mime:"",codecs:"",width:0,height:0,isAuto:pe}}else Y={id:M.getAttribute("id")||"",isAuto:pe,kind:"text",url:Ue}}else{let se=M.getAttribute("contentType")??rr?.split("/")[0]??_,pe=T.getAttribute("profiles")?.split(",")??[],oe=parseInt(M.getAttribute("width")??"",10),Me=parseInt(M.getAttribute("height")??"",10),wt=parseInt(M.getAttribute("bandwidth")??"",10)/1e3,Ze=M.getAttribute("frameRate")??"",He=M.getAttribute("quality")??void 0,Bt=Ze?Gm(Ze):void 0,ut=M.getAttribute("id")??"id"+(I++).toString(10),la=se==="video"?`${Me}p`:se==="audio"?`${wt}Kbps`:Vt,ca=`${ut}@${la}`,da=[...D,...W,...pe],ir,Vr=M.querySelector("SegmentBase"),he=M.querySelector("SegmentTemplate")??ne;if(Vr){let lt=M.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[je,_t]=lt.split("-").map(Rt=>parseInt(Rt,10)),Ce={from:je,to:_t},At=M.querySelector("SegmentBase")?.getAttribute("indexRange"),[Nt,ar]=At?At.split("-").map(Rt=>parseInt(Rt,10)):[],et=At?{from:Nt,to:ar}:void 0;ir={type:"byteRange",url:Ue,initRange:Ce,indexRange:et}}else if(he){let lt={representationId:M.getAttribute("id")??void 0,bandwidth:M.getAttribute("bandwidth")??void 0},je=parseInt(he.getAttribute("timescale")??"",10),_t=he.getAttribute("initialization")??"",Ce=he.getAttribute("media"),At=parseInt(he.getAttribute("startNumber")??"",10)??1,Nt=Et(_t,lt);if(!Ce)throw new ReferenceError("No media attribute in SegmentTemplate");let ar=he.querySelectorAll("SegmentTimeline S")??[],et=[],Rt=0,sr="",_r=0;if(ar.length){let pa=At,Ge=0;for(let nr of ar){let tt=parseInt(nr.getAttribute("d")??"",10),Ft=parseInt(nr.getAttribute("r")??"",10)||0,ha=parseInt(nr.getAttribute("t")??"",10);Ge=Number.isFinite(ha)?ha:Ge;let As=tt/je*1e3,Pf=Ge/je*1e3;for(let ma=0;ma<Ft+1;ma++){let kf=Et(Ce,{...lt,segmentNumber:pa.toString(10),segmentTime:(Ge+ma*tt).toString(10)}),ru=(Pf??0)+ma*As,wf=ru+As;pa++,et.push({time:{from:ru,to:wf},url:kf})}Ge+=(Ft+1)*tt,Rt+=(Ft+1)*As}_r=Ge/je*1e3,sr=Et(Ce,{...lt,segmentNumber:pa.toString(10),segmentTime:Ge.toString(10)})}else if((0,Cr.isNonNullable)(p)){let Ge=parseInt(he.getAttribute("duration")??"",10)/je*1e3,nr=Math.ceil(p/Ge),tt=0;for(let Ft=1;Ft<nr;Ft++){let ha=Et(Ce,{...lt,segmentNumber:Ft.toString(10),segmentTime:tt.toString(10)});et.push({time:{from:tt,to:tt+Ge},url:ha}),tt+=Ge}_r=tt,sr=Et(Ce,{...lt,segmentNumber:nr.toString(10),segmentTime:tt.toString(10)})}let xf={time:{from:_r,to:1/0},url:sr};ir={type:"template",baseUrl:Ue,segmentTemplateUrl:Ce,initUrl:Nt,totalSegmentsDurationMs:Rt,segments:et,nextSegmentBeyondManifest:xf,timescale:je}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!se||!rr)continue;let Br={video:"video",audio:"audio",text:"text"}[se];if(!Br)continue;Pe||=Br,Y={id:ca,kind:Br,segmentReference:ir,profiles:da,duration:p,bitrate:wt,mime:rr,codecs:Vt,width:oe,height:Me,fps:Bt,quality:He}}R.language||=ae,R.label||=ce,R.mime||=rr,R.codecs||=Vt,R.hdr||=Pe==="video"&&qo(Vt),R.representations.push(Y)}Pe&&a[Pe].push(R)}return{dynamic:u,liveAvailabilityStartTime:d,duration:p,streams:a}};var qi=Ye(di(),1);var Qm=require("@vkontakte/videoplayer-shared"),zm=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s})=>{let n=(s?Ct(s):void 0)??(0,Qm.videoSizeToQuality)({width:e,height:t});return n&&{id:i,quality:n,bitrate:r,size:{width:e,height:t},fps:a}},Km=({id:i,bitrate:e})=>({id:i,bitrate:e}),ds=(i,e,t)=>{let r=e.indexOf(i);return(0,qi.default)(t,Math.round(t.length*r/e.length))??(0,qi.default)(t,-1)},ps=({language:i,label:e},{id:t,url:r,isAuto:a})=>({id:t,url:r,isAuto:a,type:"internal",language:i,label:e}),Go=({id:i,language:e,label:t,codecs:r,isDefault:a})=>({id:i,language:e,label:t,codec:(0,qi.default)(r.split("."),0),isDefault:a}),Yo=({id:i,language:e,label:t,hdr:r,codecs:a})=>({id:i,language:e,hdr:r,label:t,codec:(0,qi.default)(a.split("."),0)}),hs=i=>"url"in i,xt=i=>i.type==="template",Ui=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var Hi=class{constructor(e,t,r,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:l=!1,manifest:u}){this.currentSegmentLength$=new E.ValueSubject(0);this.onLastSegment$=new E.ValueSubject(!1);this.fullyBuffered$=new E.ValueSubject(!1);this.playingRepresentation$=new E.ValueSubject(void 0);this.playingRepresentationInit$=new E.ValueSubject(void 0);this.error$=new E.Subject;this.gaps=[];this.subscription=new E.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new yt;this.destroyAbortController=new yt;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=(0,E.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,E.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new fm(this.sourceBuffer),this.subscription.add((0,E.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,l=this.mediaSource.readyState;l!=="open"&&(o={id:`SegmentEjection_source_${l}`,category:E.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:E.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add((0,E.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:E.ErrorCategory.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,Do(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=l,this.tuning.useNewPruneBufferStrategy){let u=gt(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);(0,E.assertNonNullable)(r,"No init buffer for starting representation"),(0,E.assertNonNullable)(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=(0,E.abortable)(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);(0,E.assertNonNullable)(r,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if((0,E.isNullable)(s)||(0,E.isNullable)(a)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),(0,E.assertNonNullable)(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();(0,E.isNonNullable)(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=(0,E.abortable)(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||!xt(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);(0,E.assertNonNullable)(a);let s=this.segments.get(r);(0,E.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(r);if((0,E.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,a),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=a,this.tuning=s,this.compatibilityMode=l,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!u?.dynamic,this.initData=new Map(r.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new yt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,E.isNullable)(e)||(0,E.isNullable)(this.downloadingRepresentationId)||(0,E.isNullable)(this.playingRepresentationId)||(0,E.isNullable)(this.sourceBuffer)||!(0,E.isNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if((0,E.assertNonNullable)(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=gt(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)&&Do(this.sourceBuffer.buffered)>=this.bufferLimit){let u=gt(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,Dr.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&&gt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Dr.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;(0,E.isNonNullable)(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||!xt(r.segmentReference))return;let a=r.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=this.segments.get(r.id)??[],n=(0,Dr.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;(0,E.assertNonNullable)(e);let t=this.segments.get(e);if(t?.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){for(let t of this.representations.values()){let r=t.segmentReference;if(!xt(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=Et(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:m}},b)=>{let g=p<=r&&m>=r,y=p>r||g||b===0&&r===0,I=Math.min(this.forwardBufferTarget,this.bufferLimit),D=this.preloadOnly&&p<=r+I||m<=r+I;return(d==="none"||d==="partially_ejected"&&y&&D&&this.sourceBuffer&&!yi(this.sourceBuffer.buffered,r))&&y&&D});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(0,E.abortable)(o,async function*(){let c=(0,E.getExponentialDelay)(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,m=$r(t.mime);a.segment.time.to=m.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]),Ui(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(0,E.abortable)(n,async function*(){let l=(0,E.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(u,l),(0,E.fromEvent)(window,"online").pipe((0,E.once)()).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),Ui(l)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(xt(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,Dr.default)(e,0).byte.from,to:(0,Dr.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:E.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}}}}prepareTemplateFetchSegmentParams(e,t){if(!xt(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:E.ErrorCategory.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=$r(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",m=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 g=p?d.byte.from-r:0,y=p?d.byte.to-r:e.byteLength,I=g<a,D=y<=a;if(d.status==="downloading"&&I&&D){d.status="downloaded";let x=new DataView(e.buffer,e.byteOffset+g,m);this.sourceBufferTaskQueue.append(x,s).then(T=>T&&!s.aborted?this.onSegmentFullyAppended(c,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&I&&(c.loadedBytes=Math.min(m,a-g),c.loadedBytes>c.feedingBytes)){let x=new DataView(e.buffer,e.byteOffset+g+c.feedingBytes,c.loadedBytes-c.feedingBytes),T=c.loadedBytes===m?x:$r(o.mime).parseFeedableSegmentChunk(x);T?.byteLength&&(d.status="partially_fed",c.feedingBytes+=T.byteLength,this.sourceBufferTaskQueue.append(T,s).then(P=>{if(s.aborted)n();else if(P)c.fedBytes+=T.byteLength,c.fedBytes===m&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<m)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,m=c<a,b=d<=a;if(m){if(u.status==="downloading"&&b){u.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+c,p);await this.sourceBufferTaskQueue.append(g,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 g=new DataView(e.buffer,e.byteOffset+c+l.feedingBytes,l.loadedBytes-l.feedingBytes),y=l.loadedBytes===p?g:$r(o.mime).parseFeedableSegmentChunk(g);y?.byteLength&&(u.status="partially_fed",l.feedingBytes+=y.byteLength,await this.sourceBufferTaskQueue.append(y,s)&&!s.aborted?(l.fedBytes+=y.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",hs(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=Mo(()=>(0,Jm.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?(0,E.abortable)(this.destroyAbortController.signal,async function*(){let o=(0,E.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,$r(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&&xt(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:E.ErrorCategory.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||(0,E.isNullable)(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],m=u[u.length-1];m.to>=d?m.to=Math.max(m.to,p):u.push(l[c])}return u},o=l=>{if(s>=t)return a;a.push(l.time),a=n(a);let u=hs(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 m of p)m.status==="none"&&Math.round(m.time.from)<=Math.round(u)&&Math.round(m.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||(0,E.isNullable)(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=hs(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 m of p)if(m.status==="none"&&Math.round(m.time.from)<=Math.round(c)&&Math.round(m.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=Mo(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:E.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if((0,E.isNullable)(this.sourceBuffer)||(0,E.isNullable)(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 ji=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var Xm=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}};var X=require("@vkontakte/videoplayer-shared");var ms=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new X.ValueSubject(void 0);this.lastConnectionReused$=new X.ValueSubject(void 0);this.lastRequestFirstBytes$=new X.ValueSubject(void 0);this.abortAllController=new yt;this.subscription=new X.Subscription;this.fetchManifest=(0,X.abortable)(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=ji(t));let r=yield vt(t,{signal:this.abortAllController.signal}).catch(Gi);return r?(this.onHeadersReceived(r.headers),r.text()):null}.bind(this));this.fetch=(0,X.abortable)(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 _=new URL(u,location.href);_.searchParams.append("bytes",`${r.from}-${r.to}`),u=_.toString();break}default:(0,X.assertNever)(t)}this.requestQuic&&(u=ji(u));let d=this.abortAllController.signal,p;if(n){let _=new yt;if(p=(0,X.merge)((0,X.fromEvent)(this.abortAllController.signal,"abort"),(0,X.fromEvent)(n,"abort")).subscribe(()=>{try{_.abort()}catch(W){Gi(W)}}),this.abortAllController.signal.aborted||n.aborted)try{_.abort()}catch(W){Gi(W)}d=_.signal}let m=(0,X.now)(),b=yield vt(u,{priority:s,headers:c,signal:d}).catch(Gi),g=(0,X.now)();if(!b)return p?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(g-m),!b.ok||!b.body)return p?.unsubscribe(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`));if(this.onHeadersReceived(b.headers),!a&&!o)return p?.unsubscribe(),b.arrayBuffer();let[y,I]=b.body.tee(),D=y.getReader();o&&this.throughputEstimator?.trackStream(I,l);let x=0,T=new Uint8Array(0),P=!1,j=_=>{p?.unsubscribe(),P=!0,Gi(_)},w=(0,X.abortable)(d,async function*({done:_,value:W}){if(x===0&&this.lastRequestFirstBytes$.next((0,X.now)()-m),d.aborted){p?.unsubscribe();return}if(!_&&W){let A=new Uint8Array(T.length+W.length);A.set(T),A.set(W,T.length),T=A,x+=W.byteLength,a?.(new DataView(T.buffer),x),yield D?.read().then(w,j)}}.bind(this));return yield D?.read().then(w,j),p?.unsubscribe(),P?null:T.buffer}.bind(this));this.fetchByteRangeRepresentation=(0,X.abortable)(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 m=t.parseInit(p),b=e.indexRange??t.getIndexRange(m);if(!b)throw new ReferenceError("No way to load representation index");let g;if(l)g=new DataView(d,b.from-n,b.to-b.from+1);else{let I=yield this.fetch(e.url,{range:b,priority:r,measureThroughput:!1});if(!I)return null;g=new DataView(I)}let y=t.parseSegments(g,m,b);return{init:m,dataView:new DataView(d),segments:y}}.bind(this));this.fetchTemplateRepresentation=(0,X.abortable)(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}=Xm(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:(0,X.assertNever)(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},Gi=i=>{if(!Ui(i))throw i};var Xt=(i,e,t)=>t*e+(1-t)*i,Wo=(i,e)=>i.reduce((t,r)=>t+r,0)/e,Zm=(i,e,t,r)=>{let a=0,s=t,n=Wo(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};var Yi=require("@vkontakte/videoplayer-shared"),Ot=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 Yi.ValueSubject(e.initial),this.debounced$=new Yi.ValueSubject(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new be(`raw_${t}`),this.smoothedSeries$=new be(`smoothed_${t}`),this.reportedSeries$=new be(`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)&&((0,Yi.isNullable)(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 fs=class extends Ot{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Xt(this.slow,e,this.params.emaAlphaSlow),this.fast=Xt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var bs=class extends Ot{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Wo(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Xt(this.emaSmoothed,e,this.params.emaAlpha);let r=Zm(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Ss=class extends Ot{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?Xt(this.smoothed,t,this.params.emaAlpha):t}};var Zt=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new fs({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new bs({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 Ss({initial:e,label:"liveEdgeDelay",...t})}};var Qo=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};var gs=require("@vkontakte/videoplayer-shared");var Wi=class i{constructor(e,t){this.currentRepresentation$=new gs.ValueSubject(null);this.currentSegment=null;this.currentSegmentId=0;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if((0,gs.isNullable)(e))return;let t=null,r=null;for(let a of this.representations){let s=a.segmentReference.segments.find(n=>n.time.from<=e&&n.time.to>=e);if(s){t=s,r=a;break}}!t||!r||this.currentSegment?.time.from===t.time.from&&this.currentSegment.time.to===t.time.to||(this.currentSegment=t,this.currentSegmentId=(this.currentSegmentId+1)%Number.MAX_SAFE_INTEGER,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(t.url,r.segmentReference.baseUrl).toString(),id:`subtitle-${this.currentSegmentId.toString(10)}`}))}destroy(){this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let r=i.filterRepresentations(t.representations);if(r){this.representations=r;break}}}static isSupported(e){return!!e?.some(t=>i.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&xt(t.segmentReference))}};var tf=["timeupdate","progress","play","seeked","stalled","waiting"];var vs=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new S.Subscription;this.representationSubscription=new S.Subscription;this.state$=new q("none");this.currentVideoRepresentation$=new S.ValueSubject(void 0);this.currentVideoRepresentationInit$=new S.ValueSubject(void 0);this.currentAudioRepresentation$=new S.ValueSubject(void 0);this.currentVideoSegmentLength$=new S.ValueSubject(0);this.currentAudioSegmentLength$=new S.ValueSubject(0);this.error$=new S.Subject;this.lastConnectionType$=new S.ValueSubject(void 0);this.lastConnectionReused$=new S.ValueSubject(void 0);this.lastRequestFirstBytes$=new S.ValueSubject(void 0);this.currentLiveTextRepresentation$=new S.ValueSubject(null);this.isLive$=new S.ValueSubject(!1);this.liveDuration$=new S.ValueSubject(0);this.liveAvailabilityStartTime$=new S.ValueSubject(void 0);this.bufferLength$=new S.ValueSubject(0);this.liveLoadBufferLength$=new S.ValueSubject(0);this.livePositionFromPlayer$=new S.ValueSubject(0);this.timeInWaiting=0;this.isActiveLowLatency$=new S.ValueSubject(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new S.Subject;this.gapWatchdogActive=!1;this.destroyController=new yt;this.initManifest=(0,S.abortable)(this.destroyController.signal,async function*(e,t,r){this.element=e,this.manifestUrlString=de(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:S.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,S.abortable)(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:S.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return null;let t=null;try{t=Wm(e??"",this.manifestUrlString)}catch(s){let n=pm(e)??{id:"ManifestParsing",category:S.ErrorCategory.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)&&Tt()?.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=dm(l);if(u&&(a[s]=o.filter(({codecs:c})=>c.startsWith(u))),s==="video"){let c=this.tuning.preferHDR,d=a.video.some(m=>m.hdr),p=a.video.some(m=>!m.hdr);S.clientChecker.isHDR&&c&&d?a.video=a.video.filter(m=>m.hdr):p&&(a.video=a.video.filter(m=>!m.hdr))}}return{...t,streams:a}}.bind(this));this.initRepresentations=(0,S.abortable)(this.destroyController.signal,async function*(e,t,r){(0,S.assertNonNullable)(this.manifest),(0,S.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=d=>{this.representationSubscription.add((0,S.fromEvent)(d,"error").pipe((0,S.filter)(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=this.tuning.useManagedMediaSource?im():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&us())if(r){let d=document.createElement("source");a(d),d.type="application/x-mpegurl",d.src=r.url,this.element.appendChild(d)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((d,p)=>[...d,...p.representations],[]);if(this.videoBufferManager=new Hi("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,S.isNonNullable)(t)){let d=this.manifest.streams.audio.reduce((p,m)=>[...p,...m.representations],[]);this.audioBufferManager=new Hi("audio",this.source,d,n),this.bufferManagers.push(this.audioBufferManager)}if(Wi.isSupported(this.manifest.streams.text)&&(this.liveTextManager=new Wi(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,S.interval)(1e3).subscribe(d=>{if(this.element?.paused){let p=So(this.manifestUrlString,2);this.manifestUrlString=de(this.manifestUrlString,p+1e3,2)}})),this.representationSubscription.add((0,S.merge)(...tf.filter(d=>d!=="waiting").map(d=>(0,S.fromEvent)(this.element,d))).pipe((0,S.map)(d=>this.element?gt(this.element.buffered,this.element.currentTime*1e3):0),(0,S.filterChanged)(),(0,S.filter)(d=>!!d),(0,S.tap)(d=>{this.stallWatchdogSubscription?.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe((0,S.filterChanged)()).subscribe(p=>Qo(this.element,1))),this.representationSubscription.add((0,S.combine)({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe((0,S.filter)(({bufferLength:p,isActiveLowLatency:m})=>m&&!!p)).subscribe(({bufferLength:p})=>this.liveEstimatedDelay.next(p))),this.representationSubscription.add((0,S.combine)({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:p,isActiveLowLatency:m})=>{if(!m)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=p-b,D=1;Math.abs(I)>g&&(D=1+Math.sign(I)*y),Qo(this.element,D)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let m=0;if(p){let b=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(y=>y.getLiveSegmentsToLoadState(this.manifest)?.to??b))-b}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let d=0;this.representationSubscription.add((0,S.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,S.throttle)(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:m})=>{if((0,S.assertNonNullable)(this.element),this.isUpdatingLive)return;let b=this.element.playbackRate,g=So(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),D=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,x=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,T=isFinite(p)?p:m,P=this.isActiveLowLatency$.getValue(),j=y<=this.tuning.live.activeLiveDelay&&g===0;this.isActiveLowLatency$.next(P&&j);let w="none";if(P?w="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&j?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(_=>_.proceedLowLatencyLive()),w="active_low_latency"):g!==0&&T<I?w="live_forward_buffering":T<I+x&&(w="live_with_target_offset"),isFinite(p)&&(d=p>d?p:d),w==="live_forward_buffering"||w==="live_with_target_offset"){let _=d-(I+D),W=this.normolizeLiveOffset(Math.trunc(g+_/b)),A=Math.abs(W-g),Q;!p||A<=this.tuning.dashCmafLive.offsetCalculationError?Q=g:W>0&&A>this.tuning.dashCmafLive.offsetCalculationError?Q=W:Q=0,this.manifestUrlString=de(this.manifestUrlString,Q,2)}w!=="none"&&w!=="active_low_latency"&&(d=0,this.updateLive())}))}let l=(0,S.merge)(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe((0,S.map)(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),u=(0,S.merge)(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe((0,S.map)(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue())));this.representationSubscription.add((0,S.merge)(this.forceEnded$,(0,S.combine)({allBuffersFull:l,someBufferEnded:u}).pipe((0,S.filter)(({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:S.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add((0,S.merge)(...this.bufferManagers.map(d=>d.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.subscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(d=>this.source?.addEventListener("sourceopen",d)));let c=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(d=>d.representations).flatMap(d=>d.duration??0)];this.source.duration=Math.max(...c)/1e3,this.audioBufferManager&&(0,S.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,S.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:S.ErrorCategory.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new ms({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Zt.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){(0,S.assertNonNullable)(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=de(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest?.streams.video),await this.audioBufferManager?.seekLive(this.manifest?.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){(0,S.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,S.merge)(...tf.map(e=>(0,S.fromEvent)(this.element,e)),(0,S.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:S.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,S.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,S.fromEvent)(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&yi(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(this.element){if(this.timeInWaiting+=1e3,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset);else{let t=this.element.currentTime*1e3;this.videoBufferManager?.maintain(t),this.audioBufferManager?.maintain(t)}}};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=(0,S.interval)(1e3).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:S.ErrorCategory.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){(0,S.assertNonNullable)(this.element),(0,S.assertNonNullable)(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),yi(this.element.buffered,r)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(r),this.audioBufferManager?.maintain(r),this.element.currentTime=r/1e3}stop(){this.element?.querySelectorAll("source").forEach(e=>e.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let t=this.element.currentTime*1e3,r=[],a=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let s of this.bufferManagers)for(let n of s.gaps)s.playingRepresentation$.getValue()===n.representation&&n.from-a<=t&&n.to+a>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?r.push(1/0):r.push(n.to));if(r.length){let s=Math.max(...r)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,s===1/0?this.forceEnded$.next():this.element.currentTime=s/1e3}}};var ys=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ts=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 rf=`attribute vec2 a_vertex;
36
+ [best video track] ${z?.quality}
37
+ [selected video track] ${X?.quality}
38
+ `}),Qh(r,p,X,u)},zh=(i,e,t,{throughput:r,tuning:a,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:c})=>{(0,B.assertNotEmptyArray)(t,Yh);let u=a.considerPlaybackRate&&(0,B.isNonNullable)(s)?s:1,d=[...t].sort(yo(-1)),l=i.bitrate;(0,B.assertNonNullable)(l);let p=u*Wh(n??.5,a.bitrateAudioFactorAtEmptyBuffer,a.bitrateAudioFactorAtFullBuffer),f;return(0,B.isNonNullable)(r)&&isFinite(r)&&(f=d.find(b=>(0,B.isNonNullable)(b.bitrate)?r-l>=b.bitrate*p:!0)),f||(f=Ya(i,e,t,a.minVideoAudioRatio)),f?.bitrate!==o?.last?.bitrate&&c({message:`
39
+ [AUDIO TRACKS ABR]
40
+ [available audio tracks]
41
+ ${t.map(b=>`{ id: ${b.id}, bitrate: ${b.bitrate} }`).join(`
42
+ `)}
43
+
44
+ [tuning]
45
+ ${Object.entries(a??{}).map(([b,g])=>`${b}: ${g}`).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] ${f?.id}
58
+ `}),f&&Qh(a,c,f,o)};var oe=i=>new URL(i).hostname;var O=require("@vkontakte/videoplayer-shared");var Kh=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"))},Te=async i=>{let e=i.muted;try{await i.play()}catch(t){if(!Kh(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{await i.play()}catch(r){return Kh(r)&&(i.muted=!1,console.warn(r)),!1}}return!0};var we=require("@vkontakte/videoplayer-shared");var Xe=require("@vkontakte/videoplayer-shared");function ue(){return(0,Xe.now)()}function To(i){return ue()-i}function Io(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 Jh(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function br(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,c=!1,u=0,d,l,p=!1,f="arraybuffer",b=7e3,g=2e3,y=()=>{if(c)return;(0,Xe.assertNonNullable)(d);let N=To(d),ee;if(N<g){ee=g-N,setTimeout(y,ee);return}g*=2,g>b&&(g=b),n&&n.abort(),n=new a,k()},E=N=>(s=N,D),M=N=>(l=N,D),x=()=>(f="json",D),T=()=>{if(!c){if(--u>=0){y(),r&&r();return}c=!0,l&&l(),t&&t()}},P=N=>(p=N,D),k=()=>{d=ue(),n=new a,n.open("get",i);let N=0,ee,Oe=0,fe=()=>((0,Xe.assertNonNullable)(d),Math.max(d,Math.max(ee||0,Oe||0)));if(s&&n.addEventListener("progress",w=>{let V=ue();s.updateChunk&&w.loaded>N&&(s.updateChunk(fe(),w.loaded-N),N=w.loaded,ee=V)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>T())),n.addEventListener("load",()=>{if(c)return;(0,Xe.assertNonNullable)(n);let w=n.status;if(w>=200&&w<300){if(n.response.byteLength&&s){let V=n.response.byteLength-N;V&&s.updateChunk&&s.updateChunk(fe(),V)}n.responseType==="json"&&!Object.values(n.response).length?T():(l&&l(),e(n.response))}else T()}),n.addEventListener("error",()=>{T()}),p){let w=()=>{(0,Xe.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Oe=ue(),n.removeEventListener("readystatechange",w))};n.addEventListener("readystatechange",w)}return n.responseType=f,n.send(),D},D={withBitrateReporting:E,withParallel:P,withJSONResponse:x,withRetryCount:N=>(u=N,D),withRetryInterval:(N,ee)=>((0,Xe.isNonNullable)(N)&&(g=N),(0,Xe.isNonNullable)(ee)&&(b=ee),D),withTimeout:N=>(o=N,D),withFinally:M,send:k,abort:()=>{n&&(n.abort(),n=void 0),c=!0,l&&l()}};return D}var ni=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 oi=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=ue(),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=ue()-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=br(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=ue()}_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=ue();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 Qa=1e4,Eo=3;var pE=6e4,hE=10,fE=1,mE=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 ni(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Io(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=Io(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||(0,we.isNonNullable)(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=()=>{Jh(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 oi(Eo,Qa,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 T=s&&(!d||d===this.rep);return T||t("Not running!"),T},p=(T,P,k)=>{c&&c.abort(),c=br(this.urlResolver.resolve(T,!1),P,k,()=>this._retryCallback()).withTimeout(Qa).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Eo).withFinally(()=>{c=null}).send()},f=(T,P,k)=>{(0,we.assertNonNullable)(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(T,!1),P,k,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},b=T=>{let P=r.playbackRate;r.playbackRate!==T&&(t(`Playback rate switch: ${P}=>${T}`),r.playbackRate=T)},g=T=>{this.lowLatency=T,t(`lowLatency changed to ${T}`),y()},y=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)b(1);else{let T=this._getBufferSizeSec();if(this.bufferStates.length<5){b(1);return}let k=ue()-1e4,Y=0;for(let X=0;X<this.bufferStates.length;X++){let C=this.bufferStates[X];T=Math.min(T,C.buf),C.ts<k&&Y++}this.bufferStates.splice(0,Y),t(`update playback rate; minBuffer=${T} drop=${Y} jitter=${this.sourceJitter}`);let z=T-fE;this.sourceJitter>=0?z-=this.sourceJitter/2:this.sourceJitter-=1,z>3?b(1.15):z>1?b(1.1):z>.3?b(1.05):b(1)}},E=T=>{let P,k=()=>P&&P.start?P.start.length:0,Y=w=>P.start[w]/1e3,z=w=>P.dur[w]/1e3,X=w=>P.fragIndex+w,C=(w,V)=>({chunkIdx:X(w),startTS:Y(w),dur:z(w),discontinuity:V}),D=()=>{let w=0;if(P&&P.dur){let V=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,se=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ce=V;this.sourceJitter>1&&(ce+=this.sourceJitter-1);let xe=P.dur.length-1;for(;xe>=0&&(ce-=P.dur[xe],!(ce<=0));--xe);w=Math.min(xe,P.dur.length-1-se),w=Math.max(w,0)}return C(w,!0)},N=w=>{let V=k();if(!(V<=0)){if((0,we.isNonNullable)(w)){for(let se=0;se<V;se++)if(Y(se)>w)return C(se)}return D()}},ee=w=>{let V=k(),se=w?w.chunkIdx+1:0,ce=se-P.fragIndex;if(!(V<=0)){if(!w||ce<0||ce-V>hE)return t(`Resync: offset=${ce} bChunks=${V} chunk=`+JSON.stringify(w)),D();if(!(ce>=V))return C(se-P.fragIndex,!1)}},Oe=(w,V,se)=>{u&&u.abort(),u=br(this.urlResolver.resolve(w,!0,this.lowLatency),V,se,()=>this._retryCallback()).withTimeout(Qa).withRetryCount(Eo).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(w,V)=>{Oe(T,se=>{if(!l())return;P=se;let ce=!!P.lowLatency;ce!==this.lowLatency&&g(ce);let xe=0;for(let Ye=0;Ye<P.dur.length;++Ye)xe+=P.dur[Ye];xe>0&&((0,we.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(xe/P.dur.length)),a({name:"index",zeroTime:P.zeroTime,shiftDuration:P.shiftDuration}),this.sourceJitter=P.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,P.jitter/1e3)):1,w(N(V))},()=>this._handleNetworkError())},nextChunk:ee}},M=()=>{s=!1,o&&o.abort(),c&&c.abort(),u&&u.abort(),(0,we.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:T=>{let{videoElement:P,logger:k}=this.params,Y=E(e.jidxUrl),z,X,C,D,N=0,ee,Oe,fe,w=()=>{ee&&(clearTimeout(ee),ee=void 0);let Q=Math.max(mE,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ne=N+Q,me=ue(),_e=Math.min(1e4,ne-me);N=me;let gt=()=>{u||l()&&Y.seek(()=>{l()&&(N=ue(),V(),w())})};_e>0?ee=window.setTimeout(()=>{this.paused?w():gt()},_e):gt()},V=()=>{let Q;for(;Q=Y.nextChunk(D);)D=Q,Qt(Q);let ne=Y.nextChunk(C);if(ne){if(C&&ne.discontinuity){k("Detected discontinuity; restarting playback"),this.paused?w():(M(),this._initPlayerWith(e));return}Ye(ne)}else w()},se=(Q,ne)=>{if(!l()||!this.sourceBuffer)return;let me,_e,gt,zt=St=>{window.setTimeout(()=>{l()&&se(Q,ne)},St)};if(this.sourceBuffer.updating)k("Source buffer is updating; delaying appendBuffer"),zt(100);else{let St=ue(),Kt=P.currentTime;!this.paused&&P.buffered.length>1&&Oe===Kt&&St-fe>500&&(k("Stall suspected; trying to fix"),this._fixupStall()),Oe!==Kt&&(Oe=Kt,fe=St);let wr=this._getBufferSizeSec();if(wr>30)k(`Buffered ${wr} seconds; delaying appendBuffer`),zt(2e3);else try{this.sourceBuffer.appendBuffer(Q),this.videoPlayStarted?(this.bufferStates.push({ts:St,buf:wr}),y(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ne&&ne()}catch(ta){if(ta.name==="QuotaExceededError")k("QuotaExceededError; delaying appendBuffer"),gt=this.sourceBuffer.buffered.length,gt!==0&&(me=this.sourceBuffer.buffered.start(0),_e=Kt,_e-me>4&&this.sourceBuffer.remove(me,_e-3)),zt(1e3);else throw ta}}},ce=()=>{X&&z&&(k([`Appending chunk, sz=${X.byteLength}:`,JSON.stringify(C)]),se(X,function(){X=null,V()}))},xe=Q=>e.fragUrlTemplate.replace("%%id%%",Q.chunkIdx),Ye=Q=>{l()&&f(xe(Q),(ne,me)=>{if(l()){if(me/=1e3,X=ne,C=Q,n=Q.startTS,me){let _e=Math.min(10,Q.dur/me);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*_e:_e}ce()}},()=>this._handleNetworkError())},Qt=Q=>{l()&&((0,we.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(xe(Q),!1)))},At=Q=>{l()&&(e.cachedHeader=Q,se(Q,()=>{z=!0,ce()}))};s=!0,Y.seek(Q=>{if(l()){if(N=ue(),!Q){w();return}D=Q,!(0,we.isNullable)(T)||Q.startTS>T?Ye(Q):(C=Q,V())}},T),e.cachedHeader?At(e.cachedHeader):p(e.headerUrl,At,()=>this._handleNetworkError())},stop:M,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),(0,we.isNonNullable)(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,(0,we.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,we.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=l=>{if(!this.autoQuality)return;let p,f,b;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&l<this.bitrate&&(f=this._getBufferSizeSec(),b=l/this.bitrate,f>10&&b>.8||f>15&&b>.5||f>20&&b>.3)){e(`Not switching: buffer=${Math.floor(f)}; 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,f)=>{let b=ue();if(this.chunkRateEstimator.addInterval(p,b,f)){let y=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:b-p,speed:y}),!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&&To(n)<3e4)return;r(l)}c=this.autoQuality};return{updateChunk:(l,p)=>{let f=s.updateChunk(l,p);return f&&u(),f},notifySwitch:l=>{let p=ue();l<o&&(n=p),o=l}}}_fetchManifest(e,t,r){this.manifestRequest=br(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Qa).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;Te(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))},pE))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var te=require("@vkontakte/videoplayer-shared"),xo=class{constructor(){this.onDroopedVideoFramesLimit$=new te.Subject;this.subscription=new te.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new te.Subject;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&&!(0,te.isInvariantQuality)(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&&(0,te.isHigher)(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((0,te.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,te.interval)(this.droppedFramesChecker.checkTime).pipe((0,te.filter)(()=>this.playing),(0,te.filter)(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe((0,te.debounce)(this.droppedFramesChecker.checkTime)),r=(0,te.merge)(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])=>(0,te.isLower)(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}},za=xo;var Ka=require("@vkontakte/videoplayer-shared"),Xh=require("@vkontakte/videoplayer-shared");var ci=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var bE=(i,e)=>new Ka.Observable(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=(0,Xh.fromEvent)(document,"visibilitychange").pipe((0,Ka.map)(n=>!document.hidden||ci())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),Be=bE;var gE=["paused","playing","ready"],SE=["paused","playing","ready"],li=class{constructor(e){this.subscription=new O.Subscription;this.videoState=new H("stopped");this.representations$=new O.ValueSubject([]);this.textTracksManager=new De;this.droppedFramesManager=new za;this.maxSeekBackTime$=new O.ValueSubject(1/0);this.zeroTime$=new O.ValueSubject(void 0);this.liveOffset=new nt;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:O.ErrorCategory.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=Et(a.name)??(0,O.videoSizeToQuality)(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),(0,O.isNonNullable)(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(SE.includes(e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&gE.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(le(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(le(this.params.source.url,c))}return;default:return(0,O.assertNever)(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:O.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:a})};(0,O.merge)(this.videoState.stateChangeStarted$.pipe((0,O.map)(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,O.map)(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=ge(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(oe(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=ye(this.video);this.subscription.add(this.representations$.pipe((0,O.map)(a=>a.map(({track:s})=>s)),(0,O.filter)(a=>!!a.length),(0,O.once)()).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((0,O.filterChanged)(),(0,O.map)(a=>-a/1e3)).subscribe(this.params.output.duration$)).add((0,O.combine)({zeroTime:this.zeroTime$.pipe((0,O.filter)(O.isNonNullable)),position:r.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(Je(this.video,this.params.desiredState.isLooped,t)).add(ve(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Ce(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Be(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&(0,O.videoQualityToHeight)(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(0,O.assertNever)(a.to)}},t)).add((0,O.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,O.observableFrom)(["init"])).pipe((0,O.debounce)(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Se(this.video)}createLiveDashPlayer(){let e=new 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&&(0,O.isNonNullable)(t)?t:xt(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;(0,O.assertNonNullable)(u,"Representations missing"),this.dash.startPlay(u,r)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:r})=>r.id===e.id)?.representation;(0,O.assertNonNullable)(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(le(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var Zh=li;var ct=(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)};var q=require("@vkontakte/videoplayer-shared");var Ja=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let a=0,s=r.length;a<s;a++)if(r[a].callback===t){r.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let a=0,s=r.length;a<s;a++){let n=r[a];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},gr=class extends Ja{constructor(){super(),this.listeners||Ja.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 gr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document>"u")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch{r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(di.prototype[Symbol.toStringTag]="AbortController",gr.prototype[Symbol.toStringTag]="AbortSignal");function Xa(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 Po(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!Xa({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((f,b)=>{d.addEventListener("abort",()=>b(l),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([p,n(c,u)])}return n(c,u)},Request:s}}var pi=Xa({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),ef=pi?Po({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,lt=pi?ef.fetch:window.fetch,YR=pi?ef.Request:window.Request,dt=pi?di:window.AbortController,QR=pi?gr:window.AbortSignal;var af=Fe(ii(),1);var pt=()=>window.ManagedMediaSource||window.MediaSource,Za=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),tf=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),rf=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var Ze=require("@vkontakte/videoplayer-shared"),ts=document.createElement("video"),TE='video/mp4; codecs="avc1.42000a,mp4a.40.2"',IE='video/mp4; codecs="hev1.1.6.L93.B0"',sf='video/webm; codecs="vp09.00.10.08"',nf='video/webm; codecs="av01.0.00M.08"',EE='audio/mp4; codecs="mp4a.40.2"',xE='audio/webm; codecs="opus"',_t={mms:Za(),mse:tf(),hls:!!(ts.canPlayType?.("application/x-mpegurl")||ts.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Ie={mp4:!!ts.canPlayType?.("video/mp4"),webm:!!ts.canPlayType?.("video/webm"),cmaf:!0},Ee={h264:!!pt()?.isTypeSupported?.(TE),h265:!!pt()?.isTypeSupported?.(IE),vp9:!!pt()?.isTypeSupported?.(sf),av1:!!pt()?.isTypeSupported?.(nf),aac:!!pt()?.isTypeSupported?.(EE),opus:!!pt()?.isTypeSupported?.(xE)},Sr=(Ee.h264||Ee.h265)&&Ee.aac,Nt,PE=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:nf}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:sf}})]);Nt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{PE()}catch(i){console.error(i)}var vr=_t.hls&&Ie.mp4,of=()=>Object.keys(Ee).filter(i=>Ee[i]),uf=(i,e=!1,t=!1)=>{let r=_t.mse||_t.mms&&t;return i.filter(a=>{switch(a){case"DASH_SEP":return r&&Ie.mp4&&Sr;case"DASH_WEBM":return r&&Ie.webm&&Ee.vp9&&Ee.opus;case"DASH_WEBM_AV1":return r&&Ie.webm&&Ee.av1&&Ee.opus;case"DASH_STREAMS":return r&&(Ie.mp4&&Sr||Ie.webm&&(Ee.vp9||Ee.av1)&&(Ee.opus||Ee.aac));case"DASH_LIVE":return _t.mse&&Ie.mp4&&Sr;case"DASH_LIVE_CMAF":return r&&Ie.mp4&&Sr&&Ie.cmaf;case"DASH_ONDEMAND":return r&&Ie.mp4&&Sr;case"HLS":case"HLS_ONDEMAND":return vr||e&&_t.mse&&Ie.mp4&&Sr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return vr;case"MPEG":return Ie.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return _t.webrtc&&_t.ws&&Ee.h264&&(Ie.mp4||Ie.webm);default:return(0,Ze.assertNever)(a)}})},es=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 Nt?Nt[t].smooth?[t,e]:Nt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Nt?Nt[t].powerEfficient?[t,e]:Nt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:(0,Ze.assertNever)(i)}return[e,t]},cf=({webmCodec:i,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...es(i),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],a=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Ze.clientChecker.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",...es(i),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...es(i),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...es(i),...a,"HLS","HLS_ONDEMAND"];default:(0,Ze.assertNever)(e)}return vr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},lf=({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=Ze.clientChecker.isMac&&Ze.clientChecker.isSafari;if(Ze.clientChecker.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:(0,Ze.assertNever)(i)}else vr&&!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"]},Ao=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],df=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,af.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return i.values().next().value.split(".").at(0)}};var yr=require("@vkontakte/videoplayer-shared"),pf=i=>{if(!i)return{id:"EmptyResponse",category:yr.ErrorCategory.PARSER,message:"Empty response"};if(i.length<=2&&i.match(/^\d+$/))return{id:`UVError#${i}`,category:yr.ErrorCategory.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:yr.ErrorCategory.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:yr.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:yr.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var hi=(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};var S=require("@vkontakte/videoplayer-shared");var Ar=Fe(ii(),1);var AE=(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)},kE=i=>window.clearTimeout(i),hf=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",ko=hf?AE:window.requestIdleCallback,n$=hf?kE:window.cancelIdleCallback;var Zf=Fe(ja(),1);var Ve=require("@vkontakte/videoplayer-shared"),wE=16,ff=!1;try{ff=Ve.clientChecker.isSafari&&!!Ve.clientChecker.macVersion&&Ve.clientChecker.macVersion<=wE}catch(i){console.error(i)}var wo=class{constructor(e){this.bufferFull$=new Ve.Subject;this.error$=new Ve.Subject;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:Ve.ErrorCategory.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;ff&&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:Ve.ErrorCategory.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:(0,Ve.assertNever)(t)}}},mf=wo;var Ro=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};var I=require("@vkontakte/videoplayer-shared");var K=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let a=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,a),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let a=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,a}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Tr=class extends K{};var fi=class extends K{};var mi=class extends K{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 bi=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var gi=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Si=class extends K{constructor(e,t){super(e,t),this.data=this.content}};var ae=class extends K{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Ft=class extends ae{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 vi=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var yi=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ti=class extends ae{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 Ii=class extends ae{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Ei=class extends ae{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var xi=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Pi=class extends ae{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 Ai=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ki=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var wi=class extends ae{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Ri=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var $i=class extends ae{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Li=class extends ae{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 Mi=class extends ae{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 $E={ftyp:mi,moov:bi,moof:gi,mdat:Si,sidx:Ft,trak:vi,mdia:xi,mfhd:wi,tkhd:Pi,traf:Ri,tfhd:$i,tfdt:Li,trun:Mi,minf:Ai,sv3d:yi,st3d:Ti,prhd:Ii,proj:ki,equi:Ei,uuid:fi,unknown:Tr},qt=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=$E[e];return r?new r(t,new i):new Tr(t,new i)}};var Ir=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var ME=new TextDecoder("ascii"),CE=i=>ME.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",DE=i=>{let e=new Ft(i,new qt),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})},BE=(i,e)=>{let r=new qt().parse(i),a=new Ir(r),s=a.findAll("moof"),n=e?a.findAll("uuid"):a.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],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)},VE=(i,e)=>{let r=new qt().parse(i),s=new Ir(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},OE=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 qt().parse(i),a=new Ir(r);if(a.find("sv3d")){e.is3dVideo=!0;let n=a.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=a.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let 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},bf={validateData:CE,parseInit:OE,getIndexRange:()=>{},parseSegments:DE,parseFeedableSegmentChunk:BE,getSegmentEndTime:VE};var ht=require("@vkontakte/videoplayer-shared");var Sf=require("@vkontakte/videoplayer-shared");var gf={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"}},vf=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=Ci(i,t),a=r in gf,s=a?gf[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=Ci(c),l=u*2**((o-1)*8)+d,p=t+o,f;return p+l>i.byteLength?f=new DataView(i.buffer,i.byteOffset+p):f=new DataView(i.buffer,i.byteOffset+p,l),{tag:a?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+l,value:f,valueSize:l}},Ci=(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},Ge=(i,e)=>{switch(e){case"int":return i.getInt8(0);case"uint":return Ci(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:(0,Sf.assertNever)(e)}},Ut=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=vf(r);if(!e(a))return;a.type==="master"&&Ut(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},yf=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=vf(i);return Ut(a.value,({tag:s,type:n,value:o})=>(s===17143?e=Ge(o,n):s===17026?t=Ge(o,n):s===17029&&(r=Ge(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Tf=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],_E=[231,22612,22743,167,171,163,160,175],NE=i=>{let e,t,r,a,s=!1,n=!1,o=!1,c,u,d=!1,l=0;return Ut(i,({tag:p,type:f,value:b,valueSize:g})=>{if(p===21419){let y=Ge(b,f);u=Ci(y)}else p!==21420&&(u=void 0);return p===408125543?(e=b.byteOffset,t=b.byteOffset+g):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=Ge(b,f):p===17545?a=Ge(b,f):p===21420&&u===475249515?c=Ge(b,f):p===374648427?Ut(b,({tag:y,type:E,value:M})=>y===30321?(d=Ge(M,E)===1,!1):!0):s&&n&&Tf.includes(p)&&(o=!0),!o}),(0,ht.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,ht.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,ht.assertNonNullable)(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}}}},FE=i=>{if((0,ht.isNullable)(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},qE=(i,e)=>{let t=!1,r=!1,a=o=>(0,ht.isNonNullable)(o.time)&&(0,ht.isNonNullable)(o.position),s=[],n;return Ut(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=Ge(u,c));break;case 183:break;case 241:n&&(n.position=Ge(u,c));break;default:t&&Tf.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}}})},UE=i=>{let e=0,t=!1;try{Ut(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):_E.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},If={validateData:yf,parseInit:NE,getIndexRange:FE,parseSegments:qE,parseFeedableSegmentChunk:UE};var Er=i=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(i);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return If;case"mp4":return bf}}throw new ReferenceError(`Unsupported mime type ${i}`)};var Oo=Fe(jf(),1);var Vo=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};var Pr=require("@vkontakte/videoplayer-shared");var Gf=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var Wf=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},Ht=(i,e)=>{let t=i;t=(0,Oo.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,Oo.default)(t,n,(o,c)=>(0,Pr.isNullable)(s)?o:(0,Pr.isNullable)(c)?s:s.padStart(parseInt(c,10),"0"))}return t},Qf=(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,f=s.getAttribute("mediaPresentationDuration"),b=n.getAttribute("duration"),y=s.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)p=Wf(f);else if(b){let T=Wf(b);(0,Pr.isNonNullable)(T)&&(p=T)}else y&&(p=parseInt(y,10));let E=0,M=s.getAttribute("profiles")?.split(",")??[];for(let T of c){let P=T.getAttribute("id")??"id"+(E++).toString(10),k=T.getAttribute("mimeType")??"",Y=T.getAttribute("codecs")??"",z=T.getAttribute("contentType")??k?.split("/")[0],X=T.getAttribute("profiles")?.split(",")??[],C=T.getAttribute("lang")??void 0,D=T.querySelector("Label")?.textContent?.trim()??void 0,N=T.querySelectorAll("Representation"),ee=T.querySelector("SegmentTemplate"),Oe=T.querySelector("Role")?.getAttribute("value")??void 0,fe=z,w={id:P,language:C,isDefault:Oe==="main",label:D,codecs:Y,hdr:fe==="video"&&Vo(Y),mime:k,representations:[]};for(let V of N){let se=V.getAttribute("lang")??void 0,ce=V.getAttribute("label")??void 0,xe=V.querySelector("BaseURL")?.textContent?.trim()??"",Ye=new URL(xe||o,e).toString(),Qt=V.getAttribute("mimeType")??k,At=V.getAttribute("codecs")??Y??"",Q;if(z==="text"){let ne=V.getAttribute("id")||"",me=ne.includes("_auto");Q={id:ne,isAuto:me,kind:"text",url:Ye}}else{let ne=V.getAttribute("contentType")??Qt?.split("/")[0]??z,me=T.getAttribute("profiles")?.split(",")??[],_e=parseInt(V.getAttribute("width")??"",10),gt=parseInt(V.getAttribute("height")??"",10),zt=parseInt(V.getAttribute("bandwidth")??"",10)/1e3,St=V.getAttribute("frameRate")??"",Kt=V.getAttribute("quality")??void 0,wr=St?Gf(St):void 0,ta=V.getAttribute("id")??"id"+(E++).toString(10),Pm=ne==="video"?`${gt}p`:ne==="audio"?`${zt}Kbps`:At,Am=`${ta}@${Pm}`,km=[...M,...X,...me],gs,wm=V.querySelector("SegmentBase"),kt=V.querySelector("SegmentTemplate")??ee;if(wm){let wt=V.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Rt,vs]=wt.split("-").map(Jt=>parseInt(Jt,10)),vt={from:Rt,to:vs},Rr=V.querySelector("SegmentBase")?.getAttribute("indexRange"),[ys,ra]=Rr?Rr.split("-").map(Jt=>parseInt(Jt,10)):[],$r=Rr?{from:ys,to:ra}:void 0;gs={type:"byteRange",url:Ye,initRange:vt,indexRange:$r}}else if(kt){let wt={representationId:V.getAttribute("id")??void 0,bandwidth:V.getAttribute("bandwidth")??void 0},Rt=parseInt(kt.getAttribute("timescale")??"",10),vs=kt.getAttribute("initialization")??"",vt=kt.getAttribute("media"),Rr=parseInt(kt.getAttribute("startNumber")??"",10)??1,ys=Ht(vs,wt);if(!vt)throw new ReferenceError("No media attribute in SegmentTemplate");let ra=kt.querySelectorAll("SegmentTimeline S")??[],$r=[],Jt=0,Ts="",Is=0;if(ra.length){let ia=Rr,Ne=0;for(let Xt of ra){let Qe=parseInt(Xt.getAttribute("d")??"",10),$t=parseInt(Xt.getAttribute("r")??"",10)||0,aa=parseInt(Xt.getAttribute("t")??"",10);Ne=Number.isFinite(aa)?aa:Ne;let Es=Qe/Rt*1e3,$m=Ne/Rt*1e3;for(let sa=0;sa<$t+1;sa++){let Lm=Ht(vt,{...wt,segmentNumber:ia.toString(10),segmentTime:(Ne+sa*Qe).toString(10)}),Ko=($m??0)+sa*Es,Mm=Ko+Es;ia++,$r.push({time:{from:Ko,to:Mm},url:Lm})}Ne+=($t+1)*Qe,Jt+=($t+1)*Es}Is=Ne/Rt*1e3,Ts=Ht(vt,{...wt,segmentNumber:ia.toString(10),segmentTime:Ne.toString(10)})}else if((0,Pr.isNonNullable)(p)){let Ne=parseInt(kt.getAttribute("duration")??"",10)/Rt*1e3,Xt=Math.ceil(p/Ne),Qe=0;for(let $t=1;$t<Xt;$t++){let aa=Ht(vt,{...wt,segmentNumber:$t.toString(10),segmentTime:Qe.toString(10)});$r.push({time:{from:Qe,to:Qe+Ne},url:aa}),Qe+=Ne}Is=Qe,Ts=Ht(vt,{...wt,segmentNumber:Xt.toString(10),segmentTime:Qe.toString(10)})}let Rm={time:{from:Is,to:1/0},url:Ts};gs={type:"template",baseUrl:Ye,segmentTemplateUrl:vt,initUrl:ys,totalSegmentsDurationMs:Jt,segments:$r,nextSegmentBeyondManifest:Rm,timescale:Rt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ne||!Qt)continue;let Ss={video:"video",audio:"audio",text:"text"}[ne];if(!Ss)continue;fe||=Ss,Q={id:Am,kind:Ss,segmentReference:gs,profiles:km,duration:p,bitrate:zt,mime:Qt,codecs:At,width:_e,height:gt,fps:wr,quality:Kt}}w.language||=se,w.label||=ce,w.mime||=Qt,w.codecs||=At,w.hdr||=fe==="video"&&Vo(At),w.representations.push(Q)}fe&&a[fe].push(w)}return{dynamic:u,liveAvailabilityStartTime:l,duration:p,streams:a}};var Di=Fe(ii(),1);var zf=require("@vkontakte/videoplayer-shared"),Kf=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s})=>{let n=(s?Et(s):void 0)??(0,zf.videoSizeToQuality)({width:e,height:t});return n&&{id:i,quality:n,bitrate:r,size:{width:e,height:t},fps:a}},Jf=({id:i,bitrate:e})=>({id:i,bitrate:e}),rs=(i,e,t)=>{let r=e.indexOf(i);return(0,Di.default)(t,Math.round(t.length*r/e.length))??(0,Di.default)(t,-1)},Xf=({language:i,label:e},{id:t,url:r,isAuto:a})=>({id:t,url:r,isAuto:a,type:"internal",language:i,label:e}),No=({id:i,language:e,label:t,codecs:r,isDefault:a})=>({id:i,language:e,label:t,codec:(0,Di.default)(r.split("."),0),isDefault:a}),Fo=({id:i,language:e,label:t,hdr:r,codecs:a})=>({id:i,language:e,hdr:r,label:t,codec:(0,Di.default)(a.split("."),0)}),is=i=>"url"in i,ft=i=>i.type==="template",Bi=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var Vi=class{constructor(e,t,r,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:c=!1,manifest:u}){this.currentSegmentLength$=new I.ValueSubject(0);this.onLastSegment$=new I.ValueSubject(!1);this.fullyBuffered$=new I.ValueSubject(!1);this.playingRepresentation$=new I.ValueSubject(void 0);this.playingRepresentationInit$=new I.ValueSubject(void 0);this.error$=new I.Subject;this.gaps=[];this.subscription=new I.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new dt;this.destroyAbortController=new dt;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=(0,I.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,I.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new mf(this.sourceBuffer),this.subscription.add((0,I.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,c=this.mediaSource.readyState;c!=="open"&&(o={id:`SegmentEjection_source_${c}`,category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add((0,I.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:I.ErrorCategory.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,Ro(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=c,this.tuning.useNewPruneBufferStrategy){let u=ct(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);(0,I.assertNonNullable)(r,"No init buffer for starting representation"),(0,I.assertNonNullable)(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=(0,I.abortable)(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);(0,I.assertNonNullable)(r,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if((0,I.isNullable)(s)||(0,I.isNullable)(a)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),(0,I.assertNonNullable)(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();(0,I.isNonNullable)(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=(0,I.abortable)(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||!ft(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);(0,I.assertNonNullable)(a);let s=this.segments.get(r);(0,I.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(r);if((0,I.assertNonNullable)(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 dt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,I.isNullable)(e)||(0,I.isNullable)(this.downloadingRepresentationId)||(0,I.isNullable)(this.playingRepresentationId)||(0,I.isNullable)(this.sourceBuffer)||!(0,I.isNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if((0,I.assertNonNullable)(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=ct(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)&&Ro(this.sourceBuffer.buffered)>=this.bufferLimit){let u=ct(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,Ar.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&&ct(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let c=(0,Ar.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;(0,I.isNonNullable)(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||!ft(r.segmentReference))return;let a=r.segmentReference.segments.map(c=>({...c,status:"none",size:void 0})),s=this.segments.get(r.id)??[],n=(0,Ar.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;(0,I.assertNonNullable)(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(!ft(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=Ht(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:f}},b)=>{let g=p<=r&&f>=r,y=p>r||g||b===0&&r===0,E=Math.min(this.forwardBufferTarget,this.bufferLimit),M=this.preloadOnly&&p<=r+E||f<=r+E;return(l==="none"||l==="partially_ejected"&&y&&M&&this.sourceBuffer&&!hi(this.sourceBuffer.buffered,r))&&y&&M});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(0,I.abortable)(o,async function*(){let d=(0,I.getExponentialDelay)(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,f=Er(t.mime);a.segment.time.to=f.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]),Bi(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(0,I.abortable)(n,async function*(){let c=(0,I.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(u,c),(0,I.fromEvent)(window,"online").pipe((0,I.once)()).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),Bi(c)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(ft(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,Ar.default)(e,0).byte.from,to:(0,Ar.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:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}}}}prepareTemplateFetchSegmentParams(e,t){if(!ft(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:I.ErrorCategory.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=Er(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",f=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 g=p?l.byte.from-r:0,y=p?l.byte.to-r:e.byteLength,E=g<a,M=y<=a;if(l.status==="downloading"&&E&&M){l.status="downloaded";let x=new DataView(e.buffer,e.byteOffset+g,f),T=this.getCurrentPosition();(0,I.isNonNullable)(T)&&(this.bufferAccumulation.accumulatedBufferSizeMs=l.time.to-T,this.bufferAccumulation.accumulated.push({segmentView:x,segmentProgress:d}),this.activeSegments.delete(d));let P=({segmentView:k,segmentProgress:Y})=>this.sourceBufferTaskQueue.append(k,s).then(z=>z&&!s.aborted?this.onSegmentFullyAppended(Y,t):n());this.bufferAccumulation.enabled&&this.bufferAccumulation.targetBufferSizeMs<this.bufferAccumulation.accumulatedBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(P),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||(0,I.isNullable)(T))&&(P({segmentView:x,segmentProgress:d}),this.resetAccumulateBufferAfterStall())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&E&&!M&&(d.loadedBytes=Math.min(f,a-g),d.loadedBytes>d.feedingBytes)){let x=new DataView(e.buffer,e.byteOffset+g+d.feedingBytes,d.loadedBytes-d.feedingBytes),T=d.loadedBytes===f?x:Er(o.mime).parseFeedableSegmentChunk(x);T?.byteLength&&(l.status="partially_fed",d.feedingBytes+=T.byteLength,this.sourceBufferTaskQueue.append(T,s).then(P=>{if(s.aborted)n();else if(P)d.fedBytes+=T.byteLength,d.fedBytes===f&&this.onSegmentFullyAppended(d,t);else{if(d.feedingBytes<f)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,f=d<a,b=l<=a;if(f){if(u.status==="downloading"&&b){u.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+d,p);await this.sourceBufferTaskQueue.append(g,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 g=new DataView(e.buffer,e.byteOffset+d+c.feedingBytes,c.loadedBytes-c.feedingBytes),y=c.loadedBytes===p?g:Er(o.mime).parseFeedableSegmentChunk(g);y?.byteLength&&(u.status="partially_fed",c.feedingBytes+=y.byteLength,await this.sourceBufferTaskQueue.append(y,s)&&!s.aborted?(c.fedBytes+=y.byteLength,c.fedBytes===p&&this.onSegmentFullyAppended(c,t)):n())}}}}onSegmentFullyAppended(e,t){this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",is(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let a of this.segments.get(r.id)??[])a.status==="fed"&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){(this.tuning.useDashAbortPartiallyFedSegment?e.status==="partially_fed"||e.status==="partially_ejected":e.status==="partially_ejected")?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status="none"),e.status="partially_ejected"):e.status="none";for(let r of this.activeSegments.values())if(r.segment===e){this.activeSegments.delete(r);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[a,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=ko(()=>(0,Zf.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?(0,I.abortable)(this.destroyAbortController.signal,async function*(){let o=(0,I.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Er(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&&ft(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:I.ErrorCategory.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||(0,I.isNullable)(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],f=u[u.length-1];f.to>=l?f.to=Math.max(f.to,p):u.push(c[d])}return u},o=c=>{if(s>=t)return a;a.push(c.time),a=n(a);let u=is(c)?c.size??0:c.byte.to-c.byte.from;s+=u};for(let c of this.segments.values())for(let u of c){let d=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,l=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||l)&&u.status==="fed"&&o(u)}for(let c=0;c<this.sourceBuffer.buffered.length;c++){let u=this.sourceBuffer.buffered.start(c)*1e3,d=this.sourceBuffer.buffered.end(c)*1e3,l=0;for(let p of this.segments.values())for(let f of p)f.status==="none"&&Math.round(f.time.from)<=Math.round(u)&&Math.round(f.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||(0,I.isNullable)(e)||this.sourceBuffer.updating)return!1;let a=0,s=1/0,n=-1/0,o=!1,c=u=>{s=Math.min(s,u.time.from),n=Math.max(n,u.time.to);let d=is(u)?u.size??0:u.byte.to-u.byte.from;a+=d};for(let u of this.segments.values())for(let d of u){if(d.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;d.status==="fed"&&c(d)}if(o=isFinite(s)&&isFinite(n),!o){a=0,s=1/0,n=-1/0;for(let u of this.segments.values())for(let d of u){if(d.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||a>t)break;d.status==="fed"&&c(d)}}if(o=isFinite(s)&&isFinite(n),!o)for(let u=0;u<this.sourceBuffer.buffered.length;u++){let d=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3;for(let p of this.segments.values())for(let f of p)if(f.status==="none"&&Math.round(f.time.from)<=Math.round(d)&&Math.round(f.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=ko(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:I.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if((0,I.isNullable)(this.sourceBuffer)||(0,I.isNullable)(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 Oi=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var em=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}};var G=require("@vkontakte/videoplayer-shared");var as=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:a=!1}){this.lastConnectionType$=new G.ValueSubject(void 0);this.lastConnectionReused$=new G.ValueSubject(void 0);this.lastRequestFirstBytes$=new G.ValueSubject(void 0);this.abortAllController=new dt;this.subscription=new G.Subscription;this.fetchManifest=(0,G.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Oi(r));let a=yield lt(r,{signal:this.abortAllController.signal}).catch(_i);return a?(t.log("success",(0,G.flattenObject)({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(a.headers),a.text()):(t.error("error",(0,G.flattenObject)({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,G.abortable)(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 D=new URL(u,location.href);D.searchParams.append("bytes",`${r.from}-${r.to}`),u=D.toString();break}default:(0,G.assertNever)(t)}this.requestQuic&&(u=Oi(u));let p=this.abortAllController.signal,f;if(n){let D=new dt;if(f=(0,G.merge)((0,G.fromEvent)(this.abortAllController.signal,"abort"),(0,G.fromEvent)(n,"abort")).subscribe(()=>{try{D.abort()}catch(N){_i(N)}}),this.abortAllController.signal.aborted||n.aborted)try{D.abort()}catch(N){_i(N)}p=D.signal}let b=(0,G.now)();l.log("startRequest",(0,G.flattenObject)({url:u,priority:s,rangeMethod:t,range:r,isLowLatency:c,requestStartedAt:b}));let g=yield lt(u,{priority:s,headers:d,signal:p}).catch(_i),y=(0,G.now)();if(!g)return l.error("error",{message:"No response in request"}),l.end(),f?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(y-b),!g.ok||!g.body){f?.unsubscribe();let D=`Fetch error ${g.status}: ${g.statusText}`;return l.error("error",{message:D}),l.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!a&&!o){f?.unsubscribe();let D=(0,G.now)(),N={requestStartedAt:b,requestEndedAt:D,duration:D-b};return l.log("endRequest",(0,G.flattenObject)(N)),l.end(),g.arrayBuffer()}let[E,M]=g.body.tee(),x=E.getReader();o&&this.throughputEstimator?.trackStream(M,c);let T=0,P=new Uint8Array(0),k=!1,Y=D=>{f?.unsubscribe(),k=!0,_i(D)},z=(0,G.abortable)(p,async function*({done:D,value:N}){if(T===0&&this.lastRequestFirstBytes$.next((0,G.now)()-b),p.aborted){f?.unsubscribe();return}if(!D&&N){let ee=new Uint8Array(P.length+N.length);ee.set(P),ee.set(N,P.length),P=ee,T+=N.byteLength,a?.(new DataView(P.buffer),T),yield x?.read().then(z,Y)}}.bind(this));yield x?.read().then(z,Y),f?.unsubscribe();let X=(0,G.now)(),C={failed:k,requestStartedAt:b,requestEndedAt:X,duration:X-b};return k?(l.error("endRequest",(0,G.flattenObject)(C)),l.end(),null):(l.log("endRequest",(0,G.flattenObject)(C)),l.end(),P.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,G.abortable)(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 f=t.parseInit(p),b=e.indexRange??t.getIndexRange(f);if(!b)throw new ReferenceError("No way to load representation index");let g;if(c)g=new DataView(l,b.from-n,b.to-b.from+1);else{let E=yield this.fetch(e.url,{range:b,priority:r,measureThroughput:!1});if(!E)return null;g=new DataView(E)}let y=t.parseSegments(g,f,b);return{init:f,dataView:new DataView(l),segments:y}}.bind(this));this.fetchTemplateRepresentation=(0,G.abortable)(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}=em(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:(0,G.assertNever)(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},_i=i=>{if(!Bi(i))throw i};var jt=(i,e,t)=>t*e+(1-t)*i,qo=(i,e)=>i.reduce((t,r)=>t+r,0)/e,tm=(i,e,t,r)=>{let a=0,s=t,n=qo(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};var Ni=require("@vkontakte/videoplayer-shared"),Pt=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 Ni.ValueSubject(e.initial),this.debounced$=new Ni.ValueSubject(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new he(`raw_${t}`),this.smoothedSeries$=new he(`smoothed_${t}`),this.reportedSeries$=new he(`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)&&((0,Ni.isNullable)(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 Pt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=jt(this.slow,e,this.params.emaAlphaSlow),this.fast=jt(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 Pt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=qo(this.pastMeasures,this.takenMeasures);this.emaSmoothed=jt(this.emaSmoothed,e,this.params.emaAlpha);let r=tm(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var os=class extends Pt{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?jt(this.smoothed,t,this.params.emaAlpha):t}};var Gt=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 Uo=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};var im=["timeupdate","progress","play","seeked","stalled","waiting"];var us=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new S.Subscription;this.representationSubscription=new S.Subscription;this.state$=new H("none");this.currentVideoRepresentation$=new S.ValueSubject(void 0);this.currentVideoRepresentationInit$=new S.ValueSubject(void 0);this.currentAudioRepresentation$=new S.ValueSubject(void 0);this.currentVideoSegmentLength$=new S.ValueSubject(0);this.currentAudioSegmentLength$=new S.ValueSubject(0);this.error$=new S.Subject;this.lastConnectionType$=new S.ValueSubject(void 0);this.lastConnectionReused$=new S.ValueSubject(void 0);this.lastRequestFirstBytes$=new S.ValueSubject(void 0);this.isLive$=new S.ValueSubject(!1);this.liveDuration$=new S.ValueSubject(0);this.liveAvailabilityStartTime$=new S.ValueSubject(void 0);this.bufferLength$=new S.ValueSubject(0);this.liveLoadBufferLength$=new S.ValueSubject(0);this.livePositionFromPlayer$=new S.ValueSubject(0);this.timeInWaiting=0;this.isActiveLowLatency$=new S.ValueSubject(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new S.Subject;this.gapWatchdogActive=!1;this.destroyController=new dt;this.initManifest=(0,S.abortable)(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=le(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:S.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,S.abortable)(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:S.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t;try{t=Qf(e??"",this.manifestUrlString)}catch(n){let o=pf(e)??{id:"ManifestParsing",category:S.ErrorCategory.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)&&pt()?.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=df(u);if(d&&(a[n]=c.filter(({codecs:l})=>l.startsWith(d))),n==="video"){let l=this.tuning.preferHDR,p=a.video.some(b=>b.hdr),f=a.video.some(b=>!b.hdr);S.clientChecker.isHDR&&l&&p?a.video=a.video.filter(b=>b.hdr):f&&(a.video=a.video.filter(b=>!b.hdr))}}let s={...t,streams:a};return this.tracer.log("updateManifestEnd",(0,S.flattenObject)(s)),s}.bind(this));this.initRepresentations=(0,S.abortable)(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initRepresentationsStart",(0,S.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:r})),(0,S.assertNonNullable)(this.manifest),(0,S.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=l=>{this.representationSubscription.add((0,S.fromEvent)(l,"error").pipe((0,S.filter)(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=this.tuning.useManagedMediaSource?rf():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Za())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 Vi("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,S.isNonNullable)(t)){let l=this.manifest.streams.audio.reduce((p,f)=>[...p,...f.representations],[]);this.audioBufferManager=new Vi("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((0,S.interval)(1e3).subscribe(l=>{if(this.element?.paused){let p=po(this.manifestUrlString,2);this.manifestUrlString=le(this.manifestUrlString,p+1e3,2)}})),this.representationSubscription.add((0,S.merge)(...im.filter(l=>l!=="waiting").map(l=>(0,S.fromEvent)(this.element,l))).pipe((0,S.map)(l=>this.element?ct(this.element.buffered,this.element.currentTime*1e3):0),(0,S.filterChanged)(),(0,S.filter)(l=>!!l),(0,S.tap)(l=>{this.stallWatchdogSubscription?.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe((0,S.filterChanged)()).subscribe(p=>Uo(this.element,1))),this.representationSubscription.add((0,S.combine)({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe((0,S.filter)(({bufferLength:p,isActiveLowLatency:f})=>f&&!!p)).subscribe(({bufferLength:p})=>this.liveEstimatedDelay.next(p))),this.representationSubscription.add((0,S.combine)({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:p,isActiveLowLatency:f})=>{if(!f)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,E=p-b,M=1;Math.abs(E)>g&&(M=1+Math.sign(E)*y),Uo(this.element,M)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let f=0;if(p){let b=(this.element?.currentTime??0)*1e3;f=Math.min(...this.bufferManagers.map(y=>y.getLiveSegmentsToLoadState(this.manifest)?.to??b))-b}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let l=0;this.representationSubscription.add((0,S.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,S.throttle)(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:f})=>{if((0,S.assertNonNullable)(this.element),this.isUpdatingLive)return;let b=this.element.playbackRate,g=po(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,E=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),M=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,x=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,T=isFinite(p)?p:f,P=this.isActiveLowLatency$.getValue(),k=y<=this.tuning.live.activeLiveDelay&&g===0;this.isActiveLowLatency$.next(P&&k);let Y="none";if(P?Y="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&k?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(z=>z.proceedLowLatencyLive()),Y="active_low_latency"):g!==0&&T<E?Y="live_forward_buffering":T<E+x&&(Y="live_with_target_offset"),isFinite(p)&&(l=p>l?p:l),Y==="live_forward_buffering"||Y==="live_with_target_offset"){let z=l-(E+M),X=this.normolizeLiveOffset(Math.trunc(g+z/b)),C=Math.abs(X-g),D;!p||C<=this.tuning.dashCmafLive.offsetCalculationError?D=g:X>0&&C>this.tuning.dashCmafLive.offsetCalculationError?D=X:D=0,this.manifestUrlString=le(this.manifestUrlString,D,2)}Y!=="none"&&Y!=="active_low_latency"&&(l=0,this.updateLive())}))}let c=(0,S.merge)(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe((0,S.map)(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),u=(0,S.merge)(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe((0,S.map)(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue())));this.representationSubscription.add((0,S.merge)(this.forceEnded$,(0,S.combine)({allBuffersFull:c,someBufferEnded:u}).pipe((0,S.filter)(({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:S.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:l})}})),this.representationSubscription.add((0,S.merge)(...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),ft(l.segmentReference)&&l.segmentReference.totalSegmentsDurationMs&&p.push(l.segmentReference.totalSegmentsDurationMs),p})];this.source.duration=Math.max(...d)/1e3,this.audioBufferManager&&(0,S.isNonNullable)(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=(0,S.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:S.ErrorCategory.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 as({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=Gt.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator}),this.initTracerSubscription()}async seekLive(e){(0,S.assertNonNullable)(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=le(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(){(0,S.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,S.merge)(...im.map(e=>(0,S.fromEvent)(this.element,e)),(0,S.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:S.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,S.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,S.fromEvent)(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&hi(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",(0,S.flattenObject)(t))};this.videoBufferManager?.startAccumulateBuffer(),this.audioBufferManager?.startAccumulateBuffer(),this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=(0,S.interval)(1e3).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:S.ErrorCategory.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){(0,S.assertNonNullable)(this.element),(0,S.assertNonNullable)(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),hi(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",(0,S.flattenObject)({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=(0,S.getTraceSubscriptionMethod)(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",(0,S.flattenObject)(t)))}}};var cs=class{constructor(e,t){this.fov=e,this.orientation=t}};var ls=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let a=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:a,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=r??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let a=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*a,this.fadeStartSpeed.y*a,this.fadeStartSpeed.z*a),a>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var am=`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 af=`#ifdef GL_ES
69
+ `;var sm=`#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 Is=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 ys(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ts(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(rf,this.gl.VERTEX_SHADER),r=this.createShader(af,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 er=class{constructor(e){this.subscription=new O.Subscription;this.videoState=new q("stopped");this.elementSize$=new O.ValueSubject(void 0);this.textTracksManager=new _e;this.droppedFramesManager=new as;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new rs;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"),k(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"),k(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="ready"&&k(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"&&k(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"&&k(this.params.desiredState.playbackState,"paused");return;default:return(0,O.assertNever)(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Is(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=ge(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(ue(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new vs({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=Te(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:O.ErrorCategory.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((0,O.filter)(u=>!!u.length),(0,O.once)()).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((0,O.filter)(O.isNonNullable),(0,O.once)()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe((0,O.map)(u=>u.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(at(this.video,t.isLooped,a)),this.subscription.add(ye(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Be(this.video,t.playbackRate,r.playbackRateState$,a)),s((0,O.observeElementSize)(this.video),this.elementSize$),s(Ne(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(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((0,O.assertNonNullable)(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let m of c.audio){p.push(Go(m));let b=[];for(let g of m.representations){let y=Km(g);b.push(y),this.audioTracksMap.set(y,{stream:m,representation:g})}this.audioStreamsMap.set(m,b)}this.params.output.availableAudioStreams$.next(p)}let d=[];for(let p of c.video){d.push(Yo(p));let m=[];for(let b of p.representations){let g=zm(b);g&&(m.push(g),this.videoTracksMap.set(g,{stream:p,representation:b}))}this.videoStreamsMap.set(p,m)}this.params.output.availableVideoStreams$.next(d);for(let p of c.text)for(let m of p.representations){let b=ps(p,m);this.textTracksMap.set(b,{stream:p,representation:m})}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:O.ErrorCategory.WTF,message:"Switching representations threw",thrown:u});this.subscription.add((0,O.merge)(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$,(0,O.fromEvent)(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,m]=d,b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),u==="manifest_ready")this.player.initRepresentations(p.id,m?.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(n),m){let g=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",m.id,g).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((0,O.filterChanged)()).subscribe(u=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===u);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:p}]=c,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===p.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(Yo(p))},a)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,O.filterChanged)()).subscribe(u=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===u);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:p}]=c,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===p.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(Go(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((0,O.map)(({to:u})=>u==="ready"),(0,O.filterChanged)());this.subscription.add((0,O.merge)(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((0,O.merge)(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=(0,O.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,O.observableFrom)(["init"])).pipe((0,O.debounce)(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:w})=>w===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:w})=>w===l.id),c=u&&this.videoStreamsMap.get(u);if(!c)return;let d=gt(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,m=Math.min(d/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),b=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),g=[...this.audioStreamsMap.keys()].find(({id:w})=>w===b?.id)??this.audioStreamsMap.keys().next().value,y=0;if(g){if(n&&!r){let w=ds(n,c,this.audioStreamsMap.get(g)??[]);y=Math.max(y,w?.bitrate??-1/0)}if(o){let w=ds(o,c,this.audioStreamsMap.get(g)??[]);y=Math.max(y,w?.bitrate??-1/0)}}let I=Dt(c,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:y,forwardBufferHealth:m,current:o,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),{backgroundVideoQualityLimit:D}=this.params.tuning.autoTrackSelection;!this.params.output.elementVisible$.getValue()&&r&&(I=c.filter(w=>!(0,O.isInvariantQuality)(w.quality)).sort((w,_)=>(_.bitrate??0)-(w.bitrate??0)).filter(w=>(0,O.isLowerOrEqual)(w.quality,I.quality)&&(0,O.isLowerOrEqual)(w.quality,D))[0]??I);let x=r?I??n:n??I,T=g&&ds(x,c,this.audioStreamsMap.get(g)??[]),P=this.videoTracksMap.get(x)?.representation,j=T&&this.audioTracksMap.get(T)?.representation;if(P&&j)return[P,j];if(P&&!j&&this.audioTracksMap.size===0)return[P,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ie(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:O.ErrorCategory.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),ve(this.video)}};var zi=class extends er{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)}};var tr=require("@vkontakte/videoplayer-shared");var Ki=class extends er{constructor(e){super(e),this.liveOffset=new ft}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add((0,tr.combine)({interval:(0,tr.interval)(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((0,tr.combine)({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,tr.map)(({liveBufferTime:a,liveAvailabilityStartTime:s})=>a&&s?a+s:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(a=>{if(a){let s=ps(a,a);this.params.desiredState.internalTextTracks.startTransitionTo([s])}else this.params.desiredState.internalTextTracks.startTransitionTo([])}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),a=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(n,a)})}};var sf=Ye(Za(),1);var U=require("@vkontakte/videoplayer-shared"),Xe={};var Or=(i,e)=>new U.Observable(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),Ji=class{constructor(e){this.subscription=new U.Subscription;this.videoState=new q("initializing");this.textTracksManager=new _e;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:(0,U.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,U.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,U.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,U.assertNever)(e)}break;default:(0,U.assertNever)(t)}};this.video=ge(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(ue(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),ve(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:U.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,sf.default)(import("hls.js").then(a=>{e||(Xe.Hls=a.default,Xe.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){(0,U.assertNonNullable)(Xe.Hls,"hls.js not loaded"),this.hls=new Xe.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,U.assertNonNullable)(Xe.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=u=>{t.error$.next({id:"HlsJsProvider",category:U.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},a=Te(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(at(this.video,e.isLooped,r)),this.subscription.add(ye(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Be(this.video,e.playbackRate,a.playbackRateState$,r)),s(Ne(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe((0,U.map)(u=>u.to)),this.params.output.playbackState$),this.subscription.add(Or(this.hls,Xe.Events.ERROR).subscribe(u=>{u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:U.ErrorCategory.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"),k(e.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),k(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(Or(this.hls,Xe.Events.MANIFEST_PARSED).pipe((0,U.map)(({levels:u})=>u.reduce((c,d)=>{let p=d.name||d.height.toString(10),{width:m,height:b}=d,g=Ct(d.attrs.QUALITY??"")??(0,U.videoSizeToQuality)({width:m,height:b});if(!g)return c;let y=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,I={id:p.toString(),quality:g,bitrate:d.bitrate/1e3,size:{width:m,height:b},fps:y};return this.trackLevels.set(p,{track:I,level:d}),c.push(I),c},[]))),t.availableVideoTracks$),s(Or(this.hls,Xe.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){let c=[];for(let d of u.subtitleTracks){let p=d.name,m=d.attrs.URI||"",b=d.lang;c.push({id:p,url:m,language:b,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(Or(this.hls,Xe.Events.LEVEL_LOADING).pipe((0,U.map)(({url:u})=>ue(u))),t.hostname$),s(Or(this.hls,Xe.Events.FRAG_CHANGED),u=>{let{video:c,audio:d}=u.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3)}),this.subscription.add(Mt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:r}));let n=u=>Array.from(this.trackLevels.values()).find(({level:c})=>c===u)?.track,o=Or(this.hls,Xe.Events.LEVEL_SWITCHED).pipe((0,U.map)(({level:u})=>n(this.hls.levels[u])));o.pipe((0,U.filter)(U.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Mt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),u=>{if((0,U.isNullable)(u))return;let c=this.trackLevels.get(u.id)?.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,m=this.hls.levels[p];!m||c.bitrate>m.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=(0,U.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,U.observableFrom)(["init"])).pipe((0,U.debounce)(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 Ie(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:U.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState("paused"),k(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"),k(this.params.desiredState.playbackState,"stopped",!0)}};var nf="X-Playback-Duration",zo=async i=>{let e=await vt(i),t=await e.text(),r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return r?parseInt(r,10):e.headers.has(nf)?parseInt(e.headers.get(nf),10):void 0};var F=require("@vkontakte/videoplayer-shared");var Jo=Ye(Ln(),1);var Es=require("@vkontakte/videoplayer-shared");var kx=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=(0,Es.videoSizeToQuality)({width:t,height:r})}return e??null},wx=(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,Jo.default)(o[1].split(",").map(y=>y.split("="))),c=u.QUALITY??`stream-${u.BANDWIDTH}`,d=kx(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 m=u["FRAME-RATE"]?parseFloat(u["FRAME-RATE"]):void 0,b;if(u.RESOLUTION){let[y,I]=u.RESOLUTION.split("x").map(D=>parseInt(D,10));y&&I&&(b={width:y,height:I})}let g=new URL(t[++s],e).toString();d&&r.push({id:c,quality:d,url:g,bandwidth:p,size:b,fps:m})}if(l){let u=(0,Jo.default)(l[1].split(",").map(m=>m.split("=")).map(([m,b])=>[m,b.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}},Ax=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),Ko=0,of=async(i,e=i,t)=>{let a=await(await vt(i)).text();Ko+=1;try{let{qualityManifests:s,textTracks:n}=wx(a,e);return{qualityManifests:s,textTracks:n}}catch{if(Ko<=t.manifestRetryMaxCount)return await Ax((0,Es.getExponentialDelay)(Ko-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),of(i,e,t)}return{qualityManifests:[],textTracks:[]}},xs=of;var Xi=class{constructor(e){this.subscription=new F.Subscription;this.videoState=new q("stopped");this.textTracksManager=new _e;this.manifests$=new F.ValueSubject([]);this.liveOffset=new ft;this.manifestStartTime$=new F.ValueSubject(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"),k(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"?k(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),k(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"&&k(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"&&(k(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,F.assertNever)(t)}};this.params=e,this.video=ge(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:F.VideoQuality.INVARIANT,url:this.params.source.url},xs(de(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:F.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:F.ErrorCategory.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(ue(this.params.source.url)),this.maxSeekBackTime$=new F.ValueSubject(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:F.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=Te(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(ye(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Be(this.video,t.playbackRate,a.playbackRateState$,r)),s(Ne(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),k(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((0,F.filterChanged)(),(0,F.map)(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&&(0,F.isNonNullable)(u.to)){let d=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let p=this.manifests$.getValue().find(m=>m.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(ue(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((0,F.combine)({startTime:this.manifestStartTime$.pipe((0,F.filter)(F.isNonNullable)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:l})=>this.params.output.liveTime$.next(o+l*1e3),r)),this.subscription.add(this.manifests$.pipe((0,F.map)(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=(0,F.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,F.observableFrom)(["init"])).pipe((0,F.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ve(this.video)}prepare(){let e=this.selectManifest();if((0,F.isNullable)(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=de(a.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),zo(n).then(o=>{if(!(0,F.isNullable)(o))this.maxSeekBackTime$.next(o);else{let l=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if((0,F.isNullable)(l)||!isFinite(l))try{vt(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();zo(d).then(p=>{(0,F.isNullable)(p)||this.maxSeekBackTime$.next(p)})}})}catch{}}})}playIfAllowed(){Ie(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:F.ErrorCategory.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()}};var G=require("@vkontakte/videoplayer-shared");var Zi=class{constructor(e){this.subscription=new G.Subscription;this.videoState=new q("stopped");this.textTracksManager=new _e;this.manifests$=new G.ValueSubject([]);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"),k(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"?k(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),k(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"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):a?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,G.assertNever)(t)}};this.params=e,this.video=ge(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:G.VideoQuality.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(ue(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),xs(de(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:G.ErrorCategory.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:G.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},a=Te(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((0,G.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(at(this.video,t.isLooped,r)),this.subscription.add(ye(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Be(this.video,t.playbackRate,a.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),k(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&&(0,G.isNonNullable)(u.to)){let d=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let p=this.manifests$.getValue().find(m=>m.id===d);if(p){this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(ue(p.url));let m=this.params.desiredState.playbackRate.getState(),b=this.params.output.element$.getValue()?.playbackRate;if(m!==b){let g=this.params.output.element$.getValue();g&&(this.params.desiredState.playbackRate.setState(m),g.playbackRate=m)}}}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((0,G.map)(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)),!G.clientChecker.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,G.merge)((0,G.fromEvent)(o,"addtrack"),(0,G.fromEvent)(o,"removetrack"),(0,G.fromEvent)(o,"change"),(0,G.observableFrom)(["init"])).subscribe(()=>{for(let l=0;l<o.length;l++)o[l].mode="hidden"},r))}let n=(0,G.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,G.observableFrom)(["init"])).pipe((0,G.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ve(this.video)}prepare(){let e=this.selectManifest();if((0,G.isNullable)(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(){Ie(this.video).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:G.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var J=require("@vkontakte/videoplayer-shared");var ea=class{constructor(e){this.subscription=new J.Subscription;this.videoState=new q("stopped");this.trackUrls={};this.textTracksManager=new _e;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"),k(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"?k(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),k(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"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return(0,J.assertNever)(e)}};this.params=e,this.video=ge(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:J.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},a=Te(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((0,J.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(at(this.video,t.isLooped,r)),this.subscription.add(ye(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Be(this.video,t.playbackRate,a.playbackRateState$,r)),s(Ne(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),k(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&&(0,J.isNonNullable)(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=(0,J.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,J.observableFrom)(["init"])).pipe((0,J.debounce)(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),ve(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;(0,J.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,J.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ji(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ue(t))}playIfAllowed(){Ie(this.video).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:J.ErrorCategory.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=>!(0,J.isInvariantQuality)(o.track.quality)&&(0,J.isLowerOrEqual)(o.track.quality,e))?.track,s=this.params.desiredState.videoTrack.getState()?.id,n=this.trackUrls[s??"0"]?.track;if(a&&n&&(0,J.isHigherOrEqual)(n.quality,a.quality)&&(t=a),!t){let o=Object.values(this.trackUrls).filter(u=>!(0,J.isInvariantQuality)(u.track.quality)&&(0,J.isHigher)(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=Dt(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})}};var Z=require("@vkontakte/videoplayer-shared");var lf=require("@vkontakte/videoplayer-shared"),uf=["stun:videostun.mycdn.me:80"],Rx=1e3,Lx=3,Xo=()=>null,Ps=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=Xo;this.externalStopCallback=Xo;this.externalErrorCallback=Xo;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:uf}]};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:lf.ErrorCategory.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),Rx)}normalizeOptions(e={}){let t={stunServerList:uf,maxRetryNumber:Lx,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var ta=class{constructor(e){this.videoState=new q("stopped");this.maxSeekBackTime$=new Z.ValueSubject(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"),k(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"),k(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"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return(0,Z.assertNever)(e)}};this.subscription=new Z.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ge(e.container,e.tuning),this.liveStreamClient=new Ps(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),ve(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Z.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};(0,Z.merge)(this.videoState.stateChangeStarted$.pipe((0,Z.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,Z.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=Te(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(Ne(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(ye(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(0,Z.assertNever)(n.to)}},r)).add((0,Z.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,Z.observableFrom)(["init"])).pipe((0,Z.debounce)(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(ue(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:Z.VideoQuality.INVARIANT}),this.video.srcObject=e,k(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:Z.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ie(this.video).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Z.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var ra=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}};var v=require("@vkontakte/videoplayer-shared");var Pt=require("@vkontakte/videoplayer-shared"),cf=i=>new Pt.Observable(e=>{let t=new Pt.Subscription,r=i.desiredPlaybackState$.stateChangeStarted$.pipe((0,Pt.map)(({from:u,to:c})=>`${u}-${c}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe((0,Pt.map)(({type:u})=>u!==void 0)),n=new Pt.Subject,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()}});var $e=require("@vkontakte/videoplayer-shared");var ia=null,ks=null;function Zo(){return ia||(ia=new(window.AudioContext||window.webkitAudioContext)),ks||(ks=new GainNode(ia,{gain:1}),ks.connect(ia.destination)),{audioCtx:ia,gainNode:ks}}var df=require("@vkontakte/videoplayer-shared");var aa=class i{constructor(e,t,r,a,s){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=a;this.subscriptions=new $e.Subscription;this.lastAudioContextResumeId=0;!s||!this.isSupported()||a===1||this.subscriptions.add(this.provider$.pipe((0,$e.filter)(n=>!!n.type),(0,$e.once)()).subscribe(({type:n})=>this.subscribe(n)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){df.clientChecker.isSafari&&e!=="MPEG"||this.subscriptions.add((0,$e.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,$e.filter)(({playbackState:t,video:r,volume:{muted:a,volume:s}})=>t==="playing"&&!!r&&!a&&!!s),(0,$e.once)()).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}=Zo(),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:$e.ErrorCategory.VIDEO_PIPELINE,message:n?.message??"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:n})}}).catch(n=>{this.volumeMultiplierError$.next({id:i.errorId,category:$e.ErrorCategory.VIDEO_PIPELINE,message:n?.message??"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){let{gainNode:e}=Zo();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};var $x={chunkDuration:5e3,maxParallelRequests:5},sa=class{constructor(e){this.current$=new v.ValueSubject({type:void 0});this.providerError$=new v.Subject;this.noAvailableProvidersError$=new v.Subject;this.volumeMultiplierError$=new v.Subject;this.providerOutput={position$:new v.ValueSubject(0),duration$:new v.ValueSubject(1/0),volume$:new v.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new v.ValueSubject([]),currentVideoStream$:new v.ValueSubject(void 0),availableVideoTracks$:new v.ValueSubject([]),currentVideoTrack$:new v.ValueSubject(void 0),availableAudioStreams$:new v.ValueSubject([]),currentAudioStream$:new v.ValueSubject(void 0),availableAudioTracks$:new v.ValueSubject([]),currentVideoSegmentLength$:new v.ValueSubject(0),currentAudioSegmentLength$:new v.ValueSubject(0),isAudioAvailable$:new v.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new v.ValueSubject(!1),autoVideoTrackLimits$:new v.ValueSubject(void 0),currentBuffer$:new v.ValueSubject(void 0),isBuffering$:new v.ValueSubject(!0),error$:new v.Subject,warning$:new v.Subject,willSeekEvent$:new v.Subject,seekedEvent$:new v.Subject,loopedEvent$:new v.Subject,endedEvent$:new v.Subject,firstBytesEvent$:new v.Subject,loadedMetadataEvent$:new v.Subject,firstFrameEvent$:new v.Subject,canplay$:new v.Subject,isLive$:new v.ValueSubject(void 0),isLowLatency$:new v.ValueSubject(!1),canChangePlaybackSpeed$:new v.ValueSubject(!0),liveTime$:new v.ValueSubject(void 0),liveBufferTime$:new v.ValueSubject(void 0),availableTextTracks$:new v.ValueSubject([]),currentTextTrack$:new v.ValueSubject(void 0),hostname$:new v.ValueSubject(void 0),httpConnectionType$:new v.ValueSubject(void 0),httpConnectionReused$:new v.ValueSubject(void 0),inPiP$:new v.ValueSubject(!1),inFullscreen$:new v.ValueSubject(!1),element$:new v.ValueSubject(void 0),elementVisible$:new v.ValueSubject(!0),availableSources$:new v.ValueSubject(void 0),is3DVideo$:new v.ValueSubject(!1),playbackState$:new v.ValueSubject("")};this.subscription=new v.Subscription;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=um([...cm(this.params.tuning),...lm(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>(0,v.isNonNullable)(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 ra(s);let n=[...$o(!0),...$o(!1)];this.chromecastFormatsIterator=new ra(n.filter(o=>(0,v.isNonNullable)(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new aa(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((0,v.isNullable)(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:v.ErrorCategory.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(0,v.assertNever)(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(0,v.assertNonNullable)(o),new zi({...n,source:o,sourceHls:l})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new Ki({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),wr||!this.params.tuning.useHlsJs?new Zi({...n,source:o}):new Ji({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new Xi({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new ea({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new em({...n,source:o,config:{...$x,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new ta({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(0,v.assertNever)(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(0,v.assertNonNullable)(o),new ci({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(0,v.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,v.assertNever)(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(0,v.assertNever)(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,pf.default)(Object.entries(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new v.Subscription,t=!1,r=0;return e.add((0,v.merge)(this.providerOutput.error$,cf({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,v.map)(a=>({id:`ProviderHangup:${a}`,category:v.ErrorCategory.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((0,v.filter)(({to:s})=>s==="playing"),(0,v.once)()).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===v.ErrorCategory.NETWORK,o=a.category===v.ErrorCategory.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}};var B=require("@vkontakte/videoplayer-shared");var Mx=5e3,hf="one_video_throughput",mf="one_video_rtt",na=window.navigator.connection,ff=()=>{let i=na?.downlink;if((0,B.isNonNullable)(i)&&i!==10)return i*1e3},bf=()=>{let i=na?.rtt;if((0,B.isNonNullable)(i)&&i!==3e3)return i},Sf=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},eu=class i{constructor(e){this.subscription=new B.Subscription;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=i.load(hf)||(e.useBrowserEstimation?ff():void 0)||Mx,r=i.load(mf)??(e.useBrowserEstimation?bf():void 0)??0;if(this.throughput$=new B.ValueSubject(t),this.rtt$=new B.ValueSubject(r),this.rttAdjustedThroughput$=new B.ValueSubject(Sf(t,r,e.rttPenaltyRequestSize)),this.throughput=Zt.getSmoothedValue(t,-1,e),this.rtt=Zt.getSmoothedValue(r,1,e),e.useBrowserEstimation){let a=()=>{let n=ff();n&&this.throughput.next(n);let o=bf();(0,B.isNonNullable)(o)&&this.rtt.next(o)};na&&"onchange"in na&&this.subscription.add((0,B.fromEvent)(na,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{B.safeStorage.set(hf,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{B.safeStorage.set(mf,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,B.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,B.map)(({throughput:a,rtt:s})=>Sf(a,s,e.rttPenaltyRequestSize)),(0,B.filter)(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=(0,B.now)(),a=new B.Subscription;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add((0,B.fromEvent)(e,"progress").pipe((0,B.once)()).subscribe(s=>{t=s.loaded,r=(0,B.now)()}));break;case 1:case 0:a.add((0,B.fromEvent)(e,"loadstart").subscribe(()=>{t=0,r=(0,B.now)()}));break}a.add((0,B.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,B.now)(),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=(0,B.now)(),n=0,o=(0,B.now)(),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,(0,B.now)()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=(0,B.now)();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,s=(0,B.now)()}else n+=d.byteLength;o=(0,B.now)()}else a+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,B.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,B.now)()-o,this.concurrentDownloads.size),n=0,o=(0,B.now)());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=B.safeStorage.get(e);if((0,B.isNonNullable)(t))return parseInt(t,10)??void 0}},gf=eu;var oa=require("@vkontakte/videoplayer-shared"),vf={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:oa.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:oa.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewPartialSegmentFeeding:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1},yf=i=>({...(0,oa.fillWithDefault)(i,vf),configName:[...i.configName??[],...vf.configName]});var h=require("@vkontakte/videoplayer-shared");var kt=require("@vkontakte/videoplayer-shared"),tu=({seekState:i,position$:e})=>(0,kt.merge)(i.stateChangeEnded$.pipe((0,kt.map)(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),(0,kt.filter)(kt.isNonNullable)),e.pipe((0,kt.filter)(()=>i.getState().state==="none")));var Tf=require("@vkontakte/videoplayer-shared"),If=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return(0,Tf.assertNonNullable)(e,`Wrong container or containerId {${i.container}}`),e};var ws=require("@vkontakte/videoplayer-shared"),Ef=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe((0,ws.filter)(a=>a.length>0),(0,ws.once)()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t?.getValue().find(r))&&e.startTransitionTo(i)};var ua=class{constructor(e={configName:[]}){this.subscription=new h.Subscription;this.logger=new h.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new h.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new q("stopped"),seekState:new q({state:"none"}),volume:new q({volume:1,muted:!1}),videoTrack:new q(void 0),videoStream:new q(void 0),audioStream:new q(void 0),autoVideoTrackSwitching:new q(!0),autoVideoTrackLimits:new q({}),isLooped:new q(!1),playbackRate:new q(1),externalTextTracks:new q([]),internalTextTracks:new q([]),currentTextTrack:new q(void 0),textTrackCuesSettings:new q({}),cameraOrientation:new q({x:0,y:0})};this.info={playbackState$:new h.ValueSubject("stopped"),position$:new h.ValueSubject(0),duration$:new h.ValueSubject(1/0),muted$:new h.ValueSubject(!1),volume$:new h.ValueSubject(1),availableVideoStreams$:new h.ValueSubject([]),currentVideoStream$:new h.ValueSubject(void 0),availableQualities$:new h.ValueSubject([]),availableQualitiesFps$:new h.ValueSubject({}),currentQuality$:new h.ValueSubject(void 0),isAutoQualityEnabled$:new h.ValueSubject(!0),autoQualityLimitingAvailable$:new h.ValueSubject(!1),autoQualityLimits$:new h.ValueSubject({}),availableAudioStreams$:new h.ValueSubject([]),currentAudioStream$:new h.ValueSubject(void 0),availableAudioTracks$:new h.ValueSubject([]),isAudioAvailable$:new h.ValueSubject(!0),currentPlaybackRate$:new h.ValueSubject(1),currentBuffer$:new h.ValueSubject({start:0,end:0}),isBuffering$:new h.ValueSubject(!0),isStalled$:new h.ValueSubject(!1),isEnded$:new h.ValueSubject(!1),isLooped$:new h.ValueSubject(!1),isLive$:new h.ValueSubject(void 0),canChangePlaybackSpeed$:new h.ValueSubject(void 0),atLiveEdge$:new h.ValueSubject(void 0),atLiveDurationEdge$:new h.ValueSubject(void 0),liveTime$:new h.ValueSubject(void 0),liveBufferTime$:new h.ValueSubject(void 0),currentFormat$:new h.ValueSubject(void 0),availableTextTracks$:new h.ValueSubject([]),currentTextTrack$:new h.ValueSubject(void 0),throughputEstimation$:new h.ValueSubject(void 0),rttEstimation$:new h.ValueSubject(void 0),videoBitrate$:new h.ValueSubject(void 0),hostname$:new h.ValueSubject(void 0),httpConnectionType$:new h.ValueSubject(void 0),httpConnectionReused$:new h.ValueSubject(void 0),surface$:new h.ValueSubject("none"),chromecastState$:new h.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new h.ValueSubject(void 0),intrinsicVideoSize$:new h.ValueSubject(void 0),availableSources$:new h.ValueSubject(void 0),is3DVideo$:new h.ValueSubject(!1),currentVideoSegmentLength$:new h.ValueSubject(0),currentAudioSegmentLength$:new h.ValueSubject(0)};this.events={inited$:new h.Subject,ready$:new h.Subject,started$:new h.Subject,playing$:new h.Subject,paused$:new h.Subject,stopped$:new h.Subject,willStart$:new h.Subject,willResume$:new h.Subject,willPause$:new h.Subject,willStop$:new h.Subject,willDestruct$:new h.Subject,watchCoverageRecord$:new h.Subject,watchCoverageLive$:new h.Subject,managedError$:new h.Subject,fatalError$:new h.Subject,ended$:new h.Subject,looped$:new h.Subject,seeked$:new h.Subject,willSeek$:new h.Subject,firstBytes$:new h.Subject,loadedMetadata$:new h.Subject,firstFrame$:new h.Subject,canplay$:new h.Subject,log$:new h.Subject};this.experimental={element$:new h.ValueSubject(void 0),tuningConfigName$:new h.ValueSubject([]),enableDebugTelemetry$:new h.ValueSubject(!1),dumpTelemetry:Kh};if(this.initLogs(),this.tuning=yf(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ga({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new gf(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,m)=>{let b=typeof m;return["number","string","boolean"].includes(b)?m:m===null?null:`<${b}>`})),u=`Player.${String(r)}`,c=`Exception calling ${u} (${l.join(", ")})`;throw this.events.fatalError$.next({id:u,category:h.ErrorCategory.WTF,message:c,thrown:o}),o}}}})}initVideo(e){return this.config=e,this.domContainer=If(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new sa({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){let e=this.desiredState.playbackState;return e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!bi()?(0,h.fromEvent)(document,"visibilitychange").pipe((0,h.once)()).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){(0,h.assertNonNullable)(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((0,h.filter)(r=>r.length>0),(0,h.once)()).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){(0,h.assertNonNullable)(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 Ef(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((0,h.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return(0,h.isNonNullable)(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((0,h.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,h.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,h.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,h.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,h.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,h.map)(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,h.filter)(({from:e})=>e==="stopped"),(0,h.once)()).subscribe(()=>{this.initedAt=(0,h.now)(),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:h.ErrorCategory.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((0,h.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,h.map)(n=>n.destination),(0,h.filterChanged)()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe((0,h.map)(n=>n.map(({quality:o})=>o).sort((o,l)=>(0,h.isInvariantQuality)(o)?1:(0,h.isInvariantQuality)(l)?-1:(0,h.isHigher)(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((0,h.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,h.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,h.filterChanged)()).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((0,h.map)(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((0,h.combine)({hasLiveOffsetByPaused:(0,h.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,h.map)(n=>n.to),(0,h.filterChanged)(),(0,h.map)(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((0,h.combine)({atLiveEdge:(0,h.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:tu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,h.map)(({isLive:n,position:o,isLowLatency:l})=>{let u=this.getActiveLiveDelay(l);return n&&Math.abs(o)<u/1e3}),(0,h.filterChanged)(),(0,h.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,h.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,h.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,h.map)(({isLive:n,position:o,duration:l})=>n&&(Math.abs(l)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,h.filterChanged)(),(0,h.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,h.map)(n=>n.muted),(0,h.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,h.map)(n=>n.volume),(0,h.filterChanged)()).subscribe(this.info.volume$)).add(tu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,h.merge)(e.providerOutput.endedEvent$.pipe((0,h.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,h.mapTo)(!1))).pipe((0,h.filterChanged)()).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((0,h.map)(n=>({id:n?`No${n}`:"NoProviders",category:h.ErrorCategory.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((0,h.once)(),(0,h.map)(n=>n??(0,h.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,h.once)(),(0,h.map)(()=>(0,h.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,h.once)(),(0,h.map)(()=>(0,h.now)()-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 h.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new h.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,h.filter)(({to:n})=>n==="playing"),(0,h.once)()).subscribe(()=>r.next(!1)));let a=0,s=(0,h.merge)(e.providerOutput.isBuffering$,t,r).pipe((0,h.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),(0,h.filterChanged)());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((0,h.merge)(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((0,h.merge)(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((0,h.map)(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new h.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,h.filterChanged)((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,h.filter)(r=>r.length>0),(0,h.once)()).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=Dt(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((0,h.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,h.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,h.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,h.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,h.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,h.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,h.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,h.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,h.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,h.map)(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;(0,h.assertNonNullable)(this.providerContainer),(0,h.assertNonNullable)(e),zh(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Qh(t)),this.providerContainer.current$.subscribe(({type:t})=>pi("provider",t)),e.duration$.subscribe(t=>pi("duration",t)),e.availableVideoTracks$.pipe((0,h.filter)(t=>!!t.length),(0,h.once)()).subscribe(t=>pi("tracks",t)),this.events.fatalError$.subscribe(new be("fatalError")),this.events.managedError$.subscribe(new be("managedError")),e.position$.subscribe(new be("position")),e.currentVideoTrack$.pipe((0,h.map)(t=>t?.quality)).subscribe(new be("quality")),this.info.currentBuffer$.subscribe(new be("buffer")),e.isBuffering$.subscribe(new be("isBuffering"))].forEach(t=>this.subscription.add(t)),pi("codecs",om())}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:h.ErrorCategory.DOM,message:String(a)})})};this.subscription.add((0,h.merge)((0,h.fromEvent)(document,"visibilitychange"),(0,h.fromEvent)(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}};var ot=require("@vkontakte/videoplayer-shared"),Cx=`@vkontakte/videoplayer-core@${Rs}`;
112
+ `;var ds=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 cs(this.params.fov,this.params.orientation),this.cameraRotationManager=new ls(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),a=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(a,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(am,this.gl.VERTEX_SHADER),r=this.createShader(sm,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 Wt=class{constructor(e){this.subscription=new q.Subscription;this.videoState=new H("stopped");this.elementSize$=new q.ValueSubject(void 0);this.textTracksManager=new De;this.droppedFramesManager=new za;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new si;this.audioTrackSwitchHistory=new si;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"),A(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"),A(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="ready"&&A(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"&&A(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"&&A(this.params.desiredState.playbackState,"paused");return;default:return(0,q.assertNever)(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new ds(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=ge(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(oe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new us({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=ye(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:q.ErrorCategory.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((0,q.filter)(u=>!!u.length),(0,q.once)()).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((0,q.filter)(q.isNonNullable),(0,q.once)()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe((0,q.map)(u=>u.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(Je(this.video,t.isLooped,a)),this.subscription.add(ve(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Ce(this.video,t.playbackRate,r.playbackRateState$,a)),s((0,q.observeElementSize)(this.video),this.elementSize$),s(Be(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),A(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((0,q.assertNonNullable)(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let f of d.audio){p.push(No(f));let b=[];for(let g of f.representations){let y=Jf(g);b.push(y),this.audioTracksMap.set(y,{stream:f,representation:g})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(p)}let l=[];for(let p of d.video){l.push(Fo(p));let f=[];for(let b of p.representations){let g=Kf(b);g&&(f.push(g),this.videoTracksMap.set(g,{stream:p,representation:b}))}this.videoStreamsMap.set(p,f)}this.params.output.availableVideoStreams$.next(l);for(let p of d.text)for(let f of p.representations){let b=Xf(p,f);this.textTracksMap.set(b,{stream:p,representation:f})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size>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:q.ErrorCategory.WTF,message:"Switching representations threw",thrown:u});this.subscription.add((0,q.merge)(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$,(0,q.fromEvent)(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,f]=l,b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),u==="manifest_ready")this.player.initRepresentations(p.id,f?.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(n),f){let g=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",f.id,g).catch(n)}},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((0,q.filterChanged)()).subscribe(u=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===u);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[l,{stream:p}]=d,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===p.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(l),e.currentVideoStream$.next(Fo(p))},a)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,q.filterChanged)()).subscribe(u=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===u);if(!d){e.currentAudioStream$.next(void 0);return}let[l,{stream:p}]=d,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===p.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(No(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((0,q.map)(({to:u})=>u==="ready"),(0,q.filterChanged)());this.subscription.add((0,q.merge)(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((0,q.merge)(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let c=(0,q.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,q.observableFrom)(["init"])).pipe((0,q.debounce)(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:k})=>k===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:k})=>k===c.id),d=u&&this.videoStreamsMap.get(u);if(!d)return;let l=ct(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,f=Math.min(l/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),b=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),g=[...this.audioStreamsMap.keys()].find(({id:k})=>k===b?.id)??this.audioStreamsMap.keys().next().value,y=0;if(g){if(n&&!r)if(this.params.tuning.useSeparateAudioVideoABR){let k=Ya(n,d,this.audioStreamsMap.get(g)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,k?.bitrate??-1/0)}else{let k=rs(n,d,this.audioStreamsMap.get(g)??[]);y=Math.max(y,k?.bitrate??-1/0)}if(o)if(this.params.tuning.useSeparateAudioVideoABR){let k=Ya(o,d,this.audioStreamsMap.get(g)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,k?.bitrate??-1/0)}else{let k=rs(o,d,this.audioStreamsMap.get(g)??[]);y=Math.max(y,k?.bitrate??-1/0)}}let E=xt(d,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:y,forwardBufferHealth:f,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),M=r?E??n:n??E,x;this.params.tuning.useSeparateAudioVideoABR?x=g&&zh(M,d,this.audioStreamsMap.get(g)??[],{throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:f,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}):x=g&&rs(M,d,this.audioStreamsMap.get(g)??[]);let T=this.videoTracksMap.get(M)?.representation,P=x&&this.audioTracksMap.get(x)?.representation;if(T&&P)return[T,P];if(T&&!P&&this.audioTracksMap.size===0)return[T,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Te(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:q.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Se(this.video),this.tracer.end()}};var qi=class extends Wt{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)}};var Yt=require("@vkontakte/videoplayer-shared");var Ui=class extends Wt{constructor(e){super(e),this.liveOffset=new nt}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((0,Yt.combine)({interval:(0,Yt.interval)(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((0,Yt.combine)({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,Yt.map)(({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 nm=Fe(ja(),1);var j=require("@vkontakte/videoplayer-shared"),We={};var kr=(i,e)=>new j.Observable(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),Hi=class{constructor(e){this.subscription=new j.Subscription;this.videoState=new H("initializing");this.textTracksManager=new De;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),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:(0,j.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,j.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,j.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,j.assertNever)(e)}break;default:(0,j.assertNever)(t)}};this.video=ge(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(oe(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),Se(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:j.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,nm.default)(import("hls.js").then(a=>{e||(We.Hls=a.default,We.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){(0,j.assertNonNullable)(We.Hls,"hls.js not loaded"),this.hls=new We.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,j.assertNonNullable)(We.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=u=>{t.error$.next({id:"HlsJsProvider",category:j.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},a=ye(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(Je(this.video,e.isLooped,r)),this.subscription.add(ve(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ce(this.video,e.playbackRate,a.playbackRateState$,r)),s(Be(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe((0,j.map)(u=>u.to)),this.params.output.playbackState$),this.subscription.add(kr(this.hls,We.Events.ERROR).subscribe(u=>{u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:j.ErrorCategory.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"),A(e.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),A(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(kr(this.hls,We.Events.MANIFEST_PARSED).pipe((0,j.map)(({levels:u})=>u.reduce((d,l)=>{let p=l.name||l.height.toString(10),{width:f,height:b}=l,g=Et(l.attrs.QUALITY??"")??(0,j.videoSizeToQuality)({width:f,height:b});if(!g)return d;let y=l.attrs["FRAME-RATE"]?parseFloat(l.attrs["FRAME-RATE"]):void 0,E={id:p.toString(),quality:g,bitrate:l.bitrate/1e3,size:{width:f,height:b},fps:y};return this.trackLevels.set(p,{track:E,level:l}),d.push(E),d},[]))),t.availableVideoTracks$),s(kr(this.hls,We.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){let d=[];for(let l of u.subtitleTracks){let p=l.name,f=l.attrs.URI||"",b=l.lang;d.push({id:p,url:f,language:b,type:"internal"})}e.internalTextTracks.startTransitionTo(d)}}),s(kr(this.hls,We.Events.LEVEL_LOADING).pipe((0,j.map)(({url:u})=>oe(u))),t.hostname$),s(kr(this.hls,We.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(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:d})=>d===u)?.track,o=kr(this.hls,We.Events.LEVEL_SWITCHED).pipe((0,j.map)(({level:u})=>n(this.hls.levels[u])));o.pipe((0,j.filter)(j.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(It(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),u=>{if((0,j.isNullable)(u))return;let d=this.trackLevels.get(u.id)?.level;if(!d)return;let l=this.hls.levels.indexOf(d),p=this.hls.currentLevel,f=this.hls.levels[p];!f||d.bitrate>f.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=(0,j.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,j.observableFrom)(["init"])).pipe((0,j.debounce)(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 Te(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:j.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState("paused"),A(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"),A(this.params.desiredState.playbackState,"stopped",!0)}};var om="X-Playback-Duration",Ho=async i=>{let e=await lt(i),t=await e.text(),r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return r?parseInt(r,10):e.headers.has(om)?parseInt(e.headers.get(om),10):void 0};var U=require("@vkontakte/videoplayer-shared");var Go=Fe(Pn(),1);var ps=require("@vkontakte/videoplayer-shared");var wx=i=>{let e=null;if(i.QUALITY&&(e=Et(i.QUALITY)),!e&&i.RESOLUTION){let[t,r]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=(0,ps.videoSizeToQuality)({width:t,height:r})}return e??null},Rx=(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,Go.default)(o[1].split(",").map(y=>y.split("="))),d=u.QUALITY??`stream-${u.BANDWIDTH}`,l=wx(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 f=u["FRAME-RATE"]?parseFloat(u["FRAME-RATE"]):void 0,b;if(u.RESOLUTION){let[y,E]=u.RESOLUTION.split("x").map(M=>parseInt(M,10));y&&E&&(b={width:y,height:E})}let g=new URL(t[++s],e).toString();l&&r.push({id:d,quality:l,url:g,bandwidth:p,size:b,fps:f})}if(c){let u=(0,Go.default)(c[1].split(",").map(f=>f.split("=")).map(([f,b])=>[f,b.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}},$x=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),jo=0,um=async(i,e=i,t)=>{let a=await(await lt(i)).text();jo+=1;try{let{qualityManifests:s,textTracks:n}=Rx(a,e);return{qualityManifests:s,textTracks:n}}catch{if(jo<=t.manifestRetryMaxCount)return await $x((0,ps.getExponentialDelay)(jo-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),um(i,e,t)}return{qualityManifests:[],textTracks:[]}},hs=um;var ji=class{constructor(e){this.subscription=new U.Subscription;this.videoState=new H("stopped");this.textTracksManager=new De;this.manifests$=new U.ValueSubject([]);this.liveOffset=new nt;this.manifestStartTime$=new U.ValueSubject(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"),A(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"?A(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),A(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"&&A(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"&&(A(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,U.assertNever)(t)}};this.params=e,this.video=ge(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:U.VideoQuality.INVARIANT,url:this.params.source.url},hs(le(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:U.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:U.ErrorCategory.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(oe(this.params.source.url)),this.maxSeekBackTime$=new U.ValueSubject(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:U.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=ye(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(ve(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ce(this.video,t.playbackRate,a.playbackRateState$,r)),s(Be(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),A(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((0,U.filterChanged)(),(0,U.map)(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&&(0,U.isNonNullable)(u.to)){let l=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let p=this.manifests$.getValue().find(f=>f.id===l);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(oe(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((0,U.combine)({startTime:this.manifestStartTime$.pipe((0,U.filter)(U.isNonNullable)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:c})=>this.params.output.liveTime$.next(o+c*1e3),r)),this.subscription.add(this.manifests$.pipe((0,U.map)(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=(0,U.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,U.observableFrom)(["init"])).pipe((0,U.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Se(this.video)}prepare(){let e=this.selectManifest();if((0,U.isNullable)(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=le(a.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),Ho(n).then(o=>{if(!(0,U.isNullable)(o))this.maxSeekBackTime$.next(o);else{let c=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if((0,U.isNullable)(c)||!isFinite(c))try{lt(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();Ho(l).then(p=>{(0,U.isNullable)(p)||this.maxSeekBackTime$.next(p)})}})}catch{}}})}playIfAllowed(){Te(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:U.ErrorCategory.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()}};var W=require("@vkontakte/videoplayer-shared");var Gi=class{constructor(e){this.subscription=new W.Subscription;this.videoState=new H("stopped");this.textTracksManager=new De;this.manifests$=new W.ValueSubject([]);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"),A(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"?A(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),A(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"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):a?.to==="paused"&&A(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,W.assertNever)(t)}};this.params=e,this.video=ge(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:W.VideoQuality.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(oe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),hs(le(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:W.ErrorCategory.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:W.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},a=ye(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((0,W.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Je(this.video,t.isLooped,r)),this.subscription.add(ve(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ce(this.video,t.playbackRate,a.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),A(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&&(0,W.isNonNullable)(u.to)){let l=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let p=this.manifests$.getValue().find(f=>f.id===l);if(p){this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(oe(p.url));let f=this.params.desiredState.playbackRate.getState(),b=this.params.output.element$.getValue()?.playbackRate;if(f!==b){let g=this.params.output.element$.getValue();g&&(this.params.desiredState.playbackRate.setState(f),g.playbackRate=f)}}}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((0,W.map)(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)),!W.clientChecker.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,W.merge)((0,W.fromEvent)(o,"addtrack"),(0,W.fromEvent)(o,"removetrack"),(0,W.fromEvent)(o,"change"),(0,W.observableFrom)(["init"])).subscribe(()=>{for(let c=0;c<o.length;c++)o[c].mode="hidden"},r))}let n=(0,W.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,W.observableFrom)(["init"])).pipe((0,W.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Se(this.video)}prepare(){let e=this.selectManifest();if((0,W.isNullable)(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(){Te(this.video).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:W.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var J=require("@vkontakte/videoplayer-shared");var Wi=class{constructor(e){this.subscription=new J.Subscription;this.videoState=new H("stopped");this.trackUrls={};this.textTracksManager=new De;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"),A(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"?A(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),A(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"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return(0,J.assertNever)(e)}};this.params=e,this.video=ge(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:J.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},a=ye(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((0,J.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Je(this.video,t.isLooped,r)),this.subscription.add(ve(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ce(this.video,t.playbackRate,a.playbackRateState$,r)),s(Be(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),A(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&&(0,J.isNonNullable)(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=(0,J.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,J.observableFrom)(["init"])).pipe((0,J.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Se(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;(0,J.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,J.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Oi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(oe(t))}playIfAllowed(){Te(this.video).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:J.ErrorCategory.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=>!(0,J.isInvariantQuality)(o.track.quality)&&(0,J.isLowerOrEqual)(o.track.quality,e))?.track,s=this.params.desiredState.videoTrack.getState()?.id,n=this.trackUrls[s??"0"]?.track;if(a&&n&&(0,J.isHigherOrEqual)(n.quality,a.quality)&&(t=a),!t){let o=Object.values(this.trackUrls).filter(u=>!(0,J.isInvariantQuality)(u.track.quality)&&(0,J.isHigher)(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=xt(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})}};var Z=require("@vkontakte/videoplayer-shared");var lm=require("@vkontakte/videoplayer-shared"),cm=["stun:videostun.mycdn.me:80"],Lx=1e3,Mx=3,Wo=()=>null,fs=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=Wo;this.externalStopCallback=Wo;this.externalErrorCallback=Wo;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:cm}]};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:lm.ErrorCategory.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),Lx)}normalizeOptions(e={}){let t={stunServerList:cm,maxRetryNumber:Mx,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Yi=class{constructor(e){this.videoState=new H("stopped");this.maxSeekBackTime$=new Z.ValueSubject(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"),A(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"),A(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"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return(0,Z.assertNever)(e)}};this.subscription=new Z.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ge(e.container,e.tuning),this.liveStreamClient=new fs(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Se(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Z.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};(0,Z.merge)(this.videoState.stateChangeStarted$.pipe((0,Z.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,Z.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=ye(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(Be(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(ve(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(0,Z.assertNever)(n.to)}},r)).add((0,Z.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,Z.observableFrom)(["init"])).pipe((0,Z.debounce)(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(oe(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:Z.VideoQuality.INVARIANT}),this.video.srcObject=e,A(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:Z.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Te(this.video).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Z.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Qi=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}};var v=require("@vkontakte/videoplayer-shared");var mt=require("@vkontakte/videoplayer-shared"),dm=i=>new mt.Observable(e=>{let t=new mt.Subscription,r=i.desiredPlaybackState$.stateChangeStarted$.pipe((0,mt.map)(({from:u,to:d})=>`${u}-${d}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe((0,mt.map)(({type:u})=>u!==void 0)),n=new mt.Subject,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()}});var Re=require("@vkontakte/videoplayer-shared");var zi=null,ms=null;function Yo(){return zi||(zi=new(window.AudioContext||window.webkitAudioContext)),ms||(ms=new GainNode(zi,{gain:1}),ms.connect(zi.destination)),{audioCtx:zi,gainNode:ms}}var pm=require("@vkontakte/videoplayer-shared");var Ki=class i{constructor(e,t,r,a,s){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=a;this.subscriptions=new Re.Subscription;this.lastAudioContextResumeId=0;!s||!this.isSupported()||a===1||this.subscriptions.add(this.provider$.pipe((0,Re.filter)(n=>!!n.type),(0,Re.once)()).subscribe(({type:n})=>this.subscribe(n)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){pm.clientChecker.isSafari&&e!=="MPEG"||this.subscriptions.add((0,Re.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,Re.filter)(({playbackState:t,video:r,volume:{muted:a,volume:s}})=>t==="playing"&&!!r&&!a&&!!s),(0,Re.once)()).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}=Yo(),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:Re.ErrorCategory.VIDEO_PIPELINE,message:n?.message??"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:n})}}).catch(n=>{this.volumeMultiplierError$.next({id:i.errorId,category:Re.ErrorCategory.VIDEO_PIPELINE,message:n?.message??"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){let{gainNode:e}=Yo();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};var Cx={chunkDuration:5e3,maxParallelRequests:5},Ji=class{constructor(e){this.current$=new v.ValueSubject({type:void 0});this.providerError$=new v.Subject;this.noAvailableProvidersError$=new v.Subject;this.volumeMultiplierError$=new v.Subject;this.providerOutput={position$:new v.ValueSubject(0),duration$:new v.ValueSubject(1/0),volume$:new v.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new v.ValueSubject([]),currentVideoStream$:new v.ValueSubject(void 0),availableVideoTracks$:new v.ValueSubject([]),currentVideoTrack$:new v.ValueSubject(void 0),availableAudioStreams$:new v.ValueSubject([]),currentAudioStream$:new v.ValueSubject(void 0),availableAudioTracks$:new v.ValueSubject([]),currentVideoSegmentLength$:new v.ValueSubject(0),currentAudioSegmentLength$:new v.ValueSubject(0),isAudioAvailable$:new v.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new v.ValueSubject(!1),autoVideoTrackLimits$:new v.ValueSubject(void 0),currentBuffer$:new v.ValueSubject(void 0),isBuffering$:new v.ValueSubject(!0),error$:new v.Subject,warning$:new v.Subject,willSeekEvent$:new v.Subject,seekedEvent$:new v.Subject,loopedEvent$:new v.Subject,endedEvent$:new v.Subject,firstBytesEvent$:new v.Subject,loadedMetadataEvent$:new v.Subject,firstFrameEvent$:new v.Subject,canplay$:new v.Subject,isLive$:new v.ValueSubject(void 0),isLowLatency$:new v.ValueSubject(!1),canChangePlaybackSpeed$:new v.ValueSubject(!0),liveTime$:new v.ValueSubject(void 0),liveBufferTime$:new v.ValueSubject(void 0),availableTextTracks$:new v.ValueSubject([]),currentTextTrack$:new v.ValueSubject(void 0),hostname$:new v.ValueSubject(void 0),httpConnectionType$:new v.ValueSubject(void 0),httpConnectionReused$:new v.ValueSubject(void 0),inPiP$:new v.ValueSubject(!1),inFullscreen$:new v.ValueSubject(!1),element$:new v.ValueSubject(void 0),elementVisible$:new v.ValueSubject(!0),availableSources$:new v.ValueSubject(void 0),is3DVideo$:new v.ValueSubject(!1),playbackState$:new v.ValueSubject("")};this.subscription=new v.Subscription;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=uf([...lf(this.params.tuning),...cf(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>(0,v.isNonNullable)(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",(0,v.flattenObject)(s)),this.screenFormatsIterator=new Qi(s);let n=[...Ao(!0),...Ao(!1)];this.chromecastFormatsIterator=new Qi(n.filter(o=>(0,v.isNonNullable)(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new Ki(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((0,v.isNullable)(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:v.ErrorCategory.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(0,v.assertNever)(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(0,v.assertNonNullable)(o),new qi({...n,source:o,sourceHls:c})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new Ui({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),vr||!this.params.tuning.useHlsJs?new Gi({...n,source:o}):new Hi({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new ji({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new Wi({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new Zh({...n,source:o,config:{...Cx,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new Yi({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(0,v.assertNever)(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(0,v.assertNonNullable)(o),new ri({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(0,v.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,v.assertNever)(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(0,v.assertNever)(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,hm.default)(Object.entries(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new v.Subscription,t=!1,r=0;return e.add((0,v.merge)(this.providerOutput.error$,dm({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,v.map)(a=>({id:`ProviderHangup:${a}`,category:v.ErrorCategory.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((0,v.filter)(({to:s})=>s==="playing"),(0,v.once)()).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===v.ErrorCategory.NETWORK,c=a.category===v.ErrorCategory.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",(0,v.flattenObject)(n))})),e}};var _=require("@vkontakte/videoplayer-shared");var Dx=5e3,fm="one_video_throughput",mm="one_video_rtt",Xi=window.navigator.connection,bm=()=>{let i=Xi?.downlink;if((0,_.isNonNullable)(i)&&i!==10)return i*1e3},gm=()=>{let i=Xi?.rtt;if((0,_.isNonNullable)(i)&&i!==3e3)return i},Sm=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},Qo=class i{constructor(e){this.subscription=new _.Subscription;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=i.load(fm)||(e.useBrowserEstimation?bm():void 0)||Dx,r=i.load(mm)??(e.useBrowserEstimation?gm():void 0)??0;if(this.throughput$=new _.ValueSubject(t),this.rtt$=new _.ValueSubject(r),this.rttAdjustedThroughput$=new _.ValueSubject(Sm(t,r,e.rttPenaltyRequestSize)),this.throughput=Gt.getSmoothedValue(t,-1,e),this.rtt=Gt.getSmoothedValue(r,1,e),e.useBrowserEstimation){let a=()=>{let n=bm();n&&this.throughput.next(n);let o=gm();(0,_.isNonNullable)(o)&&this.rtt.next(o)};Xi&&"onchange"in Xi&&this.subscription.add((0,_.fromEvent)(Xi,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{_.safeStorage.set(fm,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{_.safeStorage.set(mm,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,_.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,_.map)(({throughput:a,rtt:s})=>Sm(a,s,e.rttPenaltyRequestSize)),(0,_.filter)(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=(0,_.now)(),a=new _.Subscription;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add((0,_.fromEvent)(e,"progress").pipe((0,_.once)()).subscribe(s=>{t=s.loaded,r=(0,_.now)()}));break;case 1:case 0:a.add((0,_.fromEvent)(e,"loadstart").subscribe(()=>{t=0,r=(0,_.now)()}));break}a.add((0,_.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,_.now)(),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=(0,_.now)(),n=0,o=(0,_.now)(),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,(0,_.now)()-s,1),this.concurrentDownloads.delete(e);else if(l){if(t){let p=(0,_.now)();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=l.byteLength,s=(0,_.now)()}else n+=l.byteLength;o=(0,_.now)()}else a+=l.byteLength,n+=l.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,_.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,_.now)()-o,this.concurrentDownloads.size),n=0,o=(0,_.now)());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=_.safeStorage.get(e);if((0,_.isNonNullable)(t))return parseInt(t,10)??void 0}},vm=Qo;var Zi=require("@vkontakte/videoplayer-shared"),ym={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:Zi.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Zi.VideoQuality.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},Tm=i=>({...(0,Zi.fillWithDefault)(i,ym),configName:[...i.configName??[],...ym.configName]});var h=require("@vkontakte/videoplayer-shared");var bt=require("@vkontakte/videoplayer-shared"),zo=({seekState:i,position$:e})=>(0,bt.merge)(i.stateChangeEnded$.pipe((0,bt.map)(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),(0,bt.filter)(bt.isNonNullable)),e.pipe((0,bt.filter)(()=>i.getState().state==="none")));var Im=require("@vkontakte/videoplayer-shared"),Em=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return(0,Im.assertNonNullable)(e,`Wrong container or containerId {${i.container}}`),e};var bs=require("@vkontakte/videoplayer-shared"),xm=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe((0,bs.filter)(a=>a.length>0),(0,bs.once)()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t?.getValue().find(r))&&e.startTransitionTo(i)};var ea=class{constructor(e={configName:[]},t){this.subscription=new h.Subscription;this.logger=new h.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new h.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new H("stopped"),seekState:new H({state:"none"}),volume:new H({volume:1,muted:!1}),videoTrack:new H(void 0),videoStream:new H(void 0),audioStream:new H(void 0),autoVideoTrackSwitching:new H(!0),autoVideoTrackLimits:new H({}),isLooped:new H(!1),playbackRate:new H(1),externalTextTracks:new H([]),internalTextTracks:new H([]),currentTextTrack:new H(void 0),textTrackCuesSettings:new H({}),cameraOrientation:new H({x:0,y:0})};this.info={playbackState$:new h.ValueSubject("stopped"),position$:new h.ValueSubject(0),duration$:new h.ValueSubject(1/0),muted$:new h.ValueSubject(!1),volume$:new h.ValueSubject(1),availableVideoStreams$:new h.ValueSubject([]),currentVideoStream$:new h.ValueSubject(void 0),availableQualities$:new h.ValueSubject([]),availableQualitiesFps$:new h.ValueSubject({}),currentQuality$:new h.ValueSubject(void 0),isAutoQualityEnabled$:new h.ValueSubject(!0),autoQualityLimitingAvailable$:new h.ValueSubject(!1),autoQualityLimits$:new h.ValueSubject({}),availableAudioStreams$:new h.ValueSubject([]),currentAudioStream$:new h.ValueSubject(void 0),availableAudioTracks$:new h.ValueSubject([]),isAudioAvailable$:new h.ValueSubject(!0),currentPlaybackRate$:new h.ValueSubject(1),currentBuffer$:new h.ValueSubject({start:0,end:0}),isBuffering$:new h.ValueSubject(!0),isStalled$:new h.ValueSubject(!1),isEnded$:new h.ValueSubject(!1),isLooped$:new h.ValueSubject(!1),isLive$:new h.ValueSubject(void 0),canChangePlaybackSpeed$:new h.ValueSubject(void 0),atLiveEdge$:new h.ValueSubject(void 0),atLiveDurationEdge$:new h.ValueSubject(void 0),liveTime$:new h.ValueSubject(void 0),liveBufferTime$:new h.ValueSubject(void 0),currentFormat$:new h.ValueSubject(void 0),availableTextTracks$:new h.ValueSubject([]),currentTextTrack$:new h.ValueSubject(void 0),throughputEstimation$:new h.ValueSubject(void 0),rttEstimation$:new h.ValueSubject(void 0),videoBitrate$:new h.ValueSubject(void 0),hostname$:new h.ValueSubject(void 0),httpConnectionType$:new h.ValueSubject(void 0),httpConnectionReused$:new h.ValueSubject(void 0),surface$:new h.ValueSubject("none"),chromecastState$:new h.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new h.ValueSubject(void 0),intrinsicVideoSize$:new h.ValueSubject(void 0),availableSources$:new h.ValueSubject(void 0),is3DVideo$:new h.ValueSubject(!1),currentVideoSegmentLength$:new h.ValueSubject(0),currentAudioSegmentLength$:new h.ValueSubject(0)};this.events={inited$:new h.Subject,ready$:new h.Subject,started$:new h.Subject,playing$:new h.Subject,paused$:new h.Subject,stopped$:new h.Subject,willStart$:new h.Subject,willResume$:new h.Subject,willPause$:new h.Subject,willStop$:new h.Subject,willDestruct$:new h.Subject,watchCoverageRecord$:new h.Subject,watchCoverageLive$:new h.Subject,managedError$:new h.Subject,fatalError$:new h.Subject,ended$:new h.Subject,looped$:new h.Subject,seeked$:new h.Subject,willSeek$:new h.Subject,firstBytes$:new h.Subject,loadedMetadata$:new h.Subject,firstFrame$:new h.Subject,canplay$:new h.Subject,log$:new h.Subject};this.experimental={element$:new h.ValueSubject(void 0),tuningConfigName$:new h.ValueSubject([]),enableDebugTelemetry$:new h.ValueSubject(!1),dumpTelemetry:jh};if(this.initLogs(),this.tuning=Tm(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ca({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new vm(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,(f,b)=>{let g=typeof b;return["number","string","boolean"].includes(g)?b:b===null?null:`<${g}>`})),d=`Player.${String(a)}`,l=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:h.ErrorCategory.WTF,message:l,thrown:c}),c}}}})}initVideo(e){return this.config=e,this.tracer.log("initVideo",(0,h.flattenObject)(e)),this.domContainer=Em(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Ji({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"),(0,h.fromEvent)(document,"visibilitychange").pipe((0,h.once)()).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){(0,h.assertNonNullable)(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((0,h.filter)(r=>r.length>0),(0,h.once)()).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",(0,h.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){(0,h.assertNonNullable)(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",(0,h.flattenObject)(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return xm(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((0,h.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return(0,h.isNonNullable)(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((0,h.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,h.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,h.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,h.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,h.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,h.map)(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,h.filter)(({from:e})=>e==="stopped"),(0,h.once)()).subscribe(()=>{this.initedAt=(0,h.now)(),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",(0,h.flattenObject)(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:h.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",(0,h.flattenObject)(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,h.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,h.map)(n=>n.destination),(0,h.filterChanged)()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe((0,h.map)(n=>n.map(({quality:o})=>o).sort((o,c)=>(0,h.isInvariantQuality)(o)?1:(0,h.isInvariantQuality)(c)?-1:(0,h.isHigher)(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((0,h.filterChanged)()).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((0,h.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe((0,h.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,h.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,h.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,h.filterChanged)()).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((0,h.map)(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((0,h.combine)({hasLiveOffsetByPaused:(0,h.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,h.map)(n=>n.to),(0,h.filterChanged)(),(0,h.map)(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((0,h.combine)({atLiveEdge:(0,h.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:zo({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,h.map)(({isLive:n,position:o,isLowLatency:c})=>{let u=this.getActiveLiveDelay(c);return n&&Math.abs(o)<u/1e3}),(0,h.filterChanged)(),(0,h.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,h.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,h.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,h.map)(({isLive:n,position:o,duration:c})=>n&&(Math.abs(c)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,h.filterChanged)(),(0,h.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,h.map)(n=>n.muted),(0,h.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,h.map)(n=>n.volume),(0,h.filterChanged)()).subscribe(this.info.volume$)).add(zo({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,h.merge)(e.providerOutput.endedEvent$.pipe((0,h.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,h.mapTo)(!1))).pipe((0,h.filterChanged)()).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((0,h.map)(n=>({id:n?`No${n}`:"NoProviders",category:h.ErrorCategory.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((0,h.once)(),(0,h.map)(n=>n??(0,h.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,h.once)(),(0,h.map)(()=>(0,h.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,h.once)(),(0,h.map)(()=>(0,h.now)()-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 h.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new h.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,h.filter)(({to:n})=>n==="playing"),(0,h.once)()).subscribe(()=>r.next(!1)));let a=0,s=(0,h.merge)(e.providerOutput.isBuffering$,t,r).pipe((0,h.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),(0,h.filterChanged)());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((0,h.merge)(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((0,h.merge)(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((0,h.map)(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new h.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,h.filterChanged)((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,h.filter)(r=>r.length>0),(0,h.once)()).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=xt(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((0,h.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,h.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,h.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,h.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,h.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,h.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,h.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,h.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,h.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,h.map)(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;(0,h.assertNonNullable)(this.providerContainer),(0,h.assertNonNullable)(e),Hh(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Uh(t)),this.providerContainer.current$.subscribe(({type:t})=>ai("provider",t)),e.duration$.subscribe(t=>ai("duration",t)),e.availableVideoTracks$.pipe((0,h.filter)(t=>!!t.length),(0,h.once)()).subscribe(t=>ai("tracks",t)),this.events.fatalError$.subscribe(new he("fatalError")),this.events.managedError$.subscribe(new he("managedError")),e.position$.subscribe(new he("position")),e.currentVideoTrack$.pipe((0,h.map)(t=>t?.quality)).subscribe(new he("quality")),this.info.currentBuffer$.subscribe(new he("buffer")),e.isBuffering$.subscribe(new he("isBuffering"))].forEach(t=>this.subscription.add(t)),ai("codecs",of())}initTracerSubscription(){let e=(0,h.getTraceSubscriptionMethod)(this.tracer.log.bind(this.tracer)),t=(0,h.getTraceSubscriptionMethod)(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((0,h.filterChanged)()).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((0,h.combine)({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe((0,h.filter)(({currentQuality:r,videoBitrate:a})=>!!r&&!!a),(0,h.filterChanged)((r,a)=>r.currentQuality===a.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,h.filter)(r=>r>0),(0,h.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,h.filter)(r=>r>0),(0,h.filterChanged)()).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((0,h.combine)({currentBuffer:this.info.currentBuffer$.pipe((0,h.filter)(r=>r.end>0),(0,h.filterChanged)((r,a)=>r.end===a.end&&r.start===a.start)),position:this.info.position$.pipe((0,h.filterChanged)())}).pipe((0,h.throttle)(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe((0,h.filterChanged)()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe((0,h.filterChanged)()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe((0,h.filterChanged)()).subscribe(e("canChangePlaybackSpeed"))).add((0,h.combine)({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe((0,h.filter)(({liveTime:r,liveBufferTime:a})=>!!r&&!!a),(0,h.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,h.filterChanged)(),(0,h.filter)(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,h.filterChanged)(),(0,h.filter)(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe((0,h.filterChanged)()).subscribe(e("muted"))).add(this.info.volume$.pipe((0,h.filterChanged)()).subscribe(e("volume"))).add(this.info.isEnded$.pipe((0,h.filterChanged)(),(0,h.filter)(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add((0,h.combine)({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe((0,h.filter)(({throughputEstimation:r,rtt:a})=>!!r&&!!a),(0,h.throttle)(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe((0,h.filterChanged)(),(0,h.filter)(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:h.ErrorCategory.DOM,message:String(a)})})};this.subscription.add((0,h.merge)((0,h.fromEvent)(document,"visibilitychange"),(0,h.fromEvent)(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",(0,h.flattenObject)({quality:t,availableTracks:(0,h.flattenObject)(e),track:(0,h.flattenObject)(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}};var et=require("@vkontakte/videoplayer-shared"),Bx=`@vkontakte/videoplayer-core@${xs}`;