@vkontakte/videoplayer-core 2.0.104-dev.7ccfc328.0 → 2.0.105-dev.27e8f5c9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +10 -10
- package/es2015.esm.js +13 -13
- package/es2018.cjs.js +12 -12
- package/es2018.esm.js +14 -14
- package/esnext.cjs.js +8 -8
- package/esnext.esm.js +9 -9
- package/evergreen.esm.js +9 -9
- package/package.json +1 -1
- package/types/player/types.d.ts +1 -0
- package/types/providers/ProviderContainer/index.d.ts +2 -0
- package/types/utils/VolumeMultiplierManager/VolumeMultiplierManager.d.ts +9 -0
- package/types/utils/VolumeMultiplierManager/audioContext.d.ts +9 -0
- package/types/utils/VolumeMultiplierManager/index.d.ts +1 -0
- package/types/utils/tuningConfig.d.ts +1 -0
package/esnext.cjs.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.105-dev.27e8f5c9.0
|
|
3
|
+
* Wed, 26 Jun 2024 08:17:33 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-105/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var rm=Object.create;var ji=Object.defineProperty;var im=Object.getOwnPropertyDescriptor;var am=Object.getOwnPropertyNames;var sm=Object.getPrototypeOf,nm=Object.prototype.hasOwnProperty;var m=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),om=(i,e)=>{for(var t in e)ji(i,t,{get:e[t],enumerable:!0})},Lo=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of am(e))!nm.call(i,a)&&a!==t&&ji(i,a,{get:()=>e[a],enumerable:!(r=im(e,a))||r.enumerable});return i};var _e=(i,e,t)=>(t=i!=null?rm(sm(i)):{},Lo(e||!i||!i.__esModule?ji(t,"default",{value:i,enumerable:!0}):t,i)),um=i=>Lo(ji({},"__esModule",{value:!0}),i);var Pe=m((Px,Co)=>{"use strict";Co.exports=function(i){try{return!!i()}catch{return!0}}});var Pr=m((kx,Do)=>{"use strict";var cm=Pe();Do.exports=!cm(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var fe=m((wx,Bo)=>{"use strict";var Mo=Pr(),Oo=Function.prototype,cs=Oo.call,dm=Mo&&Oo.bind.bind(cs,cs);Bo.exports=Mo?dm:function(i){return function(){return cs.apply(i,arguments)}}});var Jt=m((Ax,_o)=>{"use strict";var Vo=fe(),pm=Vo({}.toString),hm=Vo("".slice);_o.exports=function(i){return hm(pm(i),8,-1)}});var Fo=m((Rx,No)=>{"use strict";var fm=fe(),mm=Pe(),bm=Jt(),ds=Object,gm=fm("".split);No.exports=mm(function(){return!ds("z").propertyIsEnumerable(0)})?function(i){return bm(i)=="String"?gm(i,""):ds(i)}:ds});var Xt=m((Lx,qo)=>{"use strict";qo.exports=function(i){return i==null}});var Qi=m(($x,Uo)=>{"use strict";var vm=Xt(),Sm=TypeError;Uo.exports=function(i){if(vm(i))throw Sm("Can't call method on "+i);return i}});var Zt=m((Cx,Ho)=>{"use strict";var ym=Fo(),Tm=Qi();Ho.exports=function(i){return ym(Tm(i))}});var ps=m((Dx,jo)=>{"use strict";jo.exports=function(){}});var Rt=m((Mx,Go)=>{"use strict";Go.exports={}});var ne=m((Yo,Wo)=>{"use strict";var zi=function(i){return i&&i.Math==Math&&i};Wo.exports=zi(typeof globalThis=="object"&&globalThis)||zi(typeof window=="object"&&window)||zi(typeof self=="object"&&self)||zi(typeof global=="object"&&global)||function(){return this}()||Yo||Function("return this")()});var fs=m((Ox,Qo)=>{"use strict";var hs=typeof document=="object"&&document.all,Im=typeof hs>"u"&&hs!==void 0;Qo.exports={all:hs,IS_HTMLDDA:Im}});var ee=m((Bx,Ko)=>{"use strict";var zo=fs(),Em=zo.all;Ko.exports=zo.IS_HTMLDDA?function(i){return typeof i=="function"||i===Em}:function(i){return typeof i=="function"}});var Zo=m((Vx,Xo)=>{"use strict";var xm=ne(),Pm=ee(),Jo=xm.WeakMap;Xo.exports=Pm(Jo)&&/native code/.test(String(Jo))});var Qe=m((_x,ru)=>{"use strict";var eu=ee(),tu=fs(),km=tu.all;ru.exports=tu.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:eu(i)||i===km}:function(i){return typeof i=="object"?i!==null:eu(i)}});var ze=m((Nx,iu)=>{"use strict";var wm=Pe();iu.exports=!wm(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7})});var Ki=m((Fx,su)=>{"use strict";var Am=ne(),au=Qe(),ms=Am.document,Rm=au(ms)&&au(ms.createElement);su.exports=function(i){return Rm?ms.createElement(i):{}}});var bs=m((qx,nu)=>{"use strict";var Lm=ze(),$m=Pe(),Cm=Ki();nu.exports=!Lm&&!$m(function(){return Object.defineProperty(Cm("div"),"a",{get:function(){return 7}}).a!=7})});var gs=m((Ux,ou)=>{"use strict";var Dm=ze(),Mm=Pe();ou.exports=Dm&&Mm(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42})});var Ne=m((Hx,uu)=>{"use strict";var Om=Qe(),Bm=String,Vm=TypeError;uu.exports=function(i){if(Om(i))return i;throw Vm(Bm(i)+" is not an object")}});var me=m((jx,lu)=>{"use strict";var _m=Pr(),Ji=Function.prototype.call;lu.exports=_m?Ji.bind(Ji):function(){return Ji.apply(Ji,arguments)}});var Xi=m((Gx,cu)=>{"use strict";cu.exports={}});var rt=m((Yx,pu)=>{"use strict";var vs=Xi(),Ss=ne(),Nm=ee(),du=function(i){return Nm(i)?i:void 0};pu.exports=function(i,e){return arguments.length<2?du(vs[i])||du(Ss[i]):vs[i]&&vs[i][e]||Ss[i]&&Ss[i][e]}});var kr=m((Wx,hu)=>{"use strict";var Fm=fe();hu.exports=Fm({}.isPrototypeOf)});var wr=m((Qx,fu)=>{"use strict";fu.exports=typeof navigator<"u"&&String(navigator.userAgent)||""});var Ts=m((zx,yu)=>{"use strict";var Su=ne(),ys=wr(),mu=Su.process,bu=Su.Deno,gu=mu&&mu.versions||bu&&bu.version,vu=gu&&gu.v8,Fe,Zi;vu&&(Fe=vu.split("."),Zi=Fe[0]>0&&Fe[0]<4?1:+(Fe[0]+Fe[1]));!Zi&&ys&&(Fe=ys.match(/Edge\/(\d+)/),(!Fe||Fe[1]>=74)&&(Fe=ys.match(/Chrome\/(\d+)/),Fe&&(Zi=+Fe[1])));yu.exports=Zi});var Is=m((Kx,Iu)=>{"use strict";var Tu=Ts(),qm=Pe(),Um=ne(),Hm=Um.String;Iu.exports=!!Object.getOwnPropertySymbols&&!qm(function(){var i=Symbol();return!Hm(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&Tu&&Tu<41})});var Es=m((Jx,Eu)=>{"use strict";var jm=Is();Eu.exports=jm&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var xs=m((Xx,xu)=>{"use strict";var Gm=rt(),Ym=ee(),Wm=kr(),Qm=Es(),zm=Object;xu.exports=Qm?function(i){return typeof i=="symbol"}:function(i){var e=Gm("Symbol");return Ym(e)&&Wm(e.prototype,zm(i))}});var Ar=m((Zx,Pu)=>{"use strict";var Km=String;Pu.exports=function(i){try{return Km(i)}catch{return"Object"}}});var it=m((eP,ku)=>{"use strict";var Jm=ee(),Xm=Ar(),Zm=TypeError;ku.exports=function(i){if(Jm(i))return i;throw Zm(Xm(i)+" is not a function")}});var Rr=m((tP,wu)=>{"use strict";var eb=it(),tb=Xt();wu.exports=function(i,e){var t=i[e];return tb(t)?void 0:eb(t)}});var Ru=m((rP,Au)=>{"use strict";var Ps=me(),ks=ee(),ws=Qe(),rb=TypeError;Au.exports=function(i,e){var t,r;if(e==="string"&&ks(t=i.toString)&&!ws(r=Ps(t,i))||ks(t=i.valueOf)&&!ws(r=Ps(t,i))||e!=="string"&&ks(t=i.toString)&&!ws(r=Ps(t,i)))return r;throw rb("Can't convert object to primitive value")}});var qe=m((iP,Lu)=>{"use strict";Lu.exports=!0});var Du=m((aP,Cu)=>{"use strict";var $u=ne(),ib=Object.defineProperty;Cu.exports=function(i,e){try{ib($u,i,{value:e,configurable:!0,writable:!0})}catch{$u[i]=e}return e}});var ea=m((sP,Ou)=>{"use strict";var ab=ne(),sb=Du(),Mu="__core-js_shared__",nb=ab[Mu]||sb(Mu,{});Ou.exports=nb});var As=m((nP,Vu)=>{"use strict";var ob=qe(),Bu=ea();(Vu.exports=function(i,e){return Bu[i]||(Bu[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:ob?"pure":"global",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Lr=m((oP,_u)=>{"use strict";var ub=Qi(),lb=Object;_u.exports=function(i){return lb(ub(i))}});var Ue=m((uP,Nu)=>{"use strict";var cb=fe(),db=Lr(),pb=cb({}.hasOwnProperty);Nu.exports=Object.hasOwn||function(e,t){return pb(db(e),t)}});var Rs=m((lP,Fu)=>{"use strict";var hb=fe(),fb=0,mb=Math.random(),bb=hb(1 .toString);Fu.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+bb(++fb+mb,36)}});var ce=m((cP,Uu)=>{"use strict";var gb=ne(),vb=As(),qu=Ue(),Sb=Rs(),yb=Is(),Tb=Es(),er=gb.Symbol,Ls=vb("wks"),Ib=Tb?er.for||er:er&&er.withoutSetter||Sb;Uu.exports=function(i){return qu(Ls,i)||(Ls[i]=yb&&qu(er,i)?er[i]:Ib("Symbol."+i)),Ls[i]}});var Yu=m((dP,Gu)=>{"use strict";var Eb=me(),Hu=Qe(),ju=xs(),xb=Rr(),Pb=Ru(),kb=ce(),wb=TypeError,Ab=kb("toPrimitive");Gu.exports=function(i,e){if(!Hu(i)||ju(i))return i;var t=xb(i,Ab),r;if(t){if(e===void 0&&(e="default"),r=Eb(t,i,e),!Hu(r)||ju(r))return r;throw wb("Can't convert object to primitive value")}return e===void 0&&(e="number"),Pb(i,e)}});var ta=m((pP,Wu)=>{"use strict";var Rb=Yu(),Lb=xs();Wu.exports=function(i){var e=Rb(i,"string");return Lb(e)?e:e+""}});var Lt=m(zu=>{"use strict";var $b=ze(),Cb=bs(),Db=gs(),ra=Ne(),Qu=ta(),Mb=TypeError,$s=Object.defineProperty,Ob=Object.getOwnPropertyDescriptor,Cs="enumerable",Ds="configurable",Ms="writable";zu.f=$b?Db?function(e,t,r){if(ra(e),t=Qu(t),ra(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Ms in r&&!r[Ms]){var a=Ob(e,t);a&&a[Ms]&&(e[t]=r.value,r={configurable:Ds in r?r[Ds]:a[Ds],enumerable:Cs in r?r[Cs]:a[Cs],writable:!1})}return $s(e,t,r)}:$s:function(e,t,r){if(ra(e),t=Qu(t),ra(r),Cb)try{return $s(e,t,r)}catch{}if("get"in r||"set"in r)throw Mb("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var $r=m((fP,Ku)=>{"use strict";Ku.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var $t=m((mP,Ju)=>{"use strict";var Bb=ze(),Vb=Lt(),_b=$r();Ju.exports=Bb?function(i,e,t){return Vb.f(i,e,_b(1,t))}:function(i,e,t){return i[e]=t,i}});var ia=m((bP,Zu)=>{"use strict";var Nb=As(),Fb=Rs(),Xu=Nb("keys");Zu.exports=function(i){return Xu[i]||(Xu[i]=Fb(i))}});var aa=m((gP,el)=>{"use strict";el.exports={}});var _s=m((vP,il)=>{"use strict";var qb=Zo(),rl=ne(),Ub=Qe(),Hb=$t(),Os=Ue(),Bs=ea(),jb=ia(),Gb=aa(),tl="Object already initialized",Vs=rl.TypeError,Yb=rl.WeakMap,sa,Cr,na,Wb=function(i){return na(i)?Cr(i):sa(i,{})},Qb=function(i){return function(e){var t;if(!Ub(e)||(t=Cr(e)).type!==i)throw Vs("Incompatible receiver, "+i+" required");return t}};qb||Bs.state?(He=Bs.state||(Bs.state=new Yb),He.get=He.get,He.has=He.has,He.set=He.set,sa=function(i,e){if(He.has(i))throw Vs(tl);return e.facade=i,He.set(i,e),e},Cr=function(i){return He.get(i)||{}},na=function(i){return He.has(i)}):(Ct=jb("state"),Gb[Ct]=!0,sa=function(i,e){if(Os(i,Ct))throw Vs(tl);return e.facade=i,Hb(i,Ct,e),e},Cr=function(i){return Os(i,Ct)?i[Ct]:{}},na=function(i){return Os(i,Ct)});var He,Ct;il.exports={set:sa,get:Cr,has:na,enforce:Wb,getterFor:Qb}});var Ns=m((SP,ol)=>{"use strict";var zb=Pr(),nl=Function.prototype,al=nl.apply,sl=nl.call;ol.exports=typeof Reflect=="object"&&Reflect.apply||(zb?sl.bind(al):function(){return sl.apply(al,arguments)})});var Fs=m((yP,ul)=>{"use strict";var Kb=Jt(),Jb=fe();ul.exports=function(i){if(Kb(i)==="Function")return Jb(i)}});var pl=m(dl=>{"use strict";var ll={}.propertyIsEnumerable,cl=Object.getOwnPropertyDescriptor,Xb=cl&&!ll.call({1:2},1);dl.f=Xb?function(e){var t=cl(this,e);return!!t&&t.enumerable}:ll});var qs=m(fl=>{"use strict";var Zb=ze(),eg=me(),tg=pl(),rg=$r(),ig=Zt(),ag=ta(),sg=Ue(),ng=bs(),hl=Object.getOwnPropertyDescriptor;fl.f=Zb?hl:function(e,t){if(e=ig(e),t=ag(t),ng)try{return hl(e,t)}catch{}if(sg(e,t))return rg(!eg(tg.f,e,t),e[t])}});var Us=m((EP,ml)=>{"use strict";var og=Pe(),ug=ee(),lg=/#|\.prototype\./,Dr=function(i,e){var t=dg[cg(i)];return t==hg?!0:t==pg?!1:ug(e)?og(e):!!e},cg=Dr.normalize=function(i){return String(i).replace(lg,".").toLowerCase()},dg=Dr.data={},pg=Dr.NATIVE="N",hg=Dr.POLYFILL="P";ml.exports=Dr});var Mr=m((xP,gl)=>{"use strict";var bl=Fs(),fg=it(),mg=Pr(),bg=bl(bl.bind);gl.exports=function(i,e){return fg(i),e===void 0?i:mg?bg(i,e):function(){return i.apply(e,arguments)}}});var Ae=m((PP,Sl)=>{"use strict";var oa=ne(),gg=Ns(),vg=Fs(),Sg=ee(),yg=qs().f,Tg=Us(),tr=Xi(),Ig=Mr(),rr=$t(),vl=Ue(),Eg=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 gg(i,this,arguments)};return e.prototype=i.prototype,e};Sl.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?oa:a?oa[t]:(oa[t]||{}).prototype,o=r?tr:tr[t]||rr(tr,t,{})[t],l=o.prototype,u,c,d,f,h,b,I,g,T;for(f in e)u=Tg(r?f:t+(a?".":"#")+f,i.forced),c=!u&&n&&vl(n,f),b=o[f],c&&(i.dontCallGetSet?(T=yg(n,f),I=T&&T.value):I=n[f]),h=c&&I?I:e[f],!(c&&typeof b==typeof h)&&(i.bind&&c?g=Ig(h,oa):i.wrap&&c?g=Eg(h):s&&Sg(h)?g=vg(h):g=h,(i.sham||h&&h.sham||b&&b.sham)&&rr(g,"sham",!0),rr(o,f,g),s&&(d=t+"Prototype",vl(tr,d)||rr(tr,d,{}),rr(tr[d],f,h),i.real&&l&&(u||!l[f])&&rr(l,f,h)))}});var Il=m((kP,Tl)=>{"use strict";var Hs=ze(),xg=Ue(),yl=Function.prototype,Pg=Hs&&Object.getOwnPropertyDescriptor,js=xg(yl,"name"),kg=js&&function(){}.name==="something",wg=js&&(!Hs||Hs&&Pg(yl,"name").configurable);Tl.exports={EXISTS:js,PROPER:kg,CONFIGURABLE:wg}});var xl=m((wP,El)=>{"use strict";var Ag=Math.ceil,Rg=Math.floor;El.exports=Math.trunc||function(e){var t=+e;return(t>0?Rg:Ag)(t)}});var ua=m((AP,Pl)=>{"use strict";var Lg=xl();Pl.exports=function(i){var e=+i;return e!==e||e===0?0:Lg(e)}});var wl=m((RP,kl)=>{"use strict";var $g=ua(),Cg=Math.max,Dg=Math.min;kl.exports=function(i,e){var t=$g(i);return t<0?Cg(t+e,0):Dg(t,e)}});var Rl=m((LP,Al)=>{"use strict";var Mg=ua(),Og=Math.min;Al.exports=function(i){return i>0?Og(Mg(i),9007199254740991):0}});var la=m(($P,Ll)=>{"use strict";var Bg=Rl();Ll.exports=function(i){return Bg(i.length)}});var Dl=m((CP,Cl)=>{"use strict";var Vg=Zt(),_g=wl(),Ng=la(),$l=function(i){return function(e,t,r){var a=Vg(e),s=Ng(a),n=_g(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}};Cl.exports={includes:$l(!0),indexOf:$l(!1)}});var Bl=m((DP,Ol)=>{"use strict";var Fg=fe(),Gs=Ue(),qg=Zt(),Ug=Dl().indexOf,Hg=aa(),Ml=Fg([].push);Ol.exports=function(i,e){var t=qg(i),r=0,a=[],s;for(s in t)!Gs(Hg,s)&&Gs(t,s)&&Ml(a,s);for(;e.length>r;)Gs(t,s=e[r++])&&(~Ug(a,s)||Ml(a,s));return a}});var Ys=m((MP,Vl)=>{"use strict";Vl.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Nl=m((OP,_l)=>{"use strict";var jg=Bl(),Gg=Ys();_l.exports=Object.keys||function(e){return jg(e,Gg)}});var ql=m(Fl=>{"use strict";var Yg=ze(),Wg=gs(),Qg=Lt(),zg=Ne(),Kg=Zt(),Jg=Nl();Fl.f=Yg&&!Wg?Object.defineProperties:function(e,t){zg(e);for(var r=Kg(t),a=Jg(t),s=a.length,n=0,o;s>n;)Qg.f(e,o=a[n++],r[o]);return e}});var Ws=m((VP,Ul)=>{"use strict";var Xg=rt();Ul.exports=Xg("document","documentElement")});var Js=m((_P,zl)=>{"use strict";var Zg=Ne(),ev=ql(),Hl=Ys(),tv=aa(),rv=Ws(),iv=Ki(),av=ia(),jl=">",Gl="<",zs="prototype",Ks="script",Wl=av("IE_PROTO"),Qs=function(){},Ql=function(i){return Gl+Ks+jl+i+Gl+"/"+Ks+jl},Yl=function(i){i.write(Ql("")),i.close();var e=i.parentWindow.Object;return i=null,e},sv=function(){var i=iv("iframe"),e="java"+Ks+":",t;return i.style.display="none",rv.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Ql("document.F=Object")),t.close(),t.F},ca,da=function(){try{ca=new ActiveXObject("htmlfile")}catch{}da=typeof document<"u"?document.domain&&ca?Yl(ca):sv():Yl(ca);for(var i=Hl.length;i--;)delete da[zs][Hl[i]];return da()};tv[Wl]=!0;zl.exports=Object.create||function(e,t){var r;return e!==null?(Qs[zs]=Zg(e),r=new Qs,Qs[zs]=null,r[Wl]=e):r=da(),t===void 0?r:ev.f(r,t)}});var Jl=m((NP,Kl)=>{"use strict";var nv=Pe();Kl.exports=!nv(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var Zs=m((FP,Zl)=>{"use strict";var ov=Ue(),uv=ee(),lv=Lr(),cv=ia(),dv=Jl(),Xl=cv("IE_PROTO"),Xs=Object,pv=Xs.prototype;Zl.exports=dv?Xs.getPrototypeOf:function(i){var e=lv(i);if(ov(e,Xl))return e[Xl];var t=e.constructor;return uv(t)&&e instanceof t?t.prototype:e instanceof Xs?pv:null}});var ir=m((qP,ec)=>{"use strict";var hv=$t();ec.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:hv(i,e,t),i}});var an=m((UP,ic)=>{"use strict";var fv=Pe(),mv=ee(),bv=Qe(),gv=Js(),tc=Zs(),vv=ir(),Sv=ce(),yv=qe(),rn=Sv("iterator"),rc=!1,at,en,tn;[].keys&&(tn=[].keys(),"next"in tn?(en=tc(tc(tn)),en!==Object.prototype&&(at=en)):rc=!0);var Tv=!bv(at)||fv(function(){var i={};return at[rn].call(i)!==i});Tv?at={}:yv&&(at=gv(at));mv(at[rn])||vv(at,rn,function(){return this});ic.exports={IteratorPrototype:at,BUGGY_SAFARI_ITERATORS:rc}});var pa=m((HP,sc)=>{"use strict";var Iv=ce(),Ev=Iv("toStringTag"),ac={};ac[Ev]="z";sc.exports=String(ac)==="[object z]"});var ar=m((jP,nc)=>{"use strict";var xv=pa(),Pv=ee(),ha=Jt(),kv=ce(),wv=kv("toStringTag"),Av=Object,Rv=ha(function(){return arguments}())=="Arguments",Lv=function(i,e){try{return i[e]}catch{}};nc.exports=xv?ha:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=Lv(e=Av(i),wv))=="string"?t:Rv?ha(e):(r=ha(e))=="Object"&&Pv(e.callee)?"Arguments":r}});var uc=m((GP,oc)=>{"use strict";var $v=pa(),Cv=ar();oc.exports=$v?{}.toString:function(){return"[object "+Cv(this)+"]"}});var fa=m((YP,cc)=>{"use strict";var Dv=pa(),Mv=Lt().f,Ov=$t(),Bv=Ue(),Vv=uc(),_v=ce(),lc=_v("toStringTag");cc.exports=function(i,e,t,r){if(i){var a=t?i:i.prototype;Bv(a,lc)||Mv(a,lc,{configurable:!0,value:e}),r&&!Dv&&Ov(a,"toString",Vv)}}});var pc=m((WP,dc)=>{"use strict";var Nv=an().IteratorPrototype,Fv=Js(),qv=$r(),Uv=fa(),Hv=Rt(),jv=function(){return this};dc.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=Fv(Nv,{next:qv(+!r,t)}),Uv(i,a,!1,!0),Hv[a]=jv,i}});var fc=m((QP,hc)=>{"use strict";var Gv=fe(),Yv=it();hc.exports=function(i,e,t){try{return Gv(Yv(Object.getOwnPropertyDescriptor(i,e)[t]))}catch{}}});var bc=m((zP,mc)=>{"use strict";var Wv=ee(),Qv=String,zv=TypeError;mc.exports=function(i){if(typeof i=="object"||Wv(i))return i;throw zv("Can't set "+Qv(i)+" as a prototype")}});var sn=m((KP,gc)=>{"use strict";var Kv=fc(),Jv=Ne(),Xv=bc();gc.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=Kv(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch{}return function(a,s){return Jv(a),Xv(s),i?t(a,s):a.__proto__=s,a}}():void 0)});var Ac=m((JP,wc)=>{"use strict";var Zv=Ae(),eS=me(),ma=qe(),Pc=Il(),tS=ee(),rS=pc(),vc=Zs(),Sc=sn(),iS=fa(),aS=$t(),nn=ir(),sS=ce(),yc=Rt(),kc=an(),nS=Pc.PROPER,oS=Pc.CONFIGURABLE,Tc=kc.IteratorPrototype,ba=kc.BUGGY_SAFARI_ITERATORS,Or=sS("iterator"),Ic="keys",Br="values",Ec="entries",xc=function(){return this};wc.exports=function(i,e,t,r,a,s,n){rS(t,e,r);var o=function(T){if(T===a&&f)return f;if(!ba&&T in c)return c[T];switch(T){case Ic:return function(){return new t(this,T)};case Br:return function(){return new t(this,T)};case Ec:return function(){return new t(this,T)}}return function(){return new t(this)}},l=e+" Iterator",u=!1,c=i.prototype,d=c[Or]||c["@@iterator"]||a&&c[a],f=!ba&&d||o(a),h=e=="Array"&&c.entries||d,b,I,g;if(h&&(b=vc(h.call(new i)),b!==Object.prototype&&b.next&&(!ma&&vc(b)!==Tc&&(Sc?Sc(b,Tc):tS(b[Or])||nn(b,Or,xc)),iS(b,l,!0,!0),ma&&(yc[l]=xc))),nS&&a==Br&&d&&d.name!==Br&&(!ma&&oS?aS(c,"name",Br):(u=!0,f=function(){return eS(d,this)})),a)if(I={values:o(Br),keys:s?f:o(Ic),entries:o(Ec)},n)for(g in I)(ba||u||!(g in c))&&nn(c,g,I[g]);else Zv({target:e,proto:!0,forced:ba||u},I);return(!ma||n)&&c[Or]!==f&&nn(c,Or,f,{name:a}),yc[e]=f,I}});var Lc=m((XP,Rc)=>{"use strict";Rc.exports=function(i,e){return{value:i,done:e}}});var un=m((ZP,Oc)=>{"use strict";var uS=Zt(),on=ps(),$c=Rt(),Dc=_s(),lS=Lt().f,cS=Ac(),ga=Lc(),dS=qe(),pS=ze(),Mc="Array Iterator",hS=Dc.set,fS=Dc.getterFor(Mc);Oc.exports=cS(Array,"Array",function(i,e){hS(this,{type:Mc,target:uS(i),index:0,kind:e})},function(){var i=fS(this),e=i.target,t=i.kind,r=i.index++;return!e||r>=e.length?(i.target=void 0,ga(void 0,!0)):t=="keys"?ga(r,!1):t=="values"?ga(e[r],!1):ga([r,e[r]],!1)},"values");var Cc=$c.Arguments=$c.Array;on("keys");on("values");on("entries");if(!dS&&pS&&Cc.name!=="values")try{lS(Cc,"name",{value:"values"})}catch{}});var Vc=m((ek,Bc)=>{"use strict";var mS=ce(),bS=Rt(),gS=mS("iterator"),vS=Array.prototype;Bc.exports=function(i){return i!==void 0&&(bS.Array===i||vS[gS]===i)}});var ln=m((tk,Nc)=>{"use strict";var SS=ar(),_c=Rr(),yS=Xt(),TS=Rt(),IS=ce(),ES=IS("iterator");Nc.exports=function(i){if(!yS(i))return _c(i,ES)||_c(i,"@@iterator")||TS[SS(i)]}});var qc=m((rk,Fc)=>{"use strict";var xS=me(),PS=it(),kS=Ne(),wS=Ar(),AS=ln(),RS=TypeError;Fc.exports=function(i,e){var t=arguments.length<2?AS(i):e;if(PS(t))return kS(xS(t,i));throw RS(wS(i)+" is not iterable")}});var jc=m((ik,Hc)=>{"use strict";var LS=me(),Uc=Ne(),$S=Rr();Hc.exports=function(i,e,t){var r,a;Uc(i);try{if(r=$S(i,"return"),!r){if(e==="throw")throw t;return t}r=LS(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return Uc(r),t}});var Sa=m((ak,Qc)=>{"use strict";var CS=Mr(),DS=me(),MS=Ne(),OS=Ar(),BS=Vc(),VS=la(),Gc=kr(),_S=qc(),NS=ln(),Yc=jc(),FS=TypeError,va=function(i,e){this.stopped=i,this.result=e},Wc=va.prototype;Qc.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=CS(e,r),u,c,d,f,h,b,I,g=function(y){return u&&Yc(u,"normal",y),new va(!0,y)},T=function(y){return a?(MS(y),o?l(y[0],y[1],g):l(y[0],y[1])):o?l(y,g):l(y)};if(s)u=i.iterator;else if(n)u=i;else{if(c=NS(i),!c)throw FS(OS(i)+" is not iterable");if(BS(c)){for(d=0,f=VS(i);f>d;d++)if(h=T(i[d]),h&&Gc(Wc,h))return h;return new va(!1)}u=_S(i,c)}for(b=s?i.next:u.next;!(I=DS(b,u)).done;){try{h=T(I.value)}catch(y){Yc(u,"throw",y)}if(typeof h=="object"&&h&&Gc(Wc,h))return h}return new va(!1)}});var Kc=m((sk,zc)=>{"use strict";var qS=ta(),US=Lt(),HS=$r();zc.exports=function(i,e,t){var r=qS(e);r in i?US.f(i,r,HS(0,t)):i[r]=t}});var Jc=m(()=>{"use strict";var jS=Ae(),GS=Sa(),YS=Kc();jS({target:"Object",stat:!0},{fromEntries:function(e){var t={};return GS(e,function(r,a){YS(t,r,a)},{AS_ENTRIES:!0}),t}})});var Zc=m((uk,Xc)=>{"use strict";un();Jc();var WS=Xi();Xc.exports=WS.Object.fromEntries});var td=m((lk,ed)=>{"use strict";ed.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 ad=m(()=>{"use strict";un();var QS=td(),zS=ne(),KS=ar(),JS=$t(),rd=Rt(),XS=ce(),id=XS("toStringTag");for(ya in QS)cn=zS[ya],Ta=cn&&cn.prototype,Ta&&KS(Ta)!==id&&JS(Ta,id,ya),rd[ya]=rd.Array;var cn,Ta,ya});var nd=m((pk,sd)=>{"use strict";var ZS=Zc();ad();sd.exports=ZS});var Ia=m((hk,od)=>{"use strict";var ey=nd();od.exports=ey});var ud=m(()=>{"use strict"});var Vr=m((bk,ld)=>{"use strict";var ty=Jt();ld.exports=typeof process<"u"&&ty(process)=="process"});var dd=m((gk,cd)=>{"use strict";var ry=Lt();cd.exports=function(i,e,t){return ry.f(i,e,t)}});var fd=m((vk,hd)=>{"use strict";var iy=rt(),ay=dd(),sy=ce(),ny=ze(),pd=sy("species");hd.exports=function(i){var e=iy(i);ny&&e&&!e[pd]&&ay(e,pd,{configurable:!0,get:function(){return this}})}});var bd=m((Sk,md)=>{"use strict";var oy=kr(),uy=TypeError;md.exports=function(i,e){if(oy(e,i))return i;throw uy("Incorrect invocation")}});var pn=m((yk,gd)=>{"use strict";var ly=fe(),cy=ee(),dn=ea(),dy=ly(Function.toString);cy(dn.inspectSource)||(dn.inspectSource=function(i){return dy(i)});gd.exports=dn.inspectSource});var Ed=m((Tk,Id)=>{"use strict";var py=fe(),hy=Pe(),vd=ee(),fy=ar(),my=rt(),by=pn(),Sd=function(){},gy=[],yd=my("Reflect","construct"),hn=/^\s*(?:class|function)\b/,vy=py(hn.exec),Sy=!hn.exec(Sd),_r=function(e){if(!vd(e))return!1;try{return yd(Sd,gy,e),!0}catch{return!1}},Td=function(e){if(!vd(e))return!1;switch(fy(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Sy||!!vy(hn,by(e))}catch{return!0}};Td.sham=!0;Id.exports=!yd||hy(function(){var i;return _r(_r.call)||!_r(Object)||!_r(function(){i=!0})||i})?Td:_r});var Pd=m((Ik,xd)=>{"use strict";var yy=Ed(),Ty=Ar(),Iy=TypeError;xd.exports=function(i){if(yy(i))return i;throw Iy(Ty(i)+" is not a constructor")}});var fn=m((Ek,wd)=>{"use strict";var kd=Ne(),Ey=Pd(),xy=Xt(),Py=ce(),ky=Py("species");wd.exports=function(i,e){var t=kd(i).constructor,r;return t===void 0||xy(r=kd(t)[ky])?e:Ey(r)}});var Rd=m((xk,Ad)=>{"use strict";var wy=fe();Ad.exports=wy([].slice)});var $d=m((Pk,Ld)=>{"use strict";var Ay=TypeError;Ld.exports=function(i,e){if(i<e)throw Ay("Not enough arguments");return i}});var mn=m((kk,Cd)=>{"use strict";var Ry=wr();Cd.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Ry)});var xn=m((wk,qd)=>{"use strict";var ke=ne(),Ly=Ns(),$y=Mr(),Dd=ee(),Cy=Ue(),Fd=Pe(),Md=Ws(),Dy=Rd(),Od=Ki(),My=$d(),Oy=mn(),By=Vr(),Tn=ke.setImmediate,In=ke.clearImmediate,Vy=ke.process,bn=ke.Dispatch,_y=ke.Function,Bd=ke.MessageChannel,Ny=ke.String,gn=0,Nr={},Vd="onreadystatechange",Fr,Dt,vn,Sn;Fd(function(){Fr=ke.location});var En=function(i){if(Cy(Nr,i)){var e=Nr[i];delete Nr[i],e()}},yn=function(i){return function(){En(i)}},_d=function(i){En(i.data)},Nd=function(i){ke.postMessage(Ny(i),Fr.protocol+"//"+Fr.host)};(!Tn||!In)&&(Tn=function(e){My(arguments.length,1);var t=Dd(e)?e:_y(e),r=Dy(arguments,1);return Nr[++gn]=function(){Ly(t,void 0,r)},Dt(gn),gn},In=function(e){delete Nr[e]},By?Dt=function(i){Vy.nextTick(yn(i))}:bn&&bn.now?Dt=function(i){bn.now(yn(i))}:Bd&&!Oy?(vn=new Bd,Sn=vn.port2,vn.port1.onmessage=_d,Dt=$y(Sn.postMessage,Sn)):ke.addEventListener&&Dd(ke.postMessage)&&!ke.importScripts&&Fr&&Fr.protocol!=="file:"&&!Fd(Nd)?(Dt=Nd,ke.addEventListener("message",_d,!1)):Vd in Od("script")?Dt=function(i){Md.appendChild(Od("script"))[Vd]=function(){Md.removeChild(this),En(i)}}:Dt=function(i){setTimeout(yn(i),0)});qd.exports={set:Tn,clear:In}});var Pn=m((Ak,Hd)=>{"use strict";var Ud=function(){this.head=null,this.tail=null};Ud.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}}};Hd.exports=Ud});var Gd=m((Rk,jd)=>{"use strict";var Fy=wr();jd.exports=/ipad|iphone|ipod/i.test(Fy)&&typeof Pebble<"u"});var Wd=m((Lk,Yd)=>{"use strict";var qy=wr();Yd.exports=/web0s(?!.*chrome)/i.test(qy)});var tp=m(($k,ep)=>{"use strict";var Mt=ne(),Qd=Mr(),Uy=qs().f,kn=xn().set,Hy=Pn(),jy=mn(),Gy=Gd(),Yy=Wd(),wn=Vr(),zd=Mt.MutationObserver||Mt.WebKitMutationObserver,Kd=Mt.document,Jd=Mt.process,Ea=Mt.Promise,Xd=Uy(Mt,"queueMicrotask"),Ln=Xd&&Xd.value,sr,An,Rn,xa,Zd;Ln||(qr=new Hy,Ur=function(){var i,e;for(wn&&(i=Jd.domain)&&i.exit();e=qr.get();)try{e()}catch(t){throw qr.head&&sr(),t}i&&i.enter()},!jy&&!wn&&!Yy&&zd&&Kd?(An=!0,Rn=Kd.createTextNode(""),new zd(Ur).observe(Rn,{characterData:!0}),sr=function(){Rn.data=An=!An}):!Gy&&Ea&&Ea.resolve?(xa=Ea.resolve(void 0),xa.constructor=Ea,Zd=Qd(xa.then,xa),sr=function(){Zd(Ur)}):wn?sr=function(){Jd.nextTick(Ur)}:(kn=Qd(kn,Mt),sr=function(){kn(Ur)}),Ln=function(i){qr.head||sr(),qr.add(i)});var qr,Ur;ep.exports=Ln});var ip=m((Ck,rp)=>{"use strict";rp.exports=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch{}}});var Pa=m((Dk,ap)=>{"use strict";ap.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var Ot=m((Mk,sp)=>{"use strict";var Wy=ne();sp.exports=Wy.Promise});var $n=m((Ok,np)=>{"use strict";np.exports=typeof Deno=="object"&&Deno&&typeof Deno.version=="object"});var up=m((Bk,op)=>{"use strict";var Qy=$n(),zy=Vr();op.exports=!Qy&&!zy&&typeof window=="object"&&typeof document=="object"});var nr=m((Vk,dp)=>{"use strict";var Ky=ne(),Hr=Ot(),Jy=ee(),Xy=Us(),Zy=pn(),eT=ce(),tT=up(),rT=$n(),iT=qe(),Cn=Ts(),lp=Hr&&Hr.prototype,aT=eT("species"),Dn=!1,cp=Jy(Ky.PromiseRejectionEvent),sT=Xy("Promise",function(){var i=Zy(Hr),e=i!==String(Hr);if(!e&&Cn===66||iT&&!(lp.catch&&lp.finally))return!0;if(!Cn||Cn<51||!/native code/.test(i)){var t=new Hr(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[aT]=r,Dn=t.then(function(){})instanceof r,!Dn)return!0}return!e&&(tT||rT)&&!cp});dp.exports={CONSTRUCTOR:sT,REJECTION_EVENT:cp,SUBCLASSING:Dn}});var or=m((_k,hp)=>{"use strict";var pp=it(),nT=TypeError,oT=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw nT("Bad Promise constructor");e=r,t=a}),this.resolve=pp(e),this.reject=pp(t)};hp.exports.f=function(i){return new oT(i)}});var Cp=m(()=>{"use strict";var uT=Ae(),lT=qe(),Ra=Vr(),yt=ne(),dr=me(),fp=ir(),mp=sn(),cT=fa(),dT=fd(),pT=it(),Aa=ee(),hT=Qe(),fT=bd(),mT=fn(),yp=xn().set,_n=tp(),bT=ip(),gT=Pa(),vT=Pn(),Tp=_s(),La=Ot(),Nn=nr(),Ip=or(),$a="Promise",Ep=Nn.CONSTRUCTOR,ST=Nn.REJECTION_EVENT,yT=Nn.SUBCLASSING,Mn=Tp.getterFor($a),TT=Tp.set,ur=La&&La.prototype,Bt=La,ka=ur,xp=yt.TypeError,On=yt.document,Fn=yt.process,Bn=Ip.f,IT=Bn,ET=!!(On&&On.createEvent&&yt.dispatchEvent),Pp="unhandledrejection",xT="rejectionhandled",bp=0,kp=1,PT=2,qn=1,wp=2,wa,gp,kT,vp,Ap=function(i){var e;return hT(i)&&Aa(e=i.then)?e:!1},Rp=function(i,e){var t=e.value,r=e.state==kp,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,l,u,c;try{a?(r||(e.rejection===wp&&AT(e),e.rejection=qn),a===!0?l=t:(o&&o.enter(),l=a(t),o&&(o.exit(),c=!0)),l===i.promise?n(xp("Promise-chain cycle")):(u=Ap(l))?dr(u,l,s,n):s(l)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Lp=function(i,e){i.notified||(i.notified=!0,_n(function(){for(var t=i.reactions,r;r=t.get();)Rp(r,i);i.notified=!1,e&&!i.rejection&&wT(i)}))},$p=function(i,e,t){var r,a;ET?(r=On.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),yt.dispatchEvent(r)):r={promise:e,reason:t},!ST&&(a=yt["on"+i])?a(r):i===Pp&&bT("Unhandled promise rejection",t)},wT=function(i){dr(yp,yt,function(){var e=i.facade,t=i.value,r=Sp(i),a;if(r&&(a=gT(function(){Ra?Fn.emit("unhandledRejection",t,e):$p(Pp,e,t)}),i.rejection=Ra||Sp(i)?wp:qn,a.error))throw a.value})},Sp=function(i){return i.rejection!==qn&&!i.parent},AT=function(i){dr(yp,yt,function(){var e=i.facade;Ra?Fn.emit("rejectionHandled",e):$p(xT,e,i.value)})},lr=function(i,e,t){return function(r){i(e,r,t)}},cr=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=PT,Lp(i,!0))},Vn=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw xp("Promise can't be resolved itself");var r=Ap(e);r?_n(function(){var a={done:!1};try{dr(r,e,lr(Vn,a,i),lr(cr,a,i))}catch(s){cr(a,s,i)}}):(i.value=e,i.state=kp,Lp(i,!1))}catch(a){cr({done:!1},a,i)}}};if(Ep&&(Bt=function(e){fT(this,ka),pT(e),dr(wa,this);var t=Mn(this);try{e(lr(Vn,t),lr(cr,t))}catch(r){cr(t,r)}},ka=Bt.prototype,wa=function(e){TT(this,{type:$a,done:!1,notified:!1,parent:!1,reactions:new vT,rejection:!1,state:bp,value:void 0})},wa.prototype=fp(ka,"then",function(e,t){var r=Mn(this),a=Bn(mT(this,Bt));return r.parent=!0,a.ok=Aa(e)?e:!0,a.fail=Aa(t)&&t,a.domain=Ra?Fn.domain:void 0,r.state==bp?r.reactions.add(a):_n(function(){Rp(a,r)}),a.promise}),gp=function(){var i=new wa,e=Mn(i);this.promise=i,this.resolve=lr(Vn,e),this.reject=lr(cr,e)},Ip.f=Bn=function(i){return i===Bt||i===kT?new gp(i):IT(i)},!lT&&Aa(La)&&ur!==Object.prototype)){vp=ur.then,yT||fp(ur,"then",function(e,t){var r=this;return new Bt(function(a,s){dr(vp,r,a,s)}).then(e,t)},{unsafe:!0});try{delete ur.constructor}catch{}mp&&mp(ur,ka)}uT({global:!0,constructor:!0,wrap:!0,forced:Ep},{Promise:Bt});cT(Bt,$a,!1,!0);dT($a)});var Vp=m((qk,Bp)=>{"use strict";var RT=ce(),Mp=RT("iterator"),Op=!1;try{Dp=0,Un={next:function(){return{done:!!Dp++}},return:function(){Op=!0}},Un[Mp]=function(){return this},Array.from(Un,function(){throw 2})}catch{}var Dp,Un;Bp.exports=function(i,e){if(!e&&!Op)return!1;var t=!1;try{var r={};r[Mp]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch{}return t}});var Hn=m((Uk,_p)=>{"use strict";var LT=Ot(),$T=Vp(),CT=nr().CONSTRUCTOR;_p.exports=CT||!$T(function(i){LT.all(i).then(void 0,function(){})})});var Np=m(()=>{"use strict";var DT=Ae(),MT=me(),OT=it(),BT=or(),VT=Pa(),_T=Sa(),NT=Hn();DT({target:"Promise",stat:!0,forced:NT},{all:function(e){var t=this,r=BT.f(t),a=r.resolve,s=r.reject,n=VT(function(){var o=OT(t.resolve),l=[],u=0,c=1;_T(e,function(d){var f=u++,h=!1;c++,MT(o,t,d).then(function(b){h||(h=!0,l[f]=b,--c||a(l))},s)}),--c||a(l)});return n.error&&s(n.value),r.promise}})});var qp=m(()=>{"use strict";var FT=Ae(),qT=qe(),UT=nr().CONSTRUCTOR,Gn=Ot(),HT=rt(),jT=ee(),GT=ir(),Fp=Gn&&Gn.prototype;FT({target:"Promise",proto:!0,forced:UT,real:!0},{catch:function(i){return this.then(void 0,i)}});!qT&&jT(Gn)&&(jn=HT("Promise").prototype.catch,Fp.catch!==jn&>(Fp,"catch",jn,{unsafe:!0}));var jn});var Up=m(()=>{"use strict";var YT=Ae(),WT=me(),QT=it(),zT=or(),KT=Pa(),JT=Sa(),XT=Hn();YT({target:"Promise",stat:!0,forced:XT},{race:function(e){var t=this,r=zT.f(t),a=r.reject,s=KT(function(){var n=QT(t.resolve);JT(e,function(o){WT(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var Hp=m(()=>{"use strict";var ZT=Ae(),eI=me(),tI=or(),rI=nr().CONSTRUCTOR;ZT({target:"Promise",stat:!0,forced:rI},{reject:function(e){var t=tI.f(this);return eI(t.reject,void 0,e),t.promise}})});var Yn=m((Jk,jp)=>{"use strict";var iI=Ne(),aI=Qe(),sI=or();jp.exports=function(i,e){if(iI(i),aI(e)&&e.constructor===i)return e;var t=sI.f(i),r=t.resolve;return r(e),t.promise}});var Wp=m(()=>{"use strict";var nI=Ae(),oI=rt(),Gp=qe(),uI=Ot(),Yp=nr().CONSTRUCTOR,lI=Yn(),cI=oI("Promise"),dI=Gp&&!Yp;nI({target:"Promise",stat:!0,forced:Gp||Yp},{resolve:function(e){return lI(dI&&this===cI?uI:this,e)}})});var Qp=m(()=>{"use strict";Cp();Np();qp();Up();Hp();Wp()});var Xp=m(()=>{"use strict";var pI=Ae(),hI=qe(),Ca=Ot(),fI=Pe(),Kp=rt(),Jp=ee(),mI=fn(),zp=Yn(),bI=ir(),Qn=Ca&&Ca.prototype,gI=!!Ca&&fI(function(){Qn.finally.call({then:function(){}},function(){})});pI({target:"Promise",proto:!0,real:!0,forced:gI},{finally:function(i){var e=mI(this,Kp("Promise")),t=Jp(i);return this.then(t?function(r){return zp(e,i()).then(function(){return r})}:i,t?function(r){return zp(e,i()).then(function(){throw r})}:i)}});!hI&&Jp(Ca)&&(Wn=Kp("Promise").prototype.finally,Qn.finally!==Wn&&bI(Qn,"finally",Wn,{unsafe:!0}));var Wn});var Da=m((aw,Zp)=>{"use strict";var vI=rt();Zp.exports=vI});var th=m((sw,eh)=>{"use strict";ud();Qp();Xp();var SI=Da();eh.exports=SI("Promise","finally")});var ih=m((nw,rh)=>{"use strict";var yI=th();rh.exports=yI});var Ma=m((ow,ah)=>{"use strict";var TI=ih();ah.exports=TI});var hh=m(()=>{"use strict";var AI=Ae(),RI=Lr(),LI=la(),$I=ua(),CI=ps();AI({target:"Array",proto:!0},{at:function(e){var t=RI(this),r=LI(t),a=$I(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});CI("at")});var mh=m((uA,fh)=>{"use strict";hh();var DI=Da();fh.exports=DI("Array","at")});var gh=m((lA,bh)=>{"use strict";var MI=mh();bh.exports=MI});var Ba=m((cA,vh)=>{"use strict";var OI=gh();vh.exports=OI});var Vh=m(()=>{"use strict"});var _h=m(()=>{"use strict"});var Fh=m((F$,Nh)=>{"use strict";var dE=Qe(),pE=Jt(),hE=ce(),fE=hE("match");Nh.exports=function(i){var e;return dE(i)&&((e=i[fE])!==void 0?!!e:pE(i)=="RegExp")}});var Uh=m((q$,qh)=>{"use strict";var mE=ar(),bE=String;qh.exports=function(i){if(mE(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return bE(i)}});var jh=m((U$,Hh)=>{"use strict";var gE=Ne();Hh.exports=function(){var i=gE(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 Wh=m((H$,Yh)=>{"use strict";var vE=me(),SE=Ue(),yE=kr(),TE=jh(),Gh=RegExp.prototype;Yh.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in Gh)&&!SE(i,"flags")&&yE(Gh,i)?vE(TE,i):e}});var zh=m((j$,Qh)=>{"use strict";var mo=fe(),IE=Lr(),EE=Math.floor,ho=mo("".charAt),xE=mo("".replace),fo=mo("".slice),PE=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,kE=/\$([$&'`]|\d{1,2})/g;Qh.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,l=kE;return a!==void 0&&(a=IE(a),l=PE),xE(s,l,function(u,c){var d;switch(ho(c,0)){case"$":return"$";case"&":return i;case"`":return fo(e,0,t);case"'":return fo(e,n);case"<":d=a[fo(c,1,-1)];break;default:var f=+c;if(f===0)return u;if(f>o){var h=EE(f/10);return h===0?u:h<=o?r[h-1]===void 0?ho(c,1):r[h-1]+ho(c,1):u}d=r[f-1]}return d===void 0?"":d})}});var ef=m(()=>{"use strict";var wE=Ae(),AE=me(),bo=fe(),Kh=Qi(),RE=ee(),LE=Xt(),$E=Fh(),br=Uh(),CE=Rr(),DE=Wh(),ME=zh(),OE=ce(),BE=qe(),VE=OE("replace"),_E=TypeError,Zh=bo("".indexOf),NE=bo("".replace),Jh=bo("".slice),FE=Math.max,Xh=function(i,e,t){return t>i.length?-1:e===""?t:Zh(i,e,t)};wE({target:"String",proto:!0},{replaceAll:function(e,t){var r=Kh(this),a,s,n,o,l,u,c,d,f,h=0,b=0,I="";if(!LE(e)){if(a=$E(e),a&&(s=br(Kh(DE(e))),!~Zh(s,"g")))throw _E("`.replaceAll` does not allow non-global regexes");if(n=CE(e,VE),n)return AE(n,e,r,t);if(BE&&a)return NE(br(r),e,t)}for(o=br(r),l=br(e),u=RE(t),u||(t=br(t)),c=l.length,d=FE(1,c),h=Xh(o,l,0);h!==-1;)f=u?br(t(l,h,o)):ME(l,o,h,[],void 0,t),I+=Jh(o,b,h)+f,b=h+c,h=Xh(o,l,h+d);return b<o.length&&(I+=Jh(o,b)),I}})});var rf=m((W$,tf)=>{"use strict";Vh();_h();ef();var qE=Da();tf.exports=qE("String","replaceAll")});var sf=m((Q$,af)=>{"use strict";var UE=rf();af.exports=UE});var of=m((z$,nf)=>{"use strict";var HE=sf();nf.exports=HE});var dx={};om(dx,{ChromecastState:()=>xr,HttpConnectionType:()=>Gi,Observable:()=>et.Observable,PlaybackState:()=>he,Player:()=>_i,SDK_VERSION:()=>cx,Subject:()=>et.Subject,Subscription:()=>et.Subscription,Surface:()=>Yi,VERSION:()=>ls,ValueSubject:()=>et.ValueSubject,VideoFormat:()=>St,VideoQuality:()=>et.VideoQuality});module.exports=um(dx);var ls="__VERSION__";var he=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(he||{}),St=(y=>(y.MPEG="MPEG",y.DASH="DASH_SEP",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(St||{});var xr=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(xr||{}),Gi=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Gi||{});var Yi=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Yi||{});var V=require("@vkontakte/videoplayer-shared");var $o=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 Wi=class{constructor(e){this.connection$=new V.ValueSubject(void 0);this.castState$=new V.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new V.Subject;this.realCastState$=new V.ValueSubject("NOT_AVAILABLE");this.subscription=new V.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,V.isNonNullable)(window.chrome?.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},a||$o("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:V.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,V.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,V.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,V.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,V.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,V.assertNever)(a.sessionState)}})).add((0,V.merge)((0,V.fromEvent)(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,V.tap)(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),(0,V.map)(a=>a.castState)),(0,V.observableFrom)([r.getCastState()])).pipe((0,V.filterChanged)(),(0,V.map)(lm),(0,V.tap)(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=(0,V.isNonNullable)(this.connection$.getValue());if(s&&!n){let o=r.getCurrentSession();(0,V.assertNonNullable)(o);let l=o.getCastDevice(),u=o.getMediaSession()?.media.contentId;((0,V.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,V.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:V.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},lm=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,V.assertNever)(i)}};var Ff=_e(Ia(),1);var uh=_e(Ma(),1);var zn=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,zn.assertNever)(t)}return i},Kn=(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,zn.assertNever)(e)}};var P=(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 sh=require("@vkontakte/videoplayer-shared"),nh=i=>{switch(i){case"MPEG":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":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,sh.assertNever)(i)}};var R=require("@vkontakte/videoplayer-shared");var II=5,EI=5,xI=500,oh=7e3,jr=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(nh(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)(xI)).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)>II)&&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(),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<EI&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),P(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"),P(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),P(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"),P(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),P(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&P(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 c=(0,R.getHighestQuality)(Object.keys(u));(0,R.assertNonNullable)(c);let d=u[c];(0,R.assertNonNullable)(d),r=d,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":{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=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:R.ErrorCategory.VIDEO_PIPELINE,message:u,thrown:c}),c}case"DASH_LIVE_WEBM":throw new Error("DASH_LIVE_WEBM 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:l}=this.params.meta;return(0,R.isNonNullable)(o)&&(n.metadata.title=o),(0,R.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,R.timeout)(oh).subscribe(()=>s(`timeout(${oh})`)))});(0,uh.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 Gr=i=>{i.removeAttribute("src"),i.load()};var lh=i=>{try{i.pause(),i.playbackRate=0,Gr(i),i.remove()}catch(e){console.error(e)}};var Jn=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)}},Xn=window.WeakMap?new WeakMap:new Jn,be=i=>{let e=i.querySelector("video"),t=!!e;return e?Gr(e):(e=document.createElement("video"),i.appendChild(e)),Xn.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},ge=i=>{let e=Xn.get(i);Xn.delete(i),e?Gr(i):lh(i)};var L=require("@vkontakte/videoplayer-shared");var Tt=require("@vkontakte/videoplayer-shared"),Oa=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),l=(0,Tt.isNullable)(a),u=new Tt.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},Je=(i,e,t)=>Oa(e,()=>i.loop,r=>{(0,Tt.isNonNullable)(r)&&(i.loop=r)},{onError:t}),ve=(i,e,t,r)=>Oa(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}),Re=(i,e,t,r)=>Oa(e,()=>i.playbackRate,a=>{(0,Tt.isNonNullable)(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),It=Oa;var PI=i=>["__",i.language,i.label].join("|"),kI=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},Zn=class i{constructor(){this.available$=new L.Subject;this.current$=new L.ValueSubject(void 0);this.error$=new L.Subject;this.subscription=new L.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:L.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,L.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,L.isNonNullable)(s)&&(0,L.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},l)=>o===n[l].id),changed$:this.available$.pipe((0,L.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(It(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{(0,L.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,L.isNonNullable)(s)&&(0,L.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},l)=>o===n[l].id),changed$:this.available$.pipe((0,L.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,L.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,L.fromEvent)(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add((0,L.merge)((0,L.fromEvent)(e,"addtrack"),(0,L.fromEvent)(e,"removetrack"),(0,L.observableFrom)(["init"])).pipe((0,L.map)(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),(0,L.filterChanged)((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add((0,L.merge)((0,L.fromEvent)(e,"change"),(0,L.observableFrom)(["init"])).pipe((0,L.map)(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),(0,L.map)(r=>r&&this.htmlTextTrackToITextTrack(r).id),(0,L.filterChanged)()).subscribe(this.current$));let t=r=>this.applyCueSettings(r.target?.activeCues??null);this.subscription.add((0,L.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,L.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,L.isNonNullable)(t.align)&&(a.align=t.align),(0,L.isNonNullable)(t.position)&&(a.position=t.position),(0,L.isNonNullable)(t.size)&&(a.size=t.size),(0,L.isNonNullable)(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,L.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:PI(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,L.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,L.isNullable)(e)||!kI(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,L.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,L.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)}},Le=Zn;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},eo=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 A=require("@vkontakte/videoplayer-shared");var wI=3,ph=(i,e,t=wI)=>{let r=0,a=0;for(let s=0;s<i.length;s++){let n=i.start(s),o=i.end(s);if(n<=e&&e<=o){if(r=n,a=o,!t)return{from:r,to:a};for(let l=s-1;l>=0;l--)i.end(l)+t>=r&&(r=i.start(l));for(let l=s+1;l<i.length;l++)i.start(l)-t<=a&&(a=i.end(l))}}return{from:r,to:a}};var Se=i=>{let e=M=>(0,A.fromEvent)(i,M).pipe((0,A.mapTo)(void 0)),r=(0,A.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(M=>(0,A.fromEvent)(i,M))).pipe((0,A.map)(M=>M.type==="ended"?i.readyState<2:i.readyState<3),(0,A.filterChanged)()),a=(0,A.merge)((0,A.fromEvent)(i,"progress"),(0,A.fromEvent)(i,"timeupdate")).pipe((0,A.map)(()=>ph(i.buffered,i.currentTime))),n=(0,A.getCurrentBrowser)().browser===A.CurrentClientBrowser.Safari?(0,A.combine)({play:e("play").pipe((0,A.once)()),playing:e("playing")}).pipe((0,A.mapTo)(void 0)):e("playing"),o=(0,A.fromEvent)(i,"volumechange").pipe((0,A.map)(()=>({muted:i.muted,volume:i.volume}))),l=(0,A.fromEvent)(i,"ratechange").pipe((0,A.map)(()=>i.playbackRate)),u=(0,A.fromEvent)(i,"error").pipe((0,A.filter)(()=>!!(i.error||i.played.length)),(0,A.map)(()=>{let M=i.error;return{id:M?`MediaError#${M.code}`:"HtmlVideoError",category:A.ErrorCategory.VIDEO_PIPELINE,message:M?M.message:"Error event from HTML video element",thrown:i.error??void 0}})),c=(0,A.fromEvent)(i,"timeupdate").pipe((0,A.map)(()=>i.currentTime)),d=new A.Subject,f=.3,h;c.subscribe(M=>{i.loop&&(0,A.isNonNullable)(h)&&(0,A.isNonNullable)(M)&&h>=i.duration-f&&M<=f&&d.next(h),h=M});let b=(0,A.fromEvent)(i,"enterpictureinpicture"),I=(0,A.fromEvent)(i,"leavepictureinpicture"),g=new A.ValueSubject(dh(i));b.subscribe(()=>g.next(!0)),I.subscribe(()=>g.next(!1));let T=new A.ValueSubject(eo(i));return(0,A.fromEvent)(i,"fullscreenchange").pipe((0,A.map)(()=>eo(i))).subscribe(T),{playing$:n,pause$:e("pause").pipe((0,A.filter)(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:d,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:(0,A.fromEvent)(i,"durationchange").pipe((0,A.map)(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:o,playbackRateState$:l,inPiP$:g,inFullscreen$:T}};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 ro=_e(Ba(),1),F=require("@vkontakte/videoplayer-shared");var to=!1,ut={},Sh=i=>{to=i},yh=()=>{ut={}},Th=i=>{i(ut)},Yr=(i,e)=>{to&&(ut.meta=ut.meta??{},ut.meta[i]=e)},pe=class{constructor(e){this.name=e}next(e){if(!to)return;ut.series=ut.series??{};let t=ut.series[this.name]??[];t.push([Date.now(),e]),ut.series[this.name]=t}};var BI=new pe("best_bitrate"),VI=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t,Va=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,F.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},_I='Assertion "ABR Tracks is empty array" failed',NI=(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,F.assertNotEmptyArray)(i,_I);let f=r.usePixelRatio?window.devicePixelRatio??1:1,h=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*f*r.containerSizeFactor,height:e.height*f*r.containerSizeFactor},b=h&&(0,F.videoSizeToQuality)(h),I=r.considerPlaybackRate&&(0,F.isNonNullable)(o)?o:1,g=i.filter(w=>!(0,F.isInvariantQuality)(w.quality)).sort((w,$)=>(0,F.isHigher)(w.quality,$.quality)?-1:1),T=(0,ro.default)(g,-1)?.quality,y=(0,ro.default)(g,0)?.quality,M=(0,F.isNullable)(a)||(0,F.isNonNullable)(a.min)&&(0,F.isNonNullable)(a.max)&&(0,F.isLower)(a.max,a.min)||(0,F.isNonNullable)(a.min)&&y&&(0,F.isHigher)(a.min,y)||(0,F.isNonNullable)(a.max)&&T&&(0,F.isLower)(a.max,T),E=I*VI(n??.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),k={},j=g.filter(w=>(b?(0,F.isLower)(w.quality,b):!0)?((0,F.isNonNullable)(t)&&isFinite(t)&&(0,F.isNonNullable)(w.bitrate)?t-s>=w.bitrate*E:!0)?r.lazyQualitySwitch&&(0,F.isNonNullable)(r.minBufferToSwitchUp)&&l&&!(0,F.isInvariantQuality)(l.quality)&&(n??0)<r.minBufferToSwitchUp&&(0,F.isHigher)(w.quality,l.quality)?(k[w.quality]="Buffer",!1):!!c&&(0,F.isHigherOrEqual)(w.quality,c)?(k[w.quality]="DroppedFramesLimit",!1):M||((0,F.isNullable)(a.max)||(0,F.isLowerOrEqual)(w.quality,a.max))&&((0,F.isNullable)(a.min)||(0,F.isHigherOrEqual)(w.quality,a.min))?!0:(k[w.quality]="FitsQualityLimits",!1):(k[w.quality]="FitsThroughput",!1):(k[w.quality]="FitsContainer",!1))[0];j&&j.bitrate&&BI.next(j.bitrate);let N=j??g[Math.ceil((g.length-1)/2)]??i[0];N.quality!==u?.last?.quality&&d({message:`
|
|
6
|
+
"use strict";var om=Object.create;var Yi=Object.defineProperty;var um=Object.getOwnPropertyDescriptor;var lm=Object.getOwnPropertyNames;var cm=Object.getPrototypeOf,dm=Object.prototype.hasOwnProperty;var m=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),pm=(i,e)=>{for(var t in e)Yi(i,t,{get:e[t],enumerable:!0})},Oo=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of lm(e))!dm.call(i,a)&&a!==t&&Yi(i,a,{get:()=>e[a],enumerable:!(r=um(e,a))||r.enumerable});return i};var _e=(i,e,t)=>(t=i!=null?om(cm(i)):{},Oo(e||!i||!i.__esModule?Yi(t,"default",{value:i,enumerable:!0}):t,i)),hm=i=>Oo(Yi({},"__esModule",{value:!0}),i);var Pe=m((Lx,Vo)=>{"use strict";Vo.exports=function(i){try{return!!i()}catch{return!0}}});var kr=m(($x,_o)=>{"use strict";var mm=Pe();_o.exports=!mm(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var fe=m((Cx,qo)=>{"use strict";var No=kr(),Fo=Function.prototype,fs=Fo.call,bm=No&&Fo.bind.bind(fs,fs);qo.exports=No?bm:function(i){return function(){return fs.apply(i,arguments)}}});var Jt=m((Dx,Ho)=>{"use strict";var Uo=fe(),vm=Uo({}.toString),gm=Uo("".slice);Ho.exports=function(i){return gm(vm(i),8,-1)}});var Go=m((Mx,jo)=>{"use strict";var Sm=fe(),ym=Pe(),Tm=Jt(),ms=Object,Im=Sm("".split);jo.exports=ym(function(){return!ms("z").propertyIsEnumerable(0)})?function(i){return Tm(i)=="String"?Im(i,""):ms(i)}:ms});var Xt=m((Ox,Yo)=>{"use strict";Yo.exports=function(i){return i==null}});var Ki=m((Bx,Wo)=>{"use strict";var Em=Xt(),xm=TypeError;Wo.exports=function(i){if(Em(i))throw xm("Can't call method on "+i);return i}});var Zt=m((Vx,Qo)=>{"use strict";var Pm=Go(),km=Ki();Qo.exports=function(i){return Pm(km(i))}});var bs=m((_x,zo)=>{"use strict";zo.exports=function(){}});var Rt=m((Nx,Ko)=>{"use strict";Ko.exports={}});var ne=m((Jo,Xo)=>{"use strict";var Ji=function(i){return i&&i.Math==Math&&i};Xo.exports=Ji(typeof globalThis=="object"&&globalThis)||Ji(typeof window=="object"&&window)||Ji(typeof self=="object"&&self)||Ji(typeof global=="object"&&global)||function(){return this}()||Jo||Function("return this")()});var gs=m((Fx,Zo)=>{"use strict";var vs=typeof document=="object"&&document.all,wm=typeof vs>"u"&&vs!==void 0;Zo.exports={all:vs,IS_HTMLDDA:wm}});var ee=m((qx,tu)=>{"use strict";var eu=gs(),Am=eu.all;tu.exports=eu.IS_HTMLDDA?function(i){return typeof i=="function"||i===Am}:function(i){return typeof i=="function"}});var au=m((Ux,iu)=>{"use strict";var Rm=ne(),Lm=ee(),ru=Rm.WeakMap;iu.exports=Lm(ru)&&/native code/.test(String(ru))});var Qe=m((Hx,ou)=>{"use strict";var su=ee(),nu=gs(),$m=nu.all;ou.exports=nu.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:su(i)||i===$m}:function(i){return typeof i=="object"?i!==null:su(i)}});var ze=m((jx,uu)=>{"use strict";var Cm=Pe();uu.exports=!Cm(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7})});var Xi=m((Gx,cu)=>{"use strict";var Dm=ne(),lu=Qe(),Ss=Dm.document,Mm=lu(Ss)&&lu(Ss.createElement);cu.exports=function(i){return Mm?Ss.createElement(i):{}}});var ys=m((Yx,du)=>{"use strict";var Om=ze(),Bm=Pe(),Vm=Xi();du.exports=!Om&&!Bm(function(){return Object.defineProperty(Vm("div"),"a",{get:function(){return 7}}).a!=7})});var Ts=m((Wx,pu)=>{"use strict";var _m=ze(),Nm=Pe();pu.exports=_m&&Nm(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42})});var Ne=m((Qx,hu)=>{"use strict";var Fm=Qe(),qm=String,Um=TypeError;hu.exports=function(i){if(Fm(i))return i;throw Um(qm(i)+" is not an object")}});var me=m((zx,fu)=>{"use strict";var Hm=kr(),Zi=Function.prototype.call;fu.exports=Hm?Zi.bind(Zi):function(){return Zi.apply(Zi,arguments)}});var ea=m((Kx,mu)=>{"use strict";mu.exports={}});var rt=m((Jx,vu)=>{"use strict";var Is=ea(),Es=ne(),jm=ee(),bu=function(i){return jm(i)?i:void 0};vu.exports=function(i,e){return arguments.length<2?bu(Is[i])||bu(Es[i]):Is[i]&&Is[i][e]||Es[i]&&Es[i][e]}});var wr=m((Xx,gu)=>{"use strict";var Gm=fe();gu.exports=Gm({}.isPrototypeOf)});var Ar=m((Zx,Su)=>{"use strict";Su.exports=typeof navigator<"u"&&String(navigator.userAgent)||""});var Ps=m((eP,Pu)=>{"use strict";var xu=ne(),xs=Ar(),yu=xu.process,Tu=xu.Deno,Iu=yu&&yu.versions||Tu&&Tu.version,Eu=Iu&&Iu.v8,Fe,ta;Eu&&(Fe=Eu.split("."),ta=Fe[0]>0&&Fe[0]<4?1:+(Fe[0]+Fe[1]));!ta&&xs&&(Fe=xs.match(/Edge\/(\d+)/),(!Fe||Fe[1]>=74)&&(Fe=xs.match(/Chrome\/(\d+)/),Fe&&(ta=+Fe[1])));Pu.exports=ta});var ks=m((tP,wu)=>{"use strict";var ku=Ps(),Ym=Pe(),Wm=ne(),Qm=Wm.String;wu.exports=!!Object.getOwnPropertySymbols&&!Ym(function(){var i=Symbol();return!Qm(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&ku&&ku<41})});var ws=m((rP,Au)=>{"use strict";var zm=ks();Au.exports=zm&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var As=m((iP,Ru)=>{"use strict";var Km=rt(),Jm=ee(),Xm=wr(),Zm=ws(),eb=Object;Ru.exports=Zm?function(i){return typeof i=="symbol"}:function(i){var e=Km("Symbol");return Jm(e)&&Xm(e.prototype,eb(i))}});var Rr=m((aP,Lu)=>{"use strict";var tb=String;Lu.exports=function(i){try{return tb(i)}catch{return"Object"}}});var it=m((sP,$u)=>{"use strict";var rb=ee(),ib=Rr(),ab=TypeError;$u.exports=function(i){if(rb(i))return i;throw ab(ib(i)+" is not a function")}});var Lr=m((nP,Cu)=>{"use strict";var sb=it(),nb=Xt();Cu.exports=function(i,e){var t=i[e];return nb(t)?void 0:sb(t)}});var Mu=m((oP,Du)=>{"use strict";var Rs=me(),Ls=ee(),$s=Qe(),ob=TypeError;Du.exports=function(i,e){var t,r;if(e==="string"&&Ls(t=i.toString)&&!$s(r=Rs(t,i))||Ls(t=i.valueOf)&&!$s(r=Rs(t,i))||e!=="string"&&Ls(t=i.toString)&&!$s(r=Rs(t,i)))return r;throw ob("Can't convert object to primitive value")}});var qe=m((uP,Ou)=>{"use strict";Ou.exports=!0});var _u=m((lP,Vu)=>{"use strict";var Bu=ne(),ub=Object.defineProperty;Vu.exports=function(i,e){try{ub(Bu,i,{value:e,configurable:!0,writable:!0})}catch{Bu[i]=e}return e}});var ra=m((cP,Fu)=>{"use strict";var lb=ne(),cb=_u(),Nu="__core-js_shared__",db=lb[Nu]||cb(Nu,{});Fu.exports=db});var Cs=m((dP,Uu)=>{"use strict";var pb=qe(),qu=ra();(Uu.exports=function(i,e){return qu[i]||(qu[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:pb?"pure":"global",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var $r=m((pP,Hu)=>{"use strict";var hb=Ki(),fb=Object;Hu.exports=function(i){return fb(hb(i))}});var Ue=m((hP,ju)=>{"use strict";var mb=fe(),bb=$r(),vb=mb({}.hasOwnProperty);ju.exports=Object.hasOwn||function(e,t){return vb(bb(e),t)}});var Ds=m((fP,Gu)=>{"use strict";var gb=fe(),Sb=0,yb=Math.random(),Tb=gb(1 .toString);Gu.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+Tb(++Sb+yb,36)}});var ce=m((mP,Wu)=>{"use strict";var Ib=ne(),Eb=Cs(),Yu=Ue(),xb=Ds(),Pb=ks(),kb=ws(),er=Ib.Symbol,Ms=Eb("wks"),wb=kb?er.for||er:er&&er.withoutSetter||xb;Wu.exports=function(i){return Yu(Ms,i)||(Ms[i]=Pb&&Yu(er,i)?er[i]:wb("Symbol."+i)),Ms[i]}});var Ju=m((bP,Ku)=>{"use strict";var Ab=me(),Qu=Qe(),zu=As(),Rb=Lr(),Lb=Mu(),$b=ce(),Cb=TypeError,Db=$b("toPrimitive");Ku.exports=function(i,e){if(!Qu(i)||zu(i))return i;var t=Rb(i,Db),r;if(t){if(e===void 0&&(e="default"),r=Ab(t,i,e),!Qu(r)||zu(r))return r;throw Cb("Can't convert object to primitive value")}return e===void 0&&(e="number"),Lb(i,e)}});var ia=m((vP,Xu)=>{"use strict";var Mb=Ju(),Ob=As();Xu.exports=function(i){var e=Mb(i,"string");return Ob(e)?e:e+""}});var Lt=m(el=>{"use strict";var Bb=ze(),Vb=ys(),_b=Ts(),aa=Ne(),Zu=ia(),Nb=TypeError,Os=Object.defineProperty,Fb=Object.getOwnPropertyDescriptor,Bs="enumerable",Vs="configurable",_s="writable";el.f=Bb?_b?function(e,t,r){if(aa(e),t=Zu(t),aa(r),typeof e=="function"&&t==="prototype"&&"value"in r&&_s in r&&!r[_s]){var a=Fb(e,t);a&&a[_s]&&(e[t]=r.value,r={configurable:Vs in r?r[Vs]:a[Vs],enumerable:Bs in r?r[Bs]:a[Bs],writable:!1})}return Os(e,t,r)}:Os:function(e,t,r){if(aa(e),t=Zu(t),aa(r),Vb)try{return Os(e,t,r)}catch{}if("get"in r||"set"in r)throw Nb("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Cr=m((SP,tl)=>{"use strict";tl.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var $t=m((yP,rl)=>{"use strict";var qb=ze(),Ub=Lt(),Hb=Cr();rl.exports=qb?function(i,e,t){return Ub.f(i,e,Hb(1,t))}:function(i,e,t){return i[e]=t,i}});var sa=m((TP,al)=>{"use strict";var jb=Cs(),Gb=Ds(),il=jb("keys");al.exports=function(i){return il[i]||(il[i]=Gb(i))}});var na=m((IP,sl)=>{"use strict";sl.exports={}});var Us=m((EP,ul)=>{"use strict";var Yb=au(),ol=ne(),Wb=Qe(),Qb=$t(),Ns=Ue(),Fs=ra(),zb=sa(),Kb=na(),nl="Object already initialized",qs=ol.TypeError,Jb=ol.WeakMap,oa,Dr,ua,Xb=function(i){return ua(i)?Dr(i):oa(i,{})},Zb=function(i){return function(e){var t;if(!Wb(e)||(t=Dr(e)).type!==i)throw qs("Incompatible receiver, "+i+" required");return t}};Yb||Fs.state?(He=Fs.state||(Fs.state=new Jb),He.get=He.get,He.has=He.has,He.set=He.set,oa=function(i,e){if(He.has(i))throw qs(nl);return e.facade=i,He.set(i,e),e},Dr=function(i){return He.get(i)||{}},ua=function(i){return He.has(i)}):(Ct=zb("state"),Kb[Ct]=!0,oa=function(i,e){if(Ns(i,Ct))throw qs(nl);return e.facade=i,Qb(i,Ct,e),e},Dr=function(i){return Ns(i,Ct)?i[Ct]:{}},ua=function(i){return Ns(i,Ct)});var He,Ct;ul.exports={set:oa,get:Dr,has:ua,enforce:Xb,getterFor:Zb}});var Hs=m((xP,pl)=>{"use strict";var ev=kr(),dl=Function.prototype,ll=dl.apply,cl=dl.call;pl.exports=typeof Reflect=="object"&&Reflect.apply||(ev?cl.bind(ll):function(){return cl.apply(ll,arguments)})});var js=m((PP,hl)=>{"use strict";var tv=Jt(),rv=fe();hl.exports=function(i){if(tv(i)==="Function")return rv(i)}});var vl=m(bl=>{"use strict";var fl={}.propertyIsEnumerable,ml=Object.getOwnPropertyDescriptor,iv=ml&&!fl.call({1:2},1);bl.f=iv?function(e){var t=ml(this,e);return!!t&&t.enumerable}:fl});var Gs=m(Sl=>{"use strict";var av=ze(),sv=me(),nv=vl(),ov=Cr(),uv=Zt(),lv=ia(),cv=Ue(),dv=ys(),gl=Object.getOwnPropertyDescriptor;Sl.f=av?gl:function(e,t){if(e=uv(e),t=lv(t),dv)try{return gl(e,t)}catch{}if(cv(e,t))return ov(!sv(nv.f,e,t),e[t])}});var Ys=m((AP,yl)=>{"use strict";var pv=Pe(),hv=ee(),fv=/#|\.prototype\./,Mr=function(i,e){var t=bv[mv(i)];return t==gv?!0:t==vv?!1:hv(e)?pv(e):!!e},mv=Mr.normalize=function(i){return String(i).replace(fv,".").toLowerCase()},bv=Mr.data={},vv=Mr.NATIVE="N",gv=Mr.POLYFILL="P";yl.exports=Mr});var Or=m((RP,Il)=>{"use strict";var Tl=js(),Sv=it(),yv=kr(),Tv=Tl(Tl.bind);Il.exports=function(i,e){return Sv(i),e===void 0?i:yv?Tv(i,e):function(){return i.apply(e,arguments)}}});var Ae=m((LP,xl)=>{"use strict";var la=ne(),Iv=Hs(),Ev=js(),xv=ee(),Pv=Gs().f,kv=Ys(),tr=ea(),wv=Or(),rr=$t(),El=Ue(),Av=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 Iv(i,this,arguments)};return e.prototype=i.prototype,e};xl.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?la:a?la[t]:(la[t]||{}).prototype,o=r?tr:tr[t]||rr(tr,t,{})[t],l=o.prototype,u,c,d,f,h,b,I,v,T;for(f in e)u=kv(r?f:t+(a?".":"#")+f,i.forced),c=!u&&n&&El(n,f),b=o[f],c&&(i.dontCallGetSet?(T=Pv(n,f),I=T&&T.value):I=n[f]),h=c&&I?I:e[f],!(c&&typeof b==typeof h)&&(i.bind&&c?v=wv(h,la):i.wrap&&c?v=Av(h):s&&xv(h)?v=Ev(h):v=h,(i.sham||h&&h.sham||b&&b.sham)&&rr(v,"sham",!0),rr(o,f,v),s&&(d=t+"Prototype",El(tr,d)||rr(tr,d,{}),rr(tr[d],f,h),i.real&&l&&(u||!l[f])&&rr(l,f,h)))}});var wl=m(($P,kl)=>{"use strict";var Ws=ze(),Rv=Ue(),Pl=Function.prototype,Lv=Ws&&Object.getOwnPropertyDescriptor,Qs=Rv(Pl,"name"),$v=Qs&&function(){}.name==="something",Cv=Qs&&(!Ws||Ws&&Lv(Pl,"name").configurable);kl.exports={EXISTS:Qs,PROPER:$v,CONFIGURABLE:Cv}});var Rl=m((CP,Al)=>{"use strict";var Dv=Math.ceil,Mv=Math.floor;Al.exports=Math.trunc||function(e){var t=+e;return(t>0?Mv:Dv)(t)}});var ca=m((DP,Ll)=>{"use strict";var Ov=Rl();Ll.exports=function(i){var e=+i;return e!==e||e===0?0:Ov(e)}});var Cl=m((MP,$l)=>{"use strict";var Bv=ca(),Vv=Math.max,_v=Math.min;$l.exports=function(i,e){var t=Bv(i);return t<0?Vv(t+e,0):_v(t,e)}});var Ml=m((OP,Dl)=>{"use strict";var Nv=ca(),Fv=Math.min;Dl.exports=function(i){return i>0?Fv(Nv(i),9007199254740991):0}});var da=m((BP,Ol)=>{"use strict";var qv=Ml();Ol.exports=function(i){return qv(i.length)}});var _l=m((VP,Vl)=>{"use strict";var Uv=Zt(),Hv=Cl(),jv=da(),Bl=function(i){return function(e,t,r){var a=Uv(e),s=jv(a),n=Hv(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}};Vl.exports={includes:Bl(!0),indexOf:Bl(!1)}});var ql=m((_P,Fl)=>{"use strict";var Gv=fe(),zs=Ue(),Yv=Zt(),Wv=_l().indexOf,Qv=na(),Nl=Gv([].push);Fl.exports=function(i,e){var t=Yv(i),r=0,a=[],s;for(s in t)!zs(Qv,s)&&zs(t,s)&&Nl(a,s);for(;e.length>r;)zs(t,s=e[r++])&&(~Wv(a,s)||Nl(a,s));return a}});var Ks=m((NP,Ul)=>{"use strict";Ul.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var jl=m((FP,Hl)=>{"use strict";var zv=ql(),Kv=Ks();Hl.exports=Object.keys||function(e){return zv(e,Kv)}});var Yl=m(Gl=>{"use strict";var Jv=ze(),Xv=Ts(),Zv=Lt(),eg=Ne(),tg=Zt(),rg=jl();Gl.f=Jv&&!Xv?Object.defineProperties:function(e,t){eg(e);for(var r=tg(t),a=rg(t),s=a.length,n=0,o;s>n;)Zv.f(e,o=a[n++],r[o]);return e}});var Js=m((UP,Wl)=>{"use strict";var ig=rt();Wl.exports=ig("document","documentElement")});var tn=m((HP,ec)=>{"use strict";var ag=Ne(),sg=Yl(),Ql=Ks(),ng=na(),og=Js(),ug=Xi(),lg=sa(),zl=">",Kl="<",Zs="prototype",en="script",Xl=lg("IE_PROTO"),Xs=function(){},Zl=function(i){return Kl+en+zl+i+Kl+"/"+en+zl},Jl=function(i){i.write(Zl("")),i.close();var e=i.parentWindow.Object;return i=null,e},cg=function(){var i=ug("iframe"),e="java"+en+":",t;return i.style.display="none",og.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Zl("document.F=Object")),t.close(),t.F},pa,ha=function(){try{pa=new ActiveXObject("htmlfile")}catch{}ha=typeof document<"u"?document.domain&&pa?Jl(pa):cg():Jl(pa);for(var i=Ql.length;i--;)delete ha[Zs][Ql[i]];return ha()};ng[Xl]=!0;ec.exports=Object.create||function(e,t){var r;return e!==null?(Xs[Zs]=ag(e),r=new Xs,Xs[Zs]=null,r[Xl]=e):r=ha(),t===void 0?r:sg.f(r,t)}});var rc=m((jP,tc)=>{"use strict";var dg=Pe();tc.exports=!dg(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var an=m((GP,ac)=>{"use strict";var pg=Ue(),hg=ee(),fg=$r(),mg=sa(),bg=rc(),ic=mg("IE_PROTO"),rn=Object,vg=rn.prototype;ac.exports=bg?rn.getPrototypeOf:function(i){var e=fg(i);if(pg(e,ic))return e[ic];var t=e.constructor;return hg(t)&&e instanceof t?t.prototype:e instanceof rn?vg:null}});var ir=m((YP,sc)=>{"use strict";var gg=$t();sc.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:gg(i,e,t),i}});var un=m((WP,uc)=>{"use strict";var Sg=Pe(),yg=ee(),Tg=Qe(),Ig=tn(),nc=an(),Eg=ir(),xg=ce(),Pg=qe(),on=xg("iterator"),oc=!1,at,sn,nn;[].keys&&(nn=[].keys(),"next"in nn?(sn=nc(nc(nn)),sn!==Object.prototype&&(at=sn)):oc=!0);var kg=!Tg(at)||Sg(function(){var i={};return at[on].call(i)!==i});kg?at={}:Pg&&(at=Ig(at));yg(at[on])||Eg(at,on,function(){return this});uc.exports={IteratorPrototype:at,BUGGY_SAFARI_ITERATORS:oc}});var fa=m((QP,cc)=>{"use strict";var wg=ce(),Ag=wg("toStringTag"),lc={};lc[Ag]="z";cc.exports=String(lc)==="[object z]"});var ar=m((zP,dc)=>{"use strict";var Rg=fa(),Lg=ee(),ma=Jt(),$g=ce(),Cg=$g("toStringTag"),Dg=Object,Mg=ma(function(){return arguments}())=="Arguments",Og=function(i,e){try{return i[e]}catch{}};dc.exports=Rg?ma:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=Og(e=Dg(i),Cg))=="string"?t:Mg?ma(e):(r=ma(e))=="Object"&&Lg(e.callee)?"Arguments":r}});var hc=m((KP,pc)=>{"use strict";var Bg=fa(),Vg=ar();pc.exports=Bg?{}.toString:function(){return"[object "+Vg(this)+"]"}});var ba=m((JP,mc)=>{"use strict";var _g=fa(),Ng=Lt().f,Fg=$t(),qg=Ue(),Ug=hc(),Hg=ce(),fc=Hg("toStringTag");mc.exports=function(i,e,t,r){if(i){var a=t?i:i.prototype;qg(a,fc)||Ng(a,fc,{configurable:!0,value:e}),r&&!_g&&Fg(a,"toString",Ug)}}});var vc=m((XP,bc)=>{"use strict";var jg=un().IteratorPrototype,Gg=tn(),Yg=Cr(),Wg=ba(),Qg=Rt(),zg=function(){return this};bc.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=Gg(jg,{next:Yg(+!r,t)}),Wg(i,a,!1,!0),Qg[a]=zg,i}});var Sc=m((ZP,gc)=>{"use strict";var Kg=fe(),Jg=it();gc.exports=function(i,e,t){try{return Kg(Jg(Object.getOwnPropertyDescriptor(i,e)[t]))}catch{}}});var Tc=m((ek,yc)=>{"use strict";var Xg=ee(),Zg=String,eS=TypeError;yc.exports=function(i){if(typeof i=="object"||Xg(i))return i;throw eS("Can't set "+Zg(i)+" as a prototype")}});var ln=m((tk,Ic)=>{"use strict";var tS=Sc(),rS=Ne(),iS=Tc();Ic.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=tS(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch{}return function(a,s){return rS(a),iS(s),i?t(a,s):a.__proto__=s,a}}():void 0)});var Dc=m((rk,Cc)=>{"use strict";var aS=Ae(),sS=me(),va=qe(),Lc=wl(),nS=ee(),oS=vc(),Ec=an(),xc=ln(),uS=ba(),lS=$t(),cn=ir(),cS=ce(),Pc=Rt(),$c=un(),dS=Lc.PROPER,pS=Lc.CONFIGURABLE,kc=$c.IteratorPrototype,ga=$c.BUGGY_SAFARI_ITERATORS,Br=cS("iterator"),wc="keys",Vr="values",Ac="entries",Rc=function(){return this};Cc.exports=function(i,e,t,r,a,s,n){oS(t,e,r);var o=function(T){if(T===a&&f)return f;if(!ga&&T in c)return c[T];switch(T){case wc:return function(){return new t(this,T)};case Vr:return function(){return new t(this,T)};case Ac:return function(){return new t(this,T)}}return function(){return new t(this)}},l=e+" Iterator",u=!1,c=i.prototype,d=c[Br]||c["@@iterator"]||a&&c[a],f=!ga&&d||o(a),h=e=="Array"&&c.entries||d,b,I,v;if(h&&(b=Ec(h.call(new i)),b!==Object.prototype&&b.next&&(!va&&Ec(b)!==kc&&(xc?xc(b,kc):nS(b[Br])||cn(b,Br,Rc)),uS(b,l,!0,!0),va&&(Pc[l]=Rc))),dS&&a==Vr&&d&&d.name!==Vr&&(!va&&pS?lS(c,"name",Vr):(u=!0,f=function(){return sS(d,this)})),a)if(I={values:o(Vr),keys:s?f:o(wc),entries:o(Ac)},n)for(v in I)(ga||u||!(v in c))&&cn(c,v,I[v]);else aS({target:e,proto:!0,forced:ga||u},I);return(!va||n)&&c[Br]!==f&&cn(c,Br,f,{name:a}),Pc[e]=f,I}});var Oc=m((ik,Mc)=>{"use strict";Mc.exports=function(i,e){return{value:i,done:e}}});var pn=m((ak,Fc)=>{"use strict";var hS=Zt(),dn=bs(),Bc=Rt(),_c=Us(),fS=Lt().f,mS=Dc(),Sa=Oc(),bS=qe(),vS=ze(),Nc="Array Iterator",gS=_c.set,SS=_c.getterFor(Nc);Fc.exports=mS(Array,"Array",function(i,e){gS(this,{type:Nc,target:hS(i),index:0,kind:e})},function(){var i=SS(this),e=i.target,t=i.kind,r=i.index++;return!e||r>=e.length?(i.target=void 0,Sa(void 0,!0)):t=="keys"?Sa(r,!1):t=="values"?Sa(e[r],!1):Sa([r,e[r]],!1)},"values");var Vc=Bc.Arguments=Bc.Array;dn("keys");dn("values");dn("entries");if(!bS&&vS&&Vc.name!=="values")try{fS(Vc,"name",{value:"values"})}catch{}});var Uc=m((sk,qc)=>{"use strict";var yS=ce(),TS=Rt(),IS=yS("iterator"),ES=Array.prototype;qc.exports=function(i){return i!==void 0&&(TS.Array===i||ES[IS]===i)}});var hn=m((nk,jc)=>{"use strict";var xS=ar(),Hc=Lr(),PS=Xt(),kS=Rt(),wS=ce(),AS=wS("iterator");jc.exports=function(i){if(!PS(i))return Hc(i,AS)||Hc(i,"@@iterator")||kS[xS(i)]}});var Yc=m((ok,Gc)=>{"use strict";var RS=me(),LS=it(),$S=Ne(),CS=Rr(),DS=hn(),MS=TypeError;Gc.exports=function(i,e){var t=arguments.length<2?DS(i):e;if(LS(t))return $S(RS(t,i));throw MS(CS(i)+" is not iterable")}});var zc=m((uk,Qc)=>{"use strict";var OS=me(),Wc=Ne(),BS=Lr();Qc.exports=function(i,e,t){var r,a;Wc(i);try{if(r=BS(i,"return"),!r){if(e==="throw")throw t;return t}r=OS(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return Wc(r),t}});var Ta=m((lk,Zc)=>{"use strict";var VS=Or(),_S=me(),NS=Ne(),FS=Rr(),qS=Uc(),US=da(),Kc=wr(),HS=Yc(),jS=hn(),Jc=zc(),GS=TypeError,ya=function(i,e){this.stopped=i,this.result=e},Xc=ya.prototype;Zc.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=VS(e,r),u,c,d,f,h,b,I,v=function(y){return u&&Jc(u,"normal",y),new ya(!0,y)},T=function(y){return a?(NS(y),o?l(y[0],y[1],v):l(y[0],y[1])):o?l(y,v):l(y)};if(s)u=i.iterator;else if(n)u=i;else{if(c=jS(i),!c)throw GS(FS(i)+" is not iterable");if(qS(c)){for(d=0,f=US(i);f>d;d++)if(h=T(i[d]),h&&Kc(Xc,h))return h;return new ya(!1)}u=HS(i,c)}for(b=s?i.next:u.next;!(I=_S(b,u)).done;){try{h=T(I.value)}catch(y){Jc(u,"throw",y)}if(typeof h=="object"&&h&&Kc(Xc,h))return h}return new ya(!1)}});var td=m((ck,ed)=>{"use strict";var YS=ia(),WS=Lt(),QS=Cr();ed.exports=function(i,e,t){var r=YS(e);r in i?WS.f(i,r,QS(0,t)):i[r]=t}});var rd=m(()=>{"use strict";var zS=Ae(),KS=Ta(),JS=td();zS({target:"Object",stat:!0},{fromEntries:function(e){var t={};return KS(e,function(r,a){JS(t,r,a)},{AS_ENTRIES:!0}),t}})});var ad=m((hk,id)=>{"use strict";pn();rd();var XS=ea();id.exports=XS.Object.fromEntries});var nd=m((fk,sd)=>{"use strict";sd.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 ld=m(()=>{"use strict";pn();var ZS=nd(),ey=ne(),ty=ar(),ry=$t(),od=Rt(),iy=ce(),ud=iy("toStringTag");for(Ia in ZS)fn=ey[Ia],Ea=fn&&fn.prototype,Ea&&ty(Ea)!==ud&&ry(Ea,ud,Ia),od[Ia]=od.Array;var fn,Ea,Ia});var dd=m((vk,cd)=>{"use strict";var ay=ad();ld();cd.exports=ay});var xa=m((gk,pd)=>{"use strict";var sy=dd();pd.exports=sy});var hd=m(()=>{"use strict"});var _r=m((Tk,fd)=>{"use strict";var ny=Jt();fd.exports=typeof process<"u"&&ny(process)=="process"});var bd=m((Ik,md)=>{"use strict";var oy=Lt();md.exports=function(i,e,t){return oy.f(i,e,t)}});var Sd=m((Ek,gd)=>{"use strict";var uy=rt(),ly=bd(),cy=ce(),dy=ze(),vd=cy("species");gd.exports=function(i){var e=uy(i);dy&&e&&!e[vd]&&ly(e,vd,{configurable:!0,get:function(){return this}})}});var Td=m((xk,yd)=>{"use strict";var py=wr(),hy=TypeError;yd.exports=function(i,e){if(py(e,i))return i;throw hy("Incorrect invocation")}});var bn=m((Pk,Id)=>{"use strict";var fy=fe(),my=ee(),mn=ra(),by=fy(Function.toString);my(mn.inspectSource)||(mn.inspectSource=function(i){return by(i)});Id.exports=mn.inspectSource});var Ad=m((kk,wd)=>{"use strict";var vy=fe(),gy=Pe(),Ed=ee(),Sy=ar(),yy=rt(),Ty=bn(),xd=function(){},Iy=[],Pd=yy("Reflect","construct"),vn=/^\s*(?:class|function)\b/,Ey=vy(vn.exec),xy=!vn.exec(xd),Nr=function(e){if(!Ed(e))return!1;try{return Pd(xd,Iy,e),!0}catch{return!1}},kd=function(e){if(!Ed(e))return!1;switch(Sy(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return xy||!!Ey(vn,Ty(e))}catch{return!0}};kd.sham=!0;wd.exports=!Pd||gy(function(){var i;return Nr(Nr.call)||!Nr(Object)||!Nr(function(){i=!0})||i})?kd:Nr});var Ld=m((wk,Rd)=>{"use strict";var Py=Ad(),ky=Rr(),wy=TypeError;Rd.exports=function(i){if(Py(i))return i;throw wy(ky(i)+" is not a constructor")}});var gn=m((Ak,Cd)=>{"use strict";var $d=Ne(),Ay=Ld(),Ry=Xt(),Ly=ce(),$y=Ly("species");Cd.exports=function(i,e){var t=$d(i).constructor,r;return t===void 0||Ry(r=$d(t)[$y])?e:Ay(r)}});var Md=m((Rk,Dd)=>{"use strict";var Cy=fe();Dd.exports=Cy([].slice)});var Bd=m((Lk,Od)=>{"use strict";var Dy=TypeError;Od.exports=function(i,e){if(i<e)throw Dy("Not enough arguments");return i}});var Sn=m(($k,Vd)=>{"use strict";var My=Ar();Vd.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(My)});var An=m((Ck,Yd)=>{"use strict";var ke=ne(),Oy=Hs(),By=Or(),_d=ee(),Vy=Ue(),Gd=Pe(),Nd=Js(),_y=Md(),Fd=Xi(),Ny=Bd(),Fy=Sn(),qy=_r(),Pn=ke.setImmediate,kn=ke.clearImmediate,Uy=ke.process,yn=ke.Dispatch,Hy=ke.Function,qd=ke.MessageChannel,jy=ke.String,Tn=0,Fr={},Ud="onreadystatechange",qr,Dt,In,En;Gd(function(){qr=ke.location});var wn=function(i){if(Vy(Fr,i)){var e=Fr[i];delete Fr[i],e()}},xn=function(i){return function(){wn(i)}},Hd=function(i){wn(i.data)},jd=function(i){ke.postMessage(jy(i),qr.protocol+"//"+qr.host)};(!Pn||!kn)&&(Pn=function(e){Ny(arguments.length,1);var t=_d(e)?e:Hy(e),r=_y(arguments,1);return Fr[++Tn]=function(){Oy(t,void 0,r)},Dt(Tn),Tn},kn=function(e){delete Fr[e]},qy?Dt=function(i){Uy.nextTick(xn(i))}:yn&&yn.now?Dt=function(i){yn.now(xn(i))}:qd&&!Fy?(In=new qd,En=In.port2,In.port1.onmessage=Hd,Dt=By(En.postMessage,En)):ke.addEventListener&&_d(ke.postMessage)&&!ke.importScripts&&qr&&qr.protocol!=="file:"&&!Gd(jd)?(Dt=jd,ke.addEventListener("message",Hd,!1)):Ud in Fd("script")?Dt=function(i){Nd.appendChild(Fd("script"))[Ud]=function(){Nd.removeChild(this),wn(i)}}:Dt=function(i){setTimeout(xn(i),0)});Yd.exports={set:Pn,clear:kn}});var Rn=m((Dk,Qd)=>{"use strict";var Wd=function(){this.head=null,this.tail=null};Wd.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}}};Qd.exports=Wd});var Kd=m((Mk,zd)=>{"use strict";var Gy=Ar();zd.exports=/ipad|iphone|ipod/i.test(Gy)&&typeof Pebble<"u"});var Xd=m((Ok,Jd)=>{"use strict";var Yy=Ar();Jd.exports=/web0s(?!.*chrome)/i.test(Yy)});var np=m((Bk,sp)=>{"use strict";var Mt=ne(),Zd=Or(),Wy=Gs().f,Ln=An().set,Qy=Rn(),zy=Sn(),Ky=Kd(),Jy=Xd(),$n=_r(),ep=Mt.MutationObserver||Mt.WebKitMutationObserver,tp=Mt.document,rp=Mt.process,Pa=Mt.Promise,ip=Wy(Mt,"queueMicrotask"),Mn=ip&&ip.value,sr,Cn,Dn,ka,ap;Mn||(Ur=new Qy,Hr=function(){var i,e;for($n&&(i=rp.domain)&&i.exit();e=Ur.get();)try{e()}catch(t){throw Ur.head&&sr(),t}i&&i.enter()},!zy&&!$n&&!Jy&&ep&&tp?(Cn=!0,Dn=tp.createTextNode(""),new ep(Hr).observe(Dn,{characterData:!0}),sr=function(){Dn.data=Cn=!Cn}):!Ky&&Pa&&Pa.resolve?(ka=Pa.resolve(void 0),ka.constructor=Pa,ap=Zd(ka.then,ka),sr=function(){ap(Hr)}):$n?sr=function(){rp.nextTick(Hr)}:(Ln=Zd(Ln,Mt),sr=function(){Ln(Hr)}),Mn=function(i){Ur.head||sr(),Ur.add(i)});var Ur,Hr;sp.exports=Mn});var up=m((Vk,op)=>{"use strict";op.exports=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch{}}});var wa=m((_k,lp)=>{"use strict";lp.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var Ot=m((Nk,cp)=>{"use strict";var Xy=ne();cp.exports=Xy.Promise});var On=m((Fk,dp)=>{"use strict";dp.exports=typeof Deno=="object"&&Deno&&typeof Deno.version=="object"});var hp=m((qk,pp)=>{"use strict";var Zy=On(),eT=_r();pp.exports=!Zy&&!eT&&typeof window=="object"&&typeof document=="object"});var nr=m((Uk,bp)=>{"use strict";var tT=ne(),jr=Ot(),rT=ee(),iT=Ys(),aT=bn(),sT=ce(),nT=hp(),oT=On(),uT=qe(),Bn=Ps(),fp=jr&&jr.prototype,lT=sT("species"),Vn=!1,mp=rT(tT.PromiseRejectionEvent),cT=iT("Promise",function(){var i=aT(jr),e=i!==String(jr);if(!e&&Bn===66||uT&&!(fp.catch&&fp.finally))return!0;if(!Bn||Bn<51||!/native code/.test(i)){var t=new jr(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[lT]=r,Vn=t.then(function(){})instanceof r,!Vn)return!0}return!e&&(nT||oT)&&!mp});bp.exports={CONSTRUCTOR:cT,REJECTION_EVENT:mp,SUBCLASSING:Vn}});var or=m((Hk,gp)=>{"use strict";var vp=it(),dT=TypeError,pT=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw dT("Bad Promise constructor");e=r,t=a}),this.resolve=vp(e),this.reject=vp(t)};gp.exports.f=function(i){return new pT(i)}});var Vp=m(()=>{"use strict";var hT=Ae(),fT=qe(),$a=_r(),yt=ne(),dr=me(),Sp=ir(),yp=ln(),mT=ba(),bT=Sd(),vT=it(),La=ee(),gT=Qe(),ST=Td(),yT=gn(),Pp=An().set,Un=np(),TT=up(),IT=wa(),ET=Rn(),kp=Us(),Ca=Ot(),Hn=nr(),wp=or(),Da="Promise",Ap=Hn.CONSTRUCTOR,xT=Hn.REJECTION_EVENT,PT=Hn.SUBCLASSING,_n=kp.getterFor(Da),kT=kp.set,ur=Ca&&Ca.prototype,Bt=Ca,Aa=ur,Rp=yt.TypeError,Nn=yt.document,jn=yt.process,Fn=wp.f,wT=Fn,AT=!!(Nn&&Nn.createEvent&&yt.dispatchEvent),Lp="unhandledrejection",RT="rejectionhandled",Tp=0,$p=1,LT=2,Gn=1,Cp=2,Ra,Ip,$T,Ep,Dp=function(i){var e;return gT(i)&&La(e=i.then)?e:!1},Mp=function(i,e){var t=e.value,r=e.state==$p,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,l,u,c;try{a?(r||(e.rejection===Cp&&DT(e),e.rejection=Gn),a===!0?l=t:(o&&o.enter(),l=a(t),o&&(o.exit(),c=!0)),l===i.promise?n(Rp("Promise-chain cycle")):(u=Dp(l))?dr(u,l,s,n):s(l)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Op=function(i,e){i.notified||(i.notified=!0,Un(function(){for(var t=i.reactions,r;r=t.get();)Mp(r,i);i.notified=!1,e&&!i.rejection&&CT(i)}))},Bp=function(i,e,t){var r,a;AT?(r=Nn.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),yt.dispatchEvent(r)):r={promise:e,reason:t},!xT&&(a=yt["on"+i])?a(r):i===Lp&&TT("Unhandled promise rejection",t)},CT=function(i){dr(Pp,yt,function(){var e=i.facade,t=i.value,r=xp(i),a;if(r&&(a=IT(function(){$a?jn.emit("unhandledRejection",t,e):Bp(Lp,e,t)}),i.rejection=$a||xp(i)?Cp:Gn,a.error))throw a.value})},xp=function(i){return i.rejection!==Gn&&!i.parent},DT=function(i){dr(Pp,yt,function(){var e=i.facade;$a?jn.emit("rejectionHandled",e):Bp(RT,e,i.value)})},lr=function(i,e,t){return function(r){i(e,r,t)}},cr=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=LT,Op(i,!0))},qn=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw Rp("Promise can't be resolved itself");var r=Dp(e);r?Un(function(){var a={done:!1};try{dr(r,e,lr(qn,a,i),lr(cr,a,i))}catch(s){cr(a,s,i)}}):(i.value=e,i.state=$p,Op(i,!1))}catch(a){cr({done:!1},a,i)}}};if(Ap&&(Bt=function(e){ST(this,Aa),vT(e),dr(Ra,this);var t=_n(this);try{e(lr(qn,t),lr(cr,t))}catch(r){cr(t,r)}},Aa=Bt.prototype,Ra=function(e){kT(this,{type:Da,done:!1,notified:!1,parent:!1,reactions:new ET,rejection:!1,state:Tp,value:void 0})},Ra.prototype=Sp(Aa,"then",function(e,t){var r=_n(this),a=Fn(yT(this,Bt));return r.parent=!0,a.ok=La(e)?e:!0,a.fail=La(t)&&t,a.domain=$a?jn.domain:void 0,r.state==Tp?r.reactions.add(a):Un(function(){Mp(a,r)}),a.promise}),Ip=function(){var i=new Ra,e=_n(i);this.promise=i,this.resolve=lr(qn,e),this.reject=lr(cr,e)},wp.f=Fn=function(i){return i===Bt||i===$T?new Ip(i):wT(i)},!fT&&La(Ca)&&ur!==Object.prototype)){Ep=ur.then,PT||Sp(ur,"then",function(e,t){var r=this;return new Bt(function(a,s){dr(Ep,r,a,s)}).then(e,t)},{unsafe:!0});try{delete ur.constructor}catch{}yp&&yp(ur,Aa)}hT({global:!0,constructor:!0,wrap:!0,forced:Ap},{Promise:Bt});mT(Bt,Da,!1,!0);bT(Da)});var Up=m((Yk,qp)=>{"use strict";var MT=ce(),Np=MT("iterator"),Fp=!1;try{_p=0,Yn={next:function(){return{done:!!_p++}},return:function(){Fp=!0}},Yn[Np]=function(){return this},Array.from(Yn,function(){throw 2})}catch{}var _p,Yn;qp.exports=function(i,e){if(!e&&!Fp)return!1;var t=!1;try{var r={};r[Np]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch{}return t}});var Wn=m((Wk,Hp)=>{"use strict";var OT=Ot(),BT=Up(),VT=nr().CONSTRUCTOR;Hp.exports=VT||!BT(function(i){OT.all(i).then(void 0,function(){})})});var jp=m(()=>{"use strict";var _T=Ae(),NT=me(),FT=it(),qT=or(),UT=wa(),HT=Ta(),jT=Wn();_T({target:"Promise",stat:!0,forced:jT},{all:function(e){var t=this,r=qT.f(t),a=r.resolve,s=r.reject,n=UT(function(){var o=FT(t.resolve),l=[],u=0,c=1;HT(e,function(d){var f=u++,h=!1;c++,NT(o,t,d).then(function(b){h||(h=!0,l[f]=b,--c||a(l))},s)}),--c||a(l)});return n.error&&s(n.value),r.promise}})});var Yp=m(()=>{"use strict";var GT=Ae(),YT=qe(),WT=nr().CONSTRUCTOR,zn=Ot(),QT=rt(),zT=ee(),KT=ir(),Gp=zn&&zn.prototype;GT({target:"Promise",proto:!0,forced:WT,real:!0},{catch:function(i){return this.then(void 0,i)}});!YT&&zT(zn)&&(Qn=QT("Promise").prototype.catch,Gp.catch!==Qn&&KT(Gp,"catch",Qn,{unsafe:!0}));var Qn});var Wp=m(()=>{"use strict";var JT=Ae(),XT=me(),ZT=it(),eI=or(),tI=wa(),rI=Ta(),iI=Wn();JT({target:"Promise",stat:!0,forced:iI},{race:function(e){var t=this,r=eI.f(t),a=r.reject,s=tI(function(){var n=ZT(t.resolve);rI(e,function(o){XT(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var Qp=m(()=>{"use strict";var aI=Ae(),sI=me(),nI=or(),oI=nr().CONSTRUCTOR;aI({target:"Promise",stat:!0,forced:oI},{reject:function(e){var t=nI.f(this);return sI(t.reject,void 0,e),t.promise}})});var Kn=m((rw,zp)=>{"use strict";var uI=Ne(),lI=Qe(),cI=or();zp.exports=function(i,e){if(uI(i),lI(e)&&e.constructor===i)return e;var t=cI.f(i),r=t.resolve;return r(e),t.promise}});var Xp=m(()=>{"use strict";var dI=Ae(),pI=rt(),Kp=qe(),hI=Ot(),Jp=nr().CONSTRUCTOR,fI=Kn(),mI=pI("Promise"),bI=Kp&&!Jp;dI({target:"Promise",stat:!0,forced:Kp||Jp},{resolve:function(e){return fI(bI&&this===mI?hI:this,e)}})});var Zp=m(()=>{"use strict";Vp();jp();Yp();Wp();Qp();Xp()});var ih=m(()=>{"use strict";var vI=Ae(),gI=qe(),Ma=Ot(),SI=Pe(),th=rt(),rh=ee(),yI=gn(),eh=Kn(),TI=ir(),Xn=Ma&&Ma.prototype,II=!!Ma&&SI(function(){Xn.finally.call({then:function(){}},function(){})});vI({target:"Promise",proto:!0,real:!0,forced:II},{finally:function(i){var e=yI(this,th("Promise")),t=rh(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)}});!gI&&rh(Ma)&&(Jn=th("Promise").prototype.finally,Xn.finally!==Jn&&TI(Xn,"finally",Jn,{unsafe:!0}));var Jn});var Oa=m((lw,ah)=>{"use strict";var EI=rt();ah.exports=EI});var nh=m((cw,sh)=>{"use strict";hd();Zp();ih();var xI=Oa();sh.exports=xI("Promise","finally")});var uh=m((dw,oh)=>{"use strict";var PI=nh();oh.exports=PI});var Ba=m((pw,lh)=>{"use strict";var kI=uh();lh.exports=kI});var gh=m(()=>{"use strict";var DI=Ae(),MI=$r(),OI=da(),BI=ca(),VI=bs();DI({target:"Array",proto:!0},{at:function(e){var t=MI(this),r=OI(t),a=BI(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});VI("at")});var yh=m((hA,Sh)=>{"use strict";gh();var _I=Oa();Sh.exports=_I("Array","at")});var Ih=m((fA,Th)=>{"use strict";var NI=yh();Th.exports=NI});var _a=m((mA,Eh)=>{"use strict";var FI=Ih();Eh.exports=FI});var Uh=m(()=>{"use strict"});var Hh=m(()=>{"use strict"});var Gh=m((G$,jh)=>{"use strict";var bE=Qe(),vE=Jt(),gE=ce(),SE=gE("match");jh.exports=function(i){var e;return bE(i)&&((e=i[SE])!==void 0?!!e:vE(i)=="RegExp")}});var Wh=m((Y$,Yh)=>{"use strict";var yE=ar(),TE=String;Yh.exports=function(i){if(yE(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return TE(i)}});var zh=m((W$,Qh)=>{"use strict";var IE=Ne();Qh.exports=function(){var i=IE(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 Xh=m((Q$,Jh)=>{"use strict";var EE=me(),xE=Ue(),PE=wr(),kE=zh(),Kh=RegExp.prototype;Jh.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in Kh)&&!xE(i,"flags")&&PE(Kh,i)?EE(kE,i):e}});var ef=m((z$,Zh)=>{"use strict";var So=fe(),wE=$r(),AE=Math.floor,vo=So("".charAt),RE=So("".replace),go=So("".slice),LE=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,$E=/\$([$&'`]|\d{1,2})/g;Zh.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,l=$E;return a!==void 0&&(a=wE(a),l=LE),RE(s,l,function(u,c){var d;switch(vo(c,0)){case"$":return"$";case"&":return i;case"`":return go(e,0,t);case"'":return go(e,n);case"<":d=a[go(c,1,-1)];break;default:var f=+c;if(f===0)return u;if(f>o){var h=AE(f/10);return h===0?u:h<=o?r[h-1]===void 0?vo(c,1):r[h-1]+vo(c,1):u}d=r[f-1]}return d===void 0?"":d})}});var nf=m(()=>{"use strict";var CE=Ae(),DE=me(),yo=fe(),tf=Ki(),ME=ee(),OE=Xt(),BE=Gh(),br=Wh(),VE=Lr(),_E=Xh(),NE=ef(),FE=ce(),qE=qe(),UE=FE("replace"),HE=TypeError,sf=yo("".indexOf),jE=yo("".replace),rf=yo("".slice),GE=Math.max,af=function(i,e,t){return t>i.length?-1:e===""?t:sf(i,e,t)};CE({target:"String",proto:!0},{replaceAll:function(e,t){var r=tf(this),a,s,n,o,l,u,c,d,f,h=0,b=0,I="";if(!OE(e)){if(a=BE(e),a&&(s=br(tf(_E(e))),!~sf(s,"g")))throw HE("`.replaceAll` does not allow non-global regexes");if(n=VE(e,UE),n)return DE(n,e,r,t);if(qE&&a)return jE(br(r),e,t)}for(o=br(r),l=br(e),u=ME(t),u||(t=br(t)),c=l.length,d=GE(1,c),h=af(o,l,0);h!==-1;)f=u?br(t(l,h,o)):NE(l,o,h,[],void 0,t),I+=rf(o,b,h)+f,b=h+c,h=af(o,l,h+d);return b<o.length&&(I+=rf(o,b)),I}})});var uf=m((X$,of)=>{"use strict";Uh();Hh();nf();var YE=Oa();of.exports=YE("String","replaceAll")});var cf=m((Z$,lf)=>{"use strict";var WE=uf();lf.exports=WE});var pf=m((eC,df)=>{"use strict";var QE=cf();df.exports=QE});var bx={};pm(bx,{ChromecastState:()=>Pr,HttpConnectionType:()=>Wi,Observable:()=>et.Observable,PlaybackState:()=>he,Player:()=>Fi,SDK_VERSION:()=>mx,Subject:()=>et.Subject,Subscription:()=>et.Subscription,Surface:()=>Qi,VERSION:()=>hs,ValueSubject:()=>et.ValueSubject,VideoFormat:()=>St,VideoQuality:()=>et.VideoQuality});module.exports=hm(bx);var hs="__VERSION__";var he=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(he||{}),St=(y=>(y.MPEG="MPEG",y.DASH="DASH_SEP",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(St||{});var Pr=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(Pr||{}),Wi=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Wi||{});var Qi=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Qi||{});var V=require("@vkontakte/videoplayer-shared");var Bo=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 zi=class{constructor(e){this.connection$=new V.ValueSubject(void 0);this.castState$=new V.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new V.Subject;this.realCastState$=new V.ValueSubject("NOT_AVAILABLE");this.subscription=new V.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,V.isNonNullable)(window.chrome?.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},a||Bo("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:V.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,V.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,V.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,V.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,V.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,V.assertNever)(a.sessionState)}})).add((0,V.merge)((0,V.fromEvent)(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,V.tap)(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),(0,V.map)(a=>a.castState)),(0,V.observableFrom)([r.getCastState()])).pipe((0,V.filterChanged)(),(0,V.map)(fm),(0,V.tap)(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=(0,V.isNonNullable)(this.connection$.getValue());if(s&&!n){let o=r.getCurrentSession();(0,V.assertNonNullable)(o);let l=o.getCastDevice(),u=o.getMediaSession()?.media.contentId;((0,V.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,V.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:V.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,V.assertNever)(i)}};var Gf=_e(xa(),1);var hh=_e(Ba(),1);var Zn=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,Zn.assertNever)(t)}return i},eo=(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,Zn.assertNever)(e)}};var P=(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 ch=require("@vkontakte/videoplayer-shared"),dh=i=>{switch(i){case"MPEG":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":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 R=require("@vkontakte/videoplayer-shared");var wI=5,AI=5,RI=500,ph=7e3,Gr=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(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 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)(RI)).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)>wI)&&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(),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<AI&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),P(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"),P(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),P(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"),P(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),P(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&P(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 c=(0,R.getHighestQuality)(Object.keys(u));(0,R.assertNonNullable)(c);let d=u[c];(0,R.assertNonNullable)(d),r=d,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":{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=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:R.ErrorCategory.VIDEO_PIPELINE,message:u,thrown:c}),c}case"DASH_LIVE_WEBM":throw new Error("DASH_LIVE_WEBM 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:l}=this.params.meta;return(0,R.isNonNullable)(o)&&(n.metadata.title=o),(0,R.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,R.timeout)(ph).subscribe(()=>s(`timeout(${ph})`)))});(0,hh.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 Yr=i=>{i.removeAttribute("src"),i.load()};var fh=i=>{try{i.pause(),i.playbackRate=0,Yr(i),i.remove()}catch(e){console.error(e)}};var to=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)}},ro=window.WeakMap?new WeakMap:new to,be=i=>{let e=i.querySelector("video"),t=!!e;return e?Yr(e):(e=document.createElement("video"),i.appendChild(e)),ro.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},ve=i=>{let e=ro.get(i);ro.delete(i),e?Yr(i):fh(i)};var L=require("@vkontakte/videoplayer-shared");var Tt=require("@vkontakte/videoplayer-shared"),Va=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),l=(0,Tt.isNullable)(a),u=new Tt.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},Je=(i,e,t)=>Va(e,()=>i.loop,r=>{(0,Tt.isNonNullable)(r)&&(i.loop=r)},{onError:t}),ge=(i,e,t,r)=>Va(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}),Re=(i,e,t,r)=>Va(e,()=>i.playbackRate,a=>{(0,Tt.isNonNullable)(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),It=Va;var LI=i=>["__",i.language,i.label].join("|"),$I=(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 L.Subject;this.current$=new L.ValueSubject(void 0);this.error$=new L.Subject;this.subscription=new L.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:L.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,L.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,L.isNonNullable)(s)&&(0,L.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},l)=>o===n[l].id),changed$:this.available$.pipe((0,L.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(It(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{(0,L.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,L.isNonNullable)(s)&&(0,L.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},l)=>o===n[l].id),changed$:this.available$.pipe((0,L.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,L.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,L.fromEvent)(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add((0,L.merge)((0,L.fromEvent)(e,"addtrack"),(0,L.fromEvent)(e,"removetrack"),(0,L.observableFrom)(["init"])).pipe((0,L.map)(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),(0,L.filterChanged)((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add((0,L.merge)((0,L.fromEvent)(e,"change"),(0,L.observableFrom)(["init"])).pipe((0,L.map)(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),(0,L.map)(r=>r&&this.htmlTextTrackToITextTrack(r).id),(0,L.filterChanged)()).subscribe(this.current$));let t=r=>this.applyCueSettings(r.target?.activeCues??null);this.subscription.add((0,L.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,L.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,L.isNonNullable)(t.align)&&(a.align=t.align),(0,L.isNonNullable)(t.position)&&(a.position=t.position),(0,L.isNonNullable)(t.size)&&(a.size=t.size),(0,L.isNonNullable)(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,L.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:LI(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,L.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,L.isNullable)(e)||!$I(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,L.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,L.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)}},Le=io;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 mh=i=>{let e=i;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},ao=i=>{let e=mh(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},bh=i=>{let e=mh(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};var A=require("@vkontakte/videoplayer-shared");var CI=3,vh=(i,e,t=CI)=>{let r=0,a=0;for(let s=0;s<i.length;s++){let n=i.start(s),o=i.end(s);if(n<=e&&e<=o){if(r=n,a=o,!t)return{from:r,to:a};for(let l=s-1;l>=0;l--)i.end(l)+t>=r&&(r=i.start(l));for(let l=s+1;l<i.length;l++)i.start(l)-t<=a&&(a=i.end(l))}}return{from:r,to:a}};var Se=i=>{let e=M=>(0,A.fromEvent)(i,M).pipe((0,A.mapTo)(void 0)),r=(0,A.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(M=>(0,A.fromEvent)(i,M))).pipe((0,A.map)(M=>M.type==="ended"?i.readyState<2:i.readyState<3),(0,A.filterChanged)()),a=(0,A.merge)((0,A.fromEvent)(i,"progress"),(0,A.fromEvent)(i,"timeupdate")).pipe((0,A.map)(()=>vh(i.buffered,i.currentTime))),n=(0,A.getCurrentBrowser)().browser===A.CurrentClientBrowser.Safari?(0,A.combine)({play:e("play").pipe((0,A.once)()),playing:e("playing")}).pipe((0,A.mapTo)(void 0)):e("playing"),o=(0,A.fromEvent)(i,"volumechange").pipe((0,A.map)(()=>({muted:i.muted,volume:i.volume}))),l=(0,A.fromEvent)(i,"ratechange").pipe((0,A.map)(()=>i.playbackRate)),u=(0,A.fromEvent)(i,"error").pipe((0,A.filter)(()=>!!(i.error||i.played.length)),(0,A.map)(()=>{let M=i.error;return{id:M?`MediaError#${M.code}`:"HtmlVideoError",category:A.ErrorCategory.VIDEO_PIPELINE,message:M?M.message:"Error event from HTML video element",thrown:i.error??void 0}})),c=(0,A.fromEvent)(i,"timeupdate").pipe((0,A.map)(()=>i.currentTime)),d=new A.Subject,f=.3,h;c.subscribe(M=>{i.loop&&(0,A.isNonNullable)(h)&&(0,A.isNonNullable)(M)&&h>=i.duration-f&&M<=f&&d.next(h),h=M});let b=(0,A.fromEvent)(i,"enterpictureinpicture"),I=(0,A.fromEvent)(i,"leavepictureinpicture"),v=new A.ValueSubject(bh(i));b.subscribe(()=>v.next(!0)),I.subscribe(()=>v.next(!1));let T=new A.ValueSubject(ao(i));return(0,A.fromEvent)(i,"fullscreenchange").pipe((0,A.map)(()=>ao(i))).subscribe(T),{playing$:n,pause$:e("pause").pipe((0,A.filter)(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:d,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:(0,A.fromEvent)(i,"durationchange").pipe((0,A.map)(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:o,playbackRateState$:l,inPiP$:v,inFullscreen$:T}};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 no=_e(_a(),1),F=require("@vkontakte/videoplayer-shared");var so=!1,ut={},xh=i=>{so=i},Ph=()=>{ut={}},kh=i=>{i(ut)},Wr=(i,e)=>{so&&(ut.meta=ut.meta??{},ut.meta[i]=e)},pe=class{constructor(e){this.name=e}next(e){if(!so)return;ut.series=ut.series??{};let t=ut.series[this.name]??[];t.push([Date.now(),e]),ut.series[this.name]=t}};var qI=new pe("best_bitrate"),UI=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t,Na=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,F.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},HI='Assertion "ABR Tracks is empty array" failed',jI=(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,F.assertNotEmptyArray)(i,HI);let f=r.usePixelRatio?window.devicePixelRatio??1:1,h=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*f*r.containerSizeFactor,height:e.height*f*r.containerSizeFactor},b=h&&(0,F.videoSizeToQuality)(h),I=r.considerPlaybackRate&&(0,F.isNonNullable)(o)?o:1,v=i.filter(w=>!(0,F.isInvariantQuality)(w.quality)).sort((w,$)=>(0,F.isHigher)(w.quality,$.quality)?-1:1),T=(0,no.default)(v,-1)?.quality,y=(0,no.default)(v,0)?.quality,M=(0,F.isNullable)(a)||(0,F.isNonNullable)(a.min)&&(0,F.isNonNullable)(a.max)&&(0,F.isLower)(a.max,a.min)||(0,F.isNonNullable)(a.min)&&y&&(0,F.isHigher)(a.min,y)||(0,F.isNonNullable)(a.max)&&T&&(0,F.isLower)(a.max,T),E=I*UI(n??.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),k={},j=v.filter(w=>(b?(0,F.isLower)(w.quality,b):!0)?((0,F.isNonNullable)(t)&&isFinite(t)&&(0,F.isNonNullable)(w.bitrate)?t-s>=w.bitrate*E:!0)?r.lazyQualitySwitch&&(0,F.isNonNullable)(r.minBufferToSwitchUp)&&l&&!(0,F.isInvariantQuality)(l.quality)&&(n??0)<r.minBufferToSwitchUp&&(0,F.isHigher)(w.quality,l.quality)?(k[w.quality]="Buffer",!1):!!c&&(0,F.isHigherOrEqual)(w.quality,c)?(k[w.quality]="DroppedFramesLimit",!1):M||((0,F.isNullable)(a.max)||(0,F.isLowerOrEqual)(w.quality,a.max))&&((0,F.isNullable)(a.min)||(0,F.isHigherOrEqual)(w.quality,a.min))?!0:(k[w.quality]="FitsQualityLimits",!1):(k[w.quality]="FitsThroughput",!1):(k[w.quality]="FitsContainer",!1))[0];j&&j.bitrate&&qI.next(j.bitrate);let N=j??v[Math.ceil((v.length-1)/2)]??i[0];N.quality!==u?.last?.quality&&d({message:`
|
|
7
7
|
[available tracks]
|
|
8
8
|
${i.map(w=>`{ id: ${w.id}, quality: ${w.quality}, bitrate: ${w.bitrate} }`).join(`
|
|
9
9
|
`)}
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
[selected track] ${N?.quality}
|
|
35
35
|
`});let Y=N&&u&&u.history[N.id]&&(0,F.now)()-u.history[N.id]<=r.trackCooldown&&(!u.last||N.id!==u.last.id);if(N?.id&&u&&!Y&&u.recordSelection(N),Y&&u?.last){let w=u.last;return u?.recordSwitch(w),d({message:`
|
|
36
36
|
[last selected] ${w?.quality}
|
|
37
|
-
`}),w}return u?.recordSwitch(N),N},xt=NI;var oe=i=>new URL(i).hostname;var B=require("@vkontakte/videoplayer-shared");var Ih=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"))},ye=async i=>{let e=i.muted;try{await i.play()}catch(t){if(!Ih(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{await i.play()}catch(r){return Ih(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 io(i){return ue()-i}function ao(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 Eh(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function pr(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,l=!1,u=0,c,d,f=!1,h="arraybuffer",b=7e3,I=2e3,g=()=>{if(l)return;(0,Xe.assertNonNullable)(c);let U=io(c),re;if(U<I){re=I-U,setTimeout(g,re);return}I*=2,I>b&&(I=b),n&&n.abort(),n=new a,z()},T=U=>(s=U,$),y=U=>(d=U,$),M=()=>(h="json",$),E=()=>{if(!l){if(--u>=0){g(),r&&r();return}l=!0,d&&d(),t&&t()}},k=U=>(f=U,$),z=()=>{c=ue(),n=new a,n.open("get",i);let U=0,re,le=0,Me=()=>((0,Xe.assertNonNullable)(c),Math.max(c,Math.max(re||0,le||0)));if(s&&n.addEventListener("progress",C=>{let W=ue();s.updateChunk&&C.loaded>U&&(s.updateChunk(Me(),C.loaded-U),U=C.loaded,re=W)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(l)return;(0,Xe.assertNonNullable)(n);let C=n.status;if(C>=200&&C<300){if(n.response.byteLength&&s){let W=n.response.byteLength-U;W&&s.updateChunk&&s.updateChunk(Me(),W)}n.responseType==="json"&&!Object.values(n.response).length?E():(d&&d(),e(n.response))}else E()}),n.addEventListener("error",()=>{E()}),f){let C=()=>{(0,Xe.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(le=ue(),n.removeEventListener("readystatechange",C))};n.addEventListener("readystatechange",C)}return n.responseType=h,n.send(),$},$={withBitrateReporting:T,withParallel:k,withJSONResponse:M,withRetryCount:U=>(u=U,$),withRetryInterval:(U,re)=>((0,Xe.isNonNullable)(U)&&(I=U),(0,Xe.isNonNullable)(re)&&(b=re),$),withTimeout:U=>(o=U,$),withFinally:y,send:z,abort:()=>{n&&(n.abort(),n=void 0),l=!0,d&&d()}};return $}var Wr=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 Qr=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=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=ue()-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=pr(t,s,()=>a("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=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 _a=1e4,so=3;var qI=6e4,UI=10,HI=1,jI=500,zr=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 Wr(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ao(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=ao(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=()=>{Eh(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 Qr(so,_a,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 E=s&&(!c||c===this.rep);return E||t("Not running!"),E},f=(E,k,z)=>{l&&l.abort(),l=pr(this.urlResolver.resolve(E,!1),k,z,()=>this._retryCallback()).withTimeout(_a).withBitrateReporting(this.bitrateSwitcher).withRetryCount(so).withFinally(()=>{l=null}).send()},h=(E,k,z)=>{(0,we.assertNonNullable)(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),k,z,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},b=E=>{let k=r.playbackRate;r.playbackRate!==E&&(t(`Playback rate switch: ${k}=>${E}`),r.playbackRate=E)},I=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)b(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){b(1);return}let z=ue()-1e4,j=0;for(let Y=0;Y<this.bufferStates.length;Y++){let w=this.bufferStates[Y];E=Math.min(E,w.buf),w.ts<z&&j++}this.bufferStates.splice(0,j),t(`update playback rate; minBuffer=${E} drop=${j} jitter=${this.sourceJitter}`);let N=E-HI;this.sourceJitter>=0?N-=this.sourceJitter/2:this.sourceJitter-=1,N>3?b(1.15):N>1?b(1.1):N>.3?b(1.05):b(1)}},T=E=>{let k,z=()=>k&&k.start?k.start.length:0,j=C=>k.start[C]/1e3,N=C=>k.dur[C]/1e3,Y=C=>k.fragIndex+C,w=(C,W)=>({chunkIdx:Y(C),startTS:j(C),dur:N(C),discontinuity:W}),$=()=>{let C=0;if(k&&k.dur){let W=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,ie=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,se=W;this.sourceJitter>1&&(se+=this.sourceJitter-1);let Te=k.dur.length-1;for(;Te>=0&&(se-=k.dur[Te],!(se<=0));--Te);C=Math.min(Te,k.dur.length-1-ie),C=Math.max(C,0)}return w(C,!0)},U=C=>{let W=z();if(!(W<=0)){if((0,we.isNonNullable)(C)){for(let ie=0;ie<W;ie++)if(j(ie)>C)return w(ie)}return $()}},re=C=>{let W=z(),ie=C?C.chunkIdx+1:0,se=ie-k.fragIndex;if(!(W<=0)){if(!C||se<0||se-W>UI)return t(`Resync: offset=${se} bChunks=${W} chunk=`+JSON.stringify(C)),$();if(!(se>=W))return w(ie-k.fragIndex,!1)}},le=(C,W,ie)=>{u&&u.abort(),u=pr(this.urlResolver.resolve(C,!0,this.lowLatency),W,ie,()=>this._retryCallback()).withTimeout(_a).withRetryCount(so).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(C,W)=>{le(E,ie=>{if(!d())return;k=ie;let se=!!k.lowLatency;se!==this.lowLatency&&I(se);let Te=0;for(let bt=0;bt<k.dur.length;++bt)Te+=k.dur[bt];Te>0&&((0,we.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Te/k.dur.length)),a({name:"index",zeroTime:k.zeroTime,shiftDuration:k.shiftDuration}),this.sourceJitter=k.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,k.jitter/1e3)):1,C(U(W))},()=>this._handleNetworkError())},nextChunk:re}},y=()=>{s=!1,o&&o.abort(),l&&l.abort(),u&&u.abort(),(0,we.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:E=>{let{videoElement:k,logger:z}=this.params,j=T(e.jidxUrl),N,Y,w,$,U=0,re,le,Me,C=()=>{re&&(clearTimeout(re),re=void 0);let K=Math.max(jI,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ie=U+K,Ee=ue(),Oe=Math.min(1e4,Ie-Ee);U=Ee;let tt=()=>{u||d()&&j.seek(()=>{d()&&(U=ue(),W(),C())})};Oe>0?re=window.setTimeout(()=>{this.paused?C():tt()},Oe):tt()},W=()=>{let K;for(;K=j.nextChunk($);)$=K,is(K);let Ie=j.nextChunk(w);if(Ie){if(w&&Ie.discontinuity){z("Detected discontinuity; restarting playback"),this.paused?C():(y(),this._initPlayerWith(e));return}bt(Ie)}else C()},ie=(K,Ie)=>{if(!d()||!this.sourceBuffer)return;let Ee,Oe,tt,Tr=xe=>{window.setTimeout(()=>{d()&&ie(K,Ie)},xe)};if(this.sourceBuffer.updating)z("Source buffer is updating; delaying appendBuffer"),Tr(100);else{let xe=ue(),gt=k.currentTime;!this.paused&&k.buffered.length>1&&le===gt&&xe-Me>500&&(z("Stall suspected; trying to fix"),this._fixupStall()),le!==gt&&(le=gt,Me=xe);let Be=this._getBufferSizeSec();if(Be>30)z(`Buffered ${Be} seconds; delaying appendBuffer`),Tr(2e3);else try{this.sourceBuffer.appendBuffer(K),this.videoPlayStarted?(this.bufferStates.push({ts:xe,buf:Be}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ie&&Ie()}catch(Ye){if(Ye.name==="QuotaExceededError")z("QuotaExceededError; delaying appendBuffer"),tt=this.sourceBuffer.buffered.length,tt!==0&&(Ee=this.sourceBuffer.buffered.start(0),Oe=gt,Oe-Ee>4&&this.sourceBuffer.remove(Ee,Oe-3)),Tr(1e3);else throw Ye}}},se=()=>{Y&&N&&(z([`Appending chunk, sz=${Y.byteLength}:`,JSON.stringify(w)]),ie(Y,function(){Y=null,W()}))},Te=K=>e.fragUrlTemplate.replace("%%id%%",K.chunkIdx),bt=K=>{d()&&h(Te(K),(Ie,Ee)=>{if(d()){if(Ee/=1e3,Y=Ie,w=K,n=K.startTS,Ee){let Oe=Math.min(10,K.dur/Ee);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Oe:Oe}se()}},()=>this._handleNetworkError())},is=K=>{d()&&((0,we.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Te(K),!1)))},Ni=K=>{d()&&(e.cachedHeader=K,ie(K,()=>{N=!0,se()}))};s=!0,j.seek(K=>{if(d()){if(U=ue(),!K){C();return}$=K,!(0,we.isNullable)(E)||K.startTS>E?bt(K):(w=K,W())}},E),e.cachedHeader?Ni(e.cachedHeader):f(e.headerUrl,Ni,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>n},c}_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=d=>{if(!this.autoQuality)return;let f,h,b;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),b=d/this.bitrate,h>10&&b>.8||h>15&&b>.5||h>20&&b>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}f=this._selectQuality(d),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${d}`)},s=(()=>({updateChunk:(f,h)=>{let b=ue();if(this.chunkRateEstimator.addInterval(f,b,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:b-f,speed:g}),!0}},get:()=>{let f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}}))(),n=-1/0,o,l=!0,u=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(l&&d>o&&io(n)<3e4)return;r(d)}l=this.autoQuality};return{updateChunk:(d,f)=>{let h=s.updateChunk(d,f);return h&&u(),h},notifySwitch:d=>{let f=ue();d<o&&(n=f),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=pr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(_a).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;ye(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))},qI))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var te=require("@vkontakte/videoplayer-shared"),no=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.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),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}},Na=no;var Fa=require("@vkontakte/videoplayer-shared"),xh=require("@vkontakte/videoplayer-shared");var Kr=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var GI=(i,e)=>new Fa.Observable(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(l=>t.next(l.isIntersecting||Kr()))},{...r,...e});a.observe(i);let s=(0,xh.fromEvent)(document,"visibilitychange").pipe((0,Fa.map)(n=>!document.hidden||Kr())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),$e=GI;var YI=["paused","playing","ready"],WI=["paused","playing","ready"],Jr=class{constructor(e){this.subscription=new B.Subscription;this.videoState=new H("stopped");this.representations$=new B.ValueSubject([]);this.textTracksManager=new Le;this.droppedFramesManager=new Na;this.maxSeekBackTime$=new B.ValueSubject(1/0);this.zeroTime$=new B.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:B.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,B.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,B.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(WI.includes(e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&YI.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,B.assertNever)(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:B.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:a})};(0,B.merge)(this.videoState.stateChangeStarted$.pipe((0,B.map)(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,B.map)(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=be(e.container),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=Se(this.video);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$:this.representations$.pipe((0,B.map)(a=>a.map(({track:s})=>s)))}),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,B.filterChanged)(),(0,B.map)(a=>-a/1e3)).subscribe(this.params.output.duration$)).add((0,B.combine)({zeroTime:this.zeroTime$.pipe((0,B.filter)(B.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(Re(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).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($e(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&(0,B.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,B.assertNever)(a.to)}},t)).add((0,B.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,B.observableFrom)(["init"])).pipe((0,B.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),ge(this.video)}createLiveDashPlayer(){let e=new zr({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,B.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,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,B.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,B.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 Ph=Jr;var Pt=(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 D=require("@vkontakte/videoplayer-shared");var qa=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let a=0,s=r.length;a<s;a++)if(r[a].callback===t){r.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let a=0,s=r.length;a<s;a++){let n=r[a];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},hr=class extends qa{constructor(){super(),this.listeners||qa.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)}},Xr=class{constructor(){Object.defineProperty(this,"signal",{value:new hr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document>"u")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch{r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(Xr.prototype[Symbol.toStringTag]="AbortController",hr.prototype[Symbol.toStringTag]="AbortSignal");function Ua(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 oo(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!Ua({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 f=new t(u,c);return d&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),f},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 f=new Promise((h,b)=>{c.addEventListener("abort",()=>b(d),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([f,n(l,u)])}return n(l,u)},Request:s}}var Zr=Ua({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),kh=Zr?oo({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,lt=Zr?kh.fetch:window.fetch,PR=Zr?kh.Request:window.Request,ct=Zr?Xr:window.AbortController,kR=Zr?hr:window.AbortSignal;var xf=_e(Ia(),1);var ei=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};var v=require("@vkontakte/videoplayer-shared");var vr=_e(Ba(),1);var QI=(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)},zI=i=>window.clearTimeout(i),wh=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",uo=wh?QI:window.requestIdleCallback,RR=wh?zI:window.cancelIdleCallback;var gf=_e(Ma(),1);var Ce=require("@vkontakte/videoplayer-shared"),KI=16,Ah=!1;try{Ah=(0,Ce.getCurrentBrowser)().browser===Ce.CurrentClientBrowser.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<=KI}catch(i){console.error(i)}var lo=class{constructor(e){this.bufferFull$=new Ce.Subject;this.error$=new Ce.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:Ce.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;Ah&&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:Ce.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,Ce.assertNever)(t)}}},Rh=lo;var co=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};var x=require("@vkontakte/videoplayer-shared");var Q=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 fr=class extends Q{};var ti=class extends Q{};var ri=class extends Q{constructor(t,r){super(t,r);this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let a=this.size-this.cursor;for(;a;){let s=this.readString(4);this.compatibleBrands.push(s),a-=4}}};var ii=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ai=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var si=class extends Q{constructor(t,r){super(t,r);this.data=this.content}};var ae=class extends Q{constructor(t,r){super(t,r);let a=this.readUint32();this.version=a>>>24,this.flags=a&16777215}};var Vt=class extends ae{constructor(t,r){super(t,r);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 a=0;a<this.referenceCount;a++){let s=this.readUint32(),n=s>>>31,o=s<<1>>>1,l=this.readUint32();s=this.readUint32();let u=s>>>28,c=s<<3>>>3;this.segments.push({referenceType:n,referencedSize:o,subsegmentDuration:l,SAPType:u,SAPDeltaTime:c})}}get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}};var ni=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var oi=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ui=class extends ae{constructor(t,r){super(t,r);switch(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 li=class extends ae{constructor(t,r){super(t,r);this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ci=class extends ae{constructor(t,r){super(t,r);this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var di=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var pi=class extends ae{constructor(t,r){super(t,r);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 hi=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var fi=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var mi=class extends ae{constructor(t,r){super(t,r);this.sequenceNumber=this.readUint32()}};var bi=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var gi=class extends ae{constructor(t,r){super(t,r);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 vi=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 Si=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 XI={ftyp:ri,moov:ii,moof:ai,mdat:si,sidx:Vt,trak:ni,mdia:di,mfhd:mi,tkhd:pi,traf:bi,tfhd:gi,tfdt:vi,trun:Si,minf:hi,sv3d:oi,st3d:ui,prhd:li,proj:fi,equi:ci,uuid:ti,unknown:fr},_t=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=XI[e];return r?new r(t,new i):new fr(t,new i)}};var mr=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 eE=new TextDecoder("ascii"),tE=i=>eE.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",rE=i=>{let e=new Vt(i,new _t),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})},iE=(i,e)=>{let r=new _t().parse(i),a=new mr(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)},aE=(i,e)=>{let r=new _t().parse(i),s=new mr(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,f)=>d+f,0):u=n.defaultSampleDuration*l.sampleCount,(Number(o.baseMediaDecodeTime)+u)/e*1e3},sE=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 _t().parse(i),a=new mr(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},Lh={validateData:tE,parseInit:sE,getIndexRange:()=>{},parseSegments:rE,parseFeedableSegmentChunk:iE,getSegmentEndTime:aE};var dt=require("@vkontakte/videoplayer-shared");var Ch=require("@vkontakte/videoplayer-shared");var $h={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"}},Dh=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=yi(i,t),a=r in $h,s=a?$h[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=yi(l),d=u*2**((o-1)*8)+c,f=t+o,h;return f+d>i.byteLength?h=new DataView(i.buffer,i.byteOffset+f):h=new DataView(i.buffer,i.byteOffset+f,d),{tag:a?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:f,tagSize:f+d,value:h,valueSize:d}},yi=(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 yi(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,Ch.assertNever)(e)}},Nt=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=Dh(r);if(!e(a))return;a.type==="master"&&Nt(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},Mh=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=Dh(i);return Nt(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 Oh=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],nE=[231,22612,22743,167,171,163,160,175],oE=i=>{let e,t,r,a,s=!1,n=!1,o=!1,l,u,c=!1,d=0;return Nt(i,({tag:f,type:h,value:b,valueSize:I})=>{if(f===21419){let g=je(b,h);u=yi(g)}else f!==21420&&(u=void 0);return f===408125543?(e=b.byteOffset,t=b.byteOffset+I):f===357149030?s=!0:f===290298740?n=!0:f===2807729?r=je(b,h):f===17545?a=je(b,h):f===21420&&u===475249515?l=je(b,h):f===374648427?Nt(b,({tag:g,type:T,value:y})=>g===30321?(c=je(y,T)===1,!1):!0):s&&n&&Oh.includes(f)&&(o=!0),!o}),(0,dt.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,dt.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,dt.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}}}},uE=i=>{if((0,dt.isNullable)(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},lE=(i,e)=>{let t=!1,r=!1,a=o=>(0,dt.isNonNullable)(o.time)&&(0,dt.isNonNullable)(o.position),s=[],n;return Nt(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&&Oh.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}}})},cE=i=>{let e=0,t=!1;try{Nt(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):nE.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},Bh={validateData:Mh,parseInit:oE,getIndexRange:uE,parseSegments:lE,parseFeedableSegmentChunk:cE};var go=_e(of(),1),gr=require("@vkontakte/videoplayer-shared");var uf=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var lf=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},Ft=(i,e)=>{let t=i;t=(0,go.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,go.default)(t,n,(o,l)=>(0,gr.isNullable)(s)?o:(0,gr.isNullable)(l)?s:s.padStart(parseInt(l,10),"0"))}return t},df=(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,f,h=s.getAttribute("mediaPresentationDuration"),b=n.getAttribute("duration"),g=s.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)f=lf(h);else if(b){let E=lf(b);(0,gr.isNonNullable)(E)&&(f=E)}else g&&(f=parseInt(g,10));let T=0,y=s.getAttribute("profiles")?.split(",")??[],M=y.includes("urn:webm:dash:profile:webm-on-demand:2012")||y.includes("urn:mpeg:dash:profile:webm-on-demand:2012")?"webm":"mp4";for(let E of l){let k=E.getAttribute("mimeType"),z=E.getAttribute("codecs"),j=E.getAttribute("contentType")??k?.split("/")[0],N=E.getAttribute("profiles")?.split(",")??[],Y=E.querySelectorAll("Representation"),w=E.querySelector("SegmentTemplate");if(j==="text"){for(let $ of Y){let U=$.getAttribute("id")||"",re=E.getAttribute("lang"),le=E.getAttribute("label"),Me=$.querySelector("BaseURL")?.textContent?.trim()??"",C=new URL(Me||o,e).toString(),W=U.includes("_auto");a.text.push({id:U,lang:re,label:le,isAuto:W,kind:"text",url:C})}continue}for(let $ of Y){let U=$.getAttribute("mimeType")??k,re=$.getAttribute("codecs")??z??"",le=$.getAttribute("contentType")??U?.split("/")[0]??j,Me=E.getAttribute("profiles")?.split(",")??[],C=parseInt($.getAttribute("width")??"",10),W=parseInt($.getAttribute("height")??"",10),ie=parseInt($.getAttribute("bandwidth")??"",10)/1e3,se=$.getAttribute("frameRate")??"",Te=$.getAttribute("quality")??void 0,bt=se?uf(se):void 0,is=$.getAttribute("id")??(T++).toString(10),Ni=le==="video"?`${W}p`:le==="audio"?`${ie}Kbps`:re,K=`${is}@${Ni}`,Ie=$.querySelector("BaseURL")?.textContent?.trim()??"",Ee=new URL(Ie||o,e).toString(),Oe=[...y,...N,...Me],tt,Tr=$.querySelector("SegmentBase"),xe=$.querySelector("SegmentTemplate")??w;if(Tr){let Be=$.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ye,as]=Be.split("-").map(zt=>parseInt(zt,10)),vt={from:Ye,to:as},Ir=$.querySelector("SegmentBase")?.getAttribute("indexRange"),[ss,Fi]=Ir?Ir.split("-").map(zt=>parseInt(zt,10)):[],Er=Ir?{from:ss,to:Fi}:void 0;tt={type:"byteRange",url:Ee,initRange:vt,indexRange:Er}}else if(xe){let Be={representationId:$.getAttribute("id")??void 0,bandwidth:$.getAttribute("bandwidth")??void 0},Ye=parseInt(xe.getAttribute("timescale")??"",10),as=xe.getAttribute("initialization")??"",vt=xe.getAttribute("media"),Ir=parseInt(xe.getAttribute("startNumber")??"",10)??1,ss=Ft(as,Be);if(!vt)throw new ReferenceError("No media attribute in SegmentTemplate");let Fi=xe.querySelectorAll("SegmentTimeline S")??[],Er=[],zt=0,ns="",os=0;if(Fi.length){let qi=Ir,Ve=0;for(let Kt of Fi){let We=parseInt(Kt.getAttribute("d")??"",10),At=parseInt(Kt.getAttribute("r")??"",10)||0,Ui=parseInt(Kt.getAttribute("t")??"",10);Ve=Number.isFinite(Ui)?Ui:Ve;let us=We/Ye*1e3,Zf=Ve/Ye*1e3;for(let Hi=0;Hi<At+1;Hi++){let em=Ft(vt,{...Be,segmentNumber:qi.toString(10),segmentTime:(Ve+Hi*We).toString(10)}),Ro=(Zf??0)+Hi*us,tm=Ro+us;qi++,Er.push({time:{from:Ro,to:tm},url:em})}Ve+=(At+1)*We,zt+=(At+1)*us}os=Ve/Ye*1e3,ns=Ft(vt,{...Be,segmentNumber:qi.toString(10),segmentTime:Ve.toString(10)})}else if((0,gr.isNonNullable)(f)){let Ve=parseInt(xe.getAttribute("duration")??"",10)/Ye*1e3,Kt=Math.ceil(f/Ve),We=0;for(let At=1;At<Kt;At++){let Ui=Ft(vt,{...Be,segmentNumber:At.toString(10),segmentTime:We.toString(10)});Er.push({time:{from:We,to:We+Ve},url:Ui}),We+=Ve}os=We,ns=Ft(vt,{...Be,segmentNumber:Kt.toString(10),segmentTime:We.toString(10)})}let Xf={time:{from:os,to:1/0},url:ns};tt={type:"template",baseUrl:Ee,segmentTemplateUrl:vt,initUrl:ss,totalSegmentsDurationMs:zt,segments:Er,nextSegmentBeyondManifest:Xf,timescale:Ye}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!le||!U)continue;let gt={video:"video",audio:"audio",text:"text"}[le];gt&&a[gt].push({id:K,kind:gt,segmentReference:tt,profiles:Oe,duration:f,bitrate:ie,mime:U,codecs:re,width:C,height:W,fps:bt,quality:Te})}}return{dynamic:u,liveAvailabilityStartTime:d,duration:f,container:M,representations:a}};var So=_e(Ba(),1);var pf=require("@vkontakte/videoplayer-shared"),hf=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s})=>{let n=(s?Et(s):void 0)??(0,pf.videoSizeToQuality)({width:e,height:t});return n&&{id:i,quality:n,bitrate:r,size:{width:e,height:t},fps:a}},ff=({id:i,bitrate:e})=>({id:i,bitrate:e}),mf=(i,e,t)=>{let r=e.indexOf(t);return(0,So.default)(i,Math.round(i.length*r/e.length))??(0,So.default)(i,-1)},bf=({id:i,lang:e,label:t,url:r,isAuto:a})=>({id:i,url:r,isAuto:a,type:"internal",language:e,label:t}),yo=i=>"url"in i,qt=i=>i.type==="template",Ti=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var Ii=class{constructor(e,t,r,a,{fetcher:s,tuning:n,getCurrentPosition:o,isActiveLowLatency:l,compatibilityMode:u=!1,manifest:c}){this.currentSegmentLength$=new x.ValueSubject(0);this.onLastSegment$=new x.ValueSubject(!1);this.fullyBuffered$=new x.ValueSubject(!1);this.playingRepresentation$=new x.ValueSubject(void 0);this.playingRepresentationInit$=new x.ValueSubject(void 0);this.error$=new x.Subject;this.gaps=[];this.subscription=new x.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ct;this.destroyAbortController=new ct;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,x.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,x.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 Rh(this.sourceBuffer),this.subscription.add((0,x.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>this.error$.next({id:"SegmentEjection",category:x.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:n}))),this.subscription.add((0,x.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:x.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{if(!this.sourceBuffer)return;let o=Math.min(this.bufferLimit,co(this.sourceBuffer.buffered)*.8);this.bufferLimit=o,this.pruneBuffer(this.getCurrentPosition(),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,x.assertNonNullable)(r,"No init buffer for starting representation"),(0,x.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,x.abortable)(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let t=this.representations.get(e);(0,x.assertNonNullable)(t,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,x.isNullable)(a)||(0,x.isNullable)(r)?yield this.loadInit(t,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,x.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal);let s=this.getCurrentPosition();(0,x.isNonNullable)(s)&&(this.isLive||(r.forEach(n=>n.status="none"),this.pruneBuffer(s,1/0,!0)),this.maintain(s))}.bind(this));this.seekLive=(0,x.abortable)(this.destroyAbortController.signal,async function*(e){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(let o of this.representations.keys()){let l=e.find(d=>d.id===o);l&&this.representations.set(o,l);let u=this.representations.get(o);if(!u||!qt(u.segmentReference))return;let c=this.getActualLiveStartingSegments(u.segmentReference);this.segments.set(u.id,c)}let t=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(t);(0,x.assertNonNullable)(r);let a=this.segments.get(t);(0,x.assertNonNullable)(a,"No segments for starting representation");let s=this.initData.get(t);if((0,x.assertNonNullable)(s,"No init buffer for starting representation"),!(s instanceof ArrayBuffer))return;let n=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),n&&(yield this.sourceBufferTaskQueue.remove(n.from*1e3,n.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(s,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));switch(this.fetcher=s,this.tuning=n,this.compatibilityMode=u,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isActiveLowLatency=l,this.isLive=!!c?.dynamic,this.container=r,r){case"mp4":this.containerParser=Lh;break;case"webm":this.containerParser=Bh;break;default:(0,x.assertNever)(r)}this.initData=new Map(a.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(a.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 ct,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,x.isNullable)(e)||(0,x.isNullable)(this.downloadingRepresentationId)||(0,x.isNullable)(this.playingRepresentationId)||(0,x.isNullable)(this.sourceBuffer)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if((0,x.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=Pt(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)&&co(this.sourceBuffer.buffered)>=this.bufferLimit){let u=Pt(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,vr.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&&Pt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,vr.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,x.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?.representations[this.kind].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){for(let t of e?.representations[this.kind].values()??[]){if(!t||!qt(t.segmentReference))return;let r=t.segmentReference.segments.map(o=>({...o,status:"none",size:void 0})),a=this.segments.get(t.id)??[],s=(0,vr.default)(a,-1)?.time.to??0,n=r?.findIndex(o=>Math.floor(s)>=Math.floor(o.time.from)&&Math.floor(s)<=Math.floor(o.time.to));if(n===-1){this.liveUpdateSegmentIndex=0;let o=this.getActualLiveStartingSegments(t.segmentReference);this.segments.set(t.id,o)}else{let o=r.slice(n+1);this.segments.set(t.id,[...a,...o])}}}updateLowLatencyLive(e){if(this.isActiveLowLatency())for(let t of this.representations.values()){let r=t.segmentReference;if(!qt(r))return;let a=Math.round(e.segment.time.to*r.timescale/1e3).toString(10),s=Ft(r.segmentTemplateUrl,{segmentTime:a}),n=this.segments.get(t.id)??[],o=n.find(u=>Math.floor(u.time.from)===Math.floor(e.segment.time.from));o&&(o.time.to=e.segment.time.to),!!n.find(u=>Math.floor(u.time.from)===Math.floor(e.segment.time.to))||n.push({status:"none",time:{from:e.segment.time.to,to:1/0},url:s})}}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:f,to:h}},b)=>{let I=f<=r&&h>=r,g=f>r||I||b===0&&r===0,T=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&f<=r+T||h<=r+T;return(d==="none"||d==="partially_ejected"&&g&&y&&this.sourceBuffer&&!ei(this.sourceBuffer.buffered,r))&&g&&y});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 f=s[d];if(n+=f.byte.to+1-f.byte.from,o+=f.time.to+1-f.time.from,f.status==="none"||f.status==="partially_ejected")l.push(f);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,x.abortable)(o,async function*(){let c=(0,x.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(this.isActiveLowLatency()){let f=t.segmentReference.timescale;a.segment.time.to=this.containerParser.getSegmentEndTime(d,f)}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]),Ti(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,x.abortable)(n,async function*(){let l=(0,x.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(u,l),(0,x.fromEvent)(window,"online").pipe((0,x.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),Ti(l)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(qt(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,vr.default)(e,0).byte.from,to:(0,vr.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:x.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}}}}prepareTemplateFetchSegmentParams(e,t){if(!qt(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:x.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||!this.representations.get(t)))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=this.containerParser.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}){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,f=l==="byteRange",h=f?d.byte.to-d.byte.from+1:u;if(c.representationId!==t||!(!f||d.byte.from>=r&&d.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let I=f?d.byte.from-r:0,g=f?d.byte.to-r:e.byteLength,T=I<a,y=g<=a;if(d.status==="downloading"&&T&&y){d.status="downloaded";let M=new DataView(e.buffer,e.byteOffset+I,h);this.sourceBufferTaskQueue.append(M,s).then(E=>E&&!s.aborted?this.onSegmentFullyAppended(c,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&T&&(c.loadedBytes=Math.min(h,a-I),c.loadedBytes>c.feedingBytes)){let M=new DataView(e.buffer,e.byteOffset+I+c.feedingBytes,c.loadedBytes-c.feedingBytes),E=c.loadedBytes===h?M:this.containerParser.parseFeedableSegmentChunk(M);E?.byteLength&&(d.status="partially_fed",c.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,s).then(k=>{if(s.aborted)n();else if(k)c.fedBytes+=E.byteLength,c.fedBytes===h&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<h)return;n()}}))}}}onSegmentFullyAppended(e,t){this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",yo(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.isActiveLowLatency()&&this.updateLowLatencyLive(e),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=uo(()=>(0,gf.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,x.abortable)(this.destroyAbortController.signal,async function*(){let o=(0,x.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,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 f=c;this.isLive&&qt(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),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:x.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||(0,x.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=yo(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 f of this.segments.values())for(let h of f)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(d)){s=c,n=d;break}}if(o=isFinite(s)&&isFinite(n),!o&&r){a=0,s=1/0,n=-1/0;let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let d of c)d.time.from>e+u&&d.status==="fed"&&l(d)}return o=isFinite(s)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(s,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let a={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){a=void 0;break}o>r.time.from&&o<r.time.to&&(a.from=o),n<r.time.to&&n>r.time.from&&(a.to=n)}}a&&a.to-a.from>1&&!this.gaps.some(s=>a&&s.from===a.from&&s.to===a.to)&&this.gaps.push(a)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=uo(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:x.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if((0,x.isNullable)(this.sourceBuffer)||(0,x.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 Ei=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var vf=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 Ha=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 ct;this.subscription=new X.Subscription;this.fetchManifest=(0,X.abortable)(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=Ei(t));let r=yield lt(t,{signal:this.abortAllController.signal}).catch(xi);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 N=new URL(u,location.href);N.searchParams.append("bytes",`${r.from}-${r.to}`),u=N.toString();break}default:(0,X.assertNever)(t)}this.requestQuic&&(u=Ei(u));let d=this.abortAllController.signal,f;if(n){let N=new ct;if(f=(0,X.merge)((0,X.fromEvent)(this.abortAllController.signal,"abort"),(0,X.fromEvent)(n,"abort")).subscribe(()=>{try{N.abort()}catch(Y){xi(Y)}}),this.abortAllController.signal.aborted||n.aborted)try{N.abort()}catch(Y){xi(Y)}d=N.signal}let h=(0,X.now)(),b=yield lt(u,{priority:s,headers:c,signal:d}).catch(xi),I=(0,X.now)();if(!b)return f?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(I-h),!b.ok||!b.body)return f?.unsubscribe(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`));if(this.onHeadersReceived(b.headers),!a&&!o)return f?.unsubscribe(),b.arrayBuffer();let[g,T]=b.body.tee(),y=g.getReader();o&&this.throughputEstimator?.trackStream(T,l);let M=0,E=new Uint8Array(0),k=!1,z=N=>{f?.unsubscribe(),k=!0,xi(N)},j=(0,X.abortable)(d,async function*({done:N,value:Y}){if(M===0&&this.lastRequestFirstBytes$.next((0,X.now)()-h),d.aborted){f?.unsubscribe();return}if(!N&&Y){let w=new Uint8Array(E.length+Y.length);w.set(E),w.set(Y,E.length),E=w,M+=Y.byteLength,a?.(new DataView(E.buffer),M),yield y?.read().then(j,z)}}.bind(this));return yield y?.read().then(j,z),f?.unsubscribe(),k?null:E.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 f=new DataView(d,a-n,s-n+1);if(!t.validateData(f))throw new Error("Invalid media file");let h=t.parseInit(f),b=e.indexRange??t.getIndexRange(h);if(!b)throw new ReferenceError("No way to load representation index");let I;if(l)I=new DataView(d,b.from-n,b.to-b.from+1);else{let T=yield this.fetch(e.url,{range:b,priority:r,measureThroughput:!1});if(!T)return null;I=new DataView(T)}let g=t.parseSegments(I,h,b);return{init:h,dataView:new DataView(d),segments:g}}.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}=vf(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()}},xi=i=>{if(!Ti(i))throw i};var Ut=(i,e,t)=>t*e+(1-t)*i,To=(i,e)=>i.reduce((t,r)=>t+r,0)/e,Sf=(i,e,t,r)=>{let a=0,s=t,n=To(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 Pi=require("@vkontakte/videoplayer-shared"),kt=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 Pi.ValueSubject(e.initial),this.debounced$=new Pi.ValueSubject(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new pe(`raw_${t}`),this.smoothedSeries$=new pe(`smoothed_${t}`),this.reportedSeries$=new pe(`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,Pi.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 ja=class extends kt{constructor(t){super(t);this.slow=this.fast=t.initial}updateSmoothedValue(t){this.slow=Ut(this.slow,t,this.params.emaAlphaSlow),this.fast=Ut(this.fast,t,this.params.emaAlphaFast);let r=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=r(this.slow,this.fast)}};var Ga=class extends kt{constructor(t){super(t);this.emaSmoothed=t.initial}updateSmoothedValue(t){let r=To(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ut(this.emaSmoothed,t,this.params.emaAlpha);let a=Sf(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=a?this.emaSmoothed:r}};var Ya=class extends kt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?Ut(this.smoothed,t,this.params.emaAlpha):t}};var Ht=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new ja({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new Ga({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 Ya({initial:e,label:"liveEdgeDelay",...t})}};var yf=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};var pt=()=>window.ManagedMediaSource||window.MediaSource,Wa=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Tf=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),If=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var Ef=["timeupdate","progress","play","seeked","stalled","waiting"];var Qa=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new v.Subscription;this.representationSubscription=new v.Subscription;this.state$=new H("none");this.currentVideoRepresentation$=new v.ValueSubject(void 0);this.currentVideoRepresentationInit$=new v.ValueSubject(void 0);this.currentVideoSegmentLength$=new v.ValueSubject(0);this.currentAudioSegmentLength$=new v.ValueSubject(0);this.error$=new v.Subject;this.lastConnectionType$=new v.ValueSubject(void 0);this.lastConnectionReused$=new v.ValueSubject(void 0);this.lastRequestFirstBytes$=new v.ValueSubject(void 0);this.isLive$=new v.ValueSubject(!1);this.liveDuration$=new v.ValueSubject(0);this.liveAvailabilityStartTime$=new v.ValueSubject(void 0);this.bufferLength$=new v.ValueSubject(0);this.liveLoadBufferLength$=new v.ValueSubject(0);this.livePositionFromPlayer$=new v.ValueSubject(0);this.timeInWaiting=0;this.isActiveLowLatency=!1;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new v.Subject;this.gapWatchdogActive=!1;this.destroyController=new ct;this.initManifest=(0,v.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?.representations.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:v.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,v.abortable)(this.destroyController.signal,async function*(){let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(a=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:v.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:a})});if(!e)return null;let t;try{t=df(e??"",this.manifestUrlString)}catch(a){this.error$.next({id:"ManifestParsing",category:v.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:a})}if(!t)return null;let r=({kind:a,mime:s,codecs:n})=>!!(this.element?.canPlayType?.(s)&&pt()?.isTypeSupported?.(`${s}; codecs="${n}"`)||a==="text");return 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)),{...t,representations:(0,xf.default)(Object.entries(t.representations).map(([a,s])=>[a,s.filter(r)]))}}.bind(this));this.initRepresentations=(0,v.abortable)(this.destroyController.signal,async function*(e,t,r){(0,v.assertNonNullable)(this.manifest),(0,v.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=h=>{this.representationSubscription.add((0,v.fromEvent)(h,"error").pipe((0,v.filter)(b=>!!this.element?.played.length)).subscribe(b=>{this.error$.next({id:"VideoSource",category:v.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:b})}))};this.source=this.tuning.useManagedMediaSource?If():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Wa())if(r){let h=document.createElement("source");a(h),h.type="application/x-mpegurl",h.src=r.url,this.element.appendChild(h)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency=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,manifest:this.manifest};if(this.videoBufferManager=new Ii("video",this.source,this.manifest.container,this.manifest.representations.video,n),this.bufferManagers=[this.videoBufferManager],(0,v.isNonNullable)(t)&&(this.audioBufferManager=new Ii("audio",this.source,this.manifest.container,this.manifest.representations.audio,n),this.bufferManagers.push(this.audioBufferManager)),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,v.interval)(1e3).subscribe(h=>{if(this.element?.paused){let b=Kn(this.manifestUrlString,2);this.manifestUrlString=de(this.manifestUrlString,b+1e3,2)}})),this.representationSubscription.add((0,v.merge)(...Ef.filter(h=>h!=="waiting").map(h=>(0,v.fromEvent)(this.element,h))).pipe((0,v.map)(h=>this.element?Pt(this.element.buffered,this.element.currentTime*1e3):0),(0,v.filterChanged)(),(0,v.filter)(h=>!!h),(0,v.tap)(h=>{this.stallWatchdogSubscription?.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe((0,v.filter)(b=>this.isActiveLowLatency&&!!b)).subscribe(b=>this.liveEstimatedDelay.next(b))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(b=>{if(!this.isActiveLowLatency)return;let I=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=b-I,M=1+Math.sign(y)*T;Math.abs(y)<g?M=1:Math.abs(y)>g*2&&(M=1+Math.sign(y)*T*2),yf(this.element,M)})),this.representationSubscription.add(this.bufferLength$.subscribe(b=>{let I=0;if(b){let g=(this.element?.currentTime??0)*1e3;I=Math.min(...this.bufferManagers.map(y=>y.getLiveSegmentsToLoadState(this.manifest)?.to??g))-g}this.liveLoadBufferLength$.getValue()!==I&&this.liveLoadBufferLength$.next(I)}));let h=0;this.representationSubscription.add((0,v.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,v.throttle)(1e3)).subscribe(async({liveLoadBufferLength:b,bufferLength:I})=>{if((0,v.assertNonNullable)(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,T=Kn(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,M=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),E=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,k=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,z=this.isActiveLowLatency?I:b,j=3;if(this.isActiveLowLatency?j=0:z<M+k&&z>=M?j=1:T!==0&&z<M&&(j=2),isFinite(b)&&(h=b>h?b:h),j===2||j===1){let N=h-(M+E),Y=this.normolizeLiveOffset(Math.trunc(T+N/g)),w=Math.abs(Y-T),$;!b||w<=this.tuning.dashCmafLive.offsetCalculationError?$=T:Y>0&&w>this.tuning.dashCmafLive.offsetCalculationError?$=Y:$=0,this.manifestUrlString=de(this.manifestUrlString,$,2)}j!==3&&j!==0&&(h=0,this.updateLive())}))}let o=(0,v.merge)(...this.bufferManagers.map(h=>h.fullyBuffered$)).pipe((0,v.map)(()=>this.bufferManagers.every(h=>h.fullyBuffered$.getValue()))),l=(0,v.merge)(...this.bufferManagers.map(h=>h.onLastSegment$)).pipe((0,v.map)(()=>this.bufferManagers.some(h=>h.onLastSegment$.getValue())));this.representationSubscription.add((0,v.merge)(this.forceEnded$,(0,v.combine)({allBuffersFull:o,someBufferEnded:l}).pipe((0,v.filter)(({allBuffersFull:h,someBufferEnded:b})=>h&&b))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{this.source?.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:v.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add((0,v.merge)(...this.bufferManagers.map(h=>h.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.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$)),this.source.readyState!=="open"&&(yield new Promise(h=>this.source?.addEventListener("sourceopen",h)));let u=this.manifest.duration??0,c=(h,b)=>Math.max(h,b.duration??0),d=this.manifest.representations.audio.reduce(c,u),f=this.manifest.representations.video.reduce(c,u);(d||f)&&(this.source.duration=Math.max(d,f)/1e3),this.audioBufferManager&&(0,v.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.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,v.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:v.ErrorCategory.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Ha({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Ht.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){(0,v.assertNonNullable)(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency=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?.representations.video),await this.audioBufferManager?.seekLive(this.manifest?.representations.audio))}initBuffer(){(0,v.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,v.merge)(...Ef.map(e=>(0,v.fromEvent)(this.element,e)),(0,v.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:v.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,v.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,v.fromEvent)(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&ei(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(this.element){if(this.timeInWaiting+=1e3,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);this.isLive$.getValue()&&this.seekLive(this.liveLastSeekOffset)}};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=(0,v.interval)(1e3).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:v.ErrorCategory.FATAL,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t)}seek(e,t){(0,v.assertNonNullable)(this.element),(0,v.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),ei(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)}getRepresentations(){return this.manifest?.representations}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency&&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 za=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ka=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 Pf=`attribute vec2 a_vertex;
|
|
37
|
+
`}),w}return u?.recordSwitch(N),N},xt=jI;var oe=i=>new URL(i).hostname;var B=require("@vkontakte/videoplayer-shared");var wh=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"))},ye=async i=>{let e=i.muted;try{await i.play()}catch(t){if(!wh(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{await i.play()}catch(r){return wh(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 oo(i){return ue()-i}function uo(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 Ah(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function pr(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,l=!1,u=0,c,d,f=!1,h="arraybuffer",b=7e3,I=2e3,v=()=>{if(l)return;(0,Xe.assertNonNullable)(c);let U=oo(c),re;if(U<I){re=I-U,setTimeout(v,re);return}I*=2,I>b&&(I=b),n&&n.abort(),n=new a,z()},T=U=>(s=U,$),y=U=>(d=U,$),M=()=>(h="json",$),E=()=>{if(!l){if(--u>=0){v(),r&&r();return}l=!0,d&&d(),t&&t()}},k=U=>(f=U,$),z=()=>{c=ue(),n=new a,n.open("get",i);let U=0,re,le=0,Me=()=>((0,Xe.assertNonNullable)(c),Math.max(c,Math.max(re||0,le||0)));if(s&&n.addEventListener("progress",C=>{let W=ue();s.updateChunk&&C.loaded>U&&(s.updateChunk(Me(),C.loaded-U),U=C.loaded,re=W)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(l)return;(0,Xe.assertNonNullable)(n);let C=n.status;if(C>=200&&C<300){if(n.response.byteLength&&s){let W=n.response.byteLength-U;W&&s.updateChunk&&s.updateChunk(Me(),W)}n.responseType==="json"&&!Object.values(n.response).length?E():(d&&d(),e(n.response))}else E()}),n.addEventListener("error",()=>{E()}),f){let C=()=>{(0,Xe.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(le=ue(),n.removeEventListener("readystatechange",C))};n.addEventListener("readystatechange",C)}return n.responseType=h,n.send(),$},$={withBitrateReporting:T,withParallel:k,withJSONResponse:M,withRetryCount:U=>(u=U,$),withRetryInterval:(U,re)=>((0,Xe.isNonNullable)(U)&&(I=U),(0,Xe.isNonNullable)(re)&&(b=re),$),withTimeout:U=>(o=U,$),withFinally:y,send:z,abort:()=>{n&&(n.abort(),n=void 0),l=!0,d&&d()}};return $}var Qr=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 zr=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=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=ue()-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=pr(t,s,()=>a("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=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 Fa=1e4,lo=3;var YI=6e4,WI=10,QI=1,zI=500,Kr=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 Qr(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=uo(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=uo(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=()=>{Ah(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 zr(lo,Fa,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 E=s&&(!c||c===this.rep);return E||t("Not running!"),E},f=(E,k,z)=>{l&&l.abort(),l=pr(this.urlResolver.resolve(E,!1),k,z,()=>this._retryCallback()).withTimeout(Fa).withBitrateReporting(this.bitrateSwitcher).withRetryCount(lo).withFinally(()=>{l=null}).send()},h=(E,k,z)=>{(0,we.assertNonNullable)(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),k,z,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},b=E=>{let k=r.playbackRate;r.playbackRate!==E&&(t(`Playback rate switch: ${k}=>${E}`),r.playbackRate=E)},I=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)b(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){b(1);return}let z=ue()-1e4,j=0;for(let Y=0;Y<this.bufferStates.length;Y++){let w=this.bufferStates[Y];E=Math.min(E,w.buf),w.ts<z&&j++}this.bufferStates.splice(0,j),t(`update playback rate; minBuffer=${E} drop=${j} jitter=${this.sourceJitter}`);let N=E-QI;this.sourceJitter>=0?N-=this.sourceJitter/2:this.sourceJitter-=1,N>3?b(1.15):N>1?b(1.1):N>.3?b(1.05):b(1)}},T=E=>{let k,z=()=>k&&k.start?k.start.length:0,j=C=>k.start[C]/1e3,N=C=>k.dur[C]/1e3,Y=C=>k.fragIndex+C,w=(C,W)=>({chunkIdx:Y(C),startTS:j(C),dur:N(C),discontinuity:W}),$=()=>{let C=0;if(k&&k.dur){let W=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,ie=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,se=W;this.sourceJitter>1&&(se+=this.sourceJitter-1);let Te=k.dur.length-1;for(;Te>=0&&(se-=k.dur[Te],!(se<=0));--Te);C=Math.min(Te,k.dur.length-1-ie),C=Math.max(C,0)}return w(C,!0)},U=C=>{let W=z();if(!(W<=0)){if((0,we.isNonNullable)(C)){for(let ie=0;ie<W;ie++)if(j(ie)>C)return w(ie)}return $()}},re=C=>{let W=z(),ie=C?C.chunkIdx+1:0,se=ie-k.fragIndex;if(!(W<=0)){if(!C||se<0||se-W>WI)return t(`Resync: offset=${se} bChunks=${W} chunk=`+JSON.stringify(C)),$();if(!(se>=W))return w(ie-k.fragIndex,!1)}},le=(C,W,ie)=>{u&&u.abort(),u=pr(this.urlResolver.resolve(C,!0,this.lowLatency),W,ie,()=>this._retryCallback()).withTimeout(Fa).withRetryCount(lo).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(C,W)=>{le(E,ie=>{if(!d())return;k=ie;let se=!!k.lowLatency;se!==this.lowLatency&&I(se);let Te=0;for(let bt=0;bt<k.dur.length;++bt)Te+=k.dur[bt];Te>0&&((0,we.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Te/k.dur.length)),a({name:"index",zeroTime:k.zeroTime,shiftDuration:k.shiftDuration}),this.sourceJitter=k.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,k.jitter/1e3)):1,C(U(W))},()=>this._handleNetworkError())},nextChunk:re}},y=()=>{s=!1,o&&o.abort(),l&&l.abort(),u&&u.abort(),(0,we.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:E=>{let{videoElement:k,logger:z}=this.params,j=T(e.jidxUrl),N,Y,w,$,U=0,re,le,Me,C=()=>{re&&(clearTimeout(re),re=void 0);let K=Math.max(zI,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ie=U+K,Ee=ue(),Oe=Math.min(1e4,Ie-Ee);U=Ee;let tt=()=>{u||d()&&j.seek(()=>{d()&&(U=ue(),W(),C())})};Oe>0?re=window.setTimeout(()=>{this.paused?C():tt()},Oe):tt()},W=()=>{let K;for(;K=j.nextChunk($);)$=K,os(K);let Ie=j.nextChunk(w);if(Ie){if(w&&Ie.discontinuity){z("Detected discontinuity; restarting playback"),this.paused?C():(y(),this._initPlayerWith(e));return}bt(Ie)}else C()},ie=(K,Ie)=>{if(!d()||!this.sourceBuffer)return;let Ee,Oe,tt,Ir=xe=>{window.setTimeout(()=>{d()&&ie(K,Ie)},xe)};if(this.sourceBuffer.updating)z("Source buffer is updating; delaying appendBuffer"),Ir(100);else{let xe=ue(),vt=k.currentTime;!this.paused&&k.buffered.length>1&&le===vt&&xe-Me>500&&(z("Stall suspected; trying to fix"),this._fixupStall()),le!==vt&&(le=vt,Me=xe);let Be=this._getBufferSizeSec();if(Be>30)z(`Buffered ${Be} seconds; delaying appendBuffer`),Ir(2e3);else try{this.sourceBuffer.appendBuffer(K),this.videoPlayStarted?(this.bufferStates.push({ts:xe,buf:Be}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ie&&Ie()}catch(Ye){if(Ye.name==="QuotaExceededError")z("QuotaExceededError; delaying appendBuffer"),tt=this.sourceBuffer.buffered.length,tt!==0&&(Ee=this.sourceBuffer.buffered.start(0),Oe=vt,Oe-Ee>4&&this.sourceBuffer.remove(Ee,Oe-3)),Ir(1e3);else throw Ye}}},se=()=>{Y&&N&&(z([`Appending chunk, sz=${Y.byteLength}:`,JSON.stringify(w)]),ie(Y,function(){Y=null,W()}))},Te=K=>e.fragUrlTemplate.replace("%%id%%",K.chunkIdx),bt=K=>{d()&&h(Te(K),(Ie,Ee)=>{if(d()){if(Ee/=1e3,Y=Ie,w=K,n=K.startTS,Ee){let Oe=Math.min(10,K.dur/Ee);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Oe:Oe}se()}},()=>this._handleNetworkError())},os=K=>{d()&&((0,we.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Te(K),!1)))},qi=K=>{d()&&(e.cachedHeader=K,ie(K,()=>{N=!0,se()}))};s=!0,j.seek(K=>{if(d()){if(U=ue(),!K){C();return}$=K,!(0,we.isNullable)(E)||K.startTS>E?bt(K):(w=K,W())}},E),e.cachedHeader?qi(e.cachedHeader):f(e.headerUrl,qi,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>n},c}_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=d=>{if(!this.autoQuality)return;let f,h,b;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),b=d/this.bitrate,h>10&&b>.8||h>15&&b>.5||h>20&&b>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}f=this._selectQuality(d),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${d}`)},s=(()=>({updateChunk:(f,h)=>{let b=ue();if(this.chunkRateEstimator.addInterval(f,b,h)){let v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:b-f,speed:v}),!0}},get:()=>{let f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}}))(),n=-1/0,o,l=!0,u=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(l&&d>o&&oo(n)<3e4)return;r(d)}l=this.autoQuality};return{updateChunk:(d,f)=>{let h=s.updateChunk(d,f);return h&&u(),h},notifySwitch:d=>{let f=ue();d<o&&(n=f),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=pr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Fa).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;ye(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))},YI))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var te=require("@vkontakte/videoplayer-shared"),co=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.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),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}},qa=co;var Ua=require("@vkontakte/videoplayer-shared"),Rh=require("@vkontakte/videoplayer-shared");var Jr=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var KI=(i,e)=>new Ua.Observable(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(l=>t.next(l.isIntersecting||Jr()))},{...r,...e});a.observe(i);let s=(0,Rh.fromEvent)(document,"visibilitychange").pipe((0,Ua.map)(n=>!document.hidden||Jr())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),$e=KI;var JI=["paused","playing","ready"],XI=["paused","playing","ready"],Xr=class{constructor(e){this.subscription=new B.Subscription;this.videoState=new H("stopped");this.representations$=new B.ValueSubject([]);this.textTracksManager=new Le;this.droppedFramesManager=new qa;this.maxSeekBackTime$=new B.ValueSubject(1/0);this.zeroTime$=new B.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:B.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,B.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,B.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(XI.includes(e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&JI.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,B.assertNever)(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:B.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:a})};(0,B.merge)(this.videoState.stateChangeStarted$.pipe((0,B.map)(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,B.map)(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=be(e.container),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=Se(this.video);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$:this.representations$.pipe((0,B.map)(a=>a.map(({track:s})=>s)))}),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,B.filterChanged)(),(0,B.map)(a=>-a/1e3)).subscribe(this.params.output.duration$)).add((0,B.combine)({zeroTime:this.zeroTime$.pipe((0,B.filter)(B.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(ge(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Re(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).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($e(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&(0,B.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,B.assertNever)(a.to)}},t)).add((0,B.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,B.observableFrom)(["init"])).pipe((0,B.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 Kr({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,B.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,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,B.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,B.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 Lh=Xr;var Pt=(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 D=require("@vkontakte/videoplayer-shared");var Ha=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let a=0,s=r.length;a<s;a++)if(r[a].callback===t){r.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let a=0,s=r.length;a<s;a++){let n=r[a];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},hr=class extends Ha{constructor(){super(),this.listeners||Ha.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)}},Zr=class{constructor(){Object.defineProperty(this,"signal",{value:new hr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document>"u")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch{r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(Zr.prototype[Symbol.toStringTag]="AbortController",hr.prototype[Symbol.toStringTag]="AbortSignal");function ja(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(!ja({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 f=new t(u,c);return d&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),f},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 f=new Promise((h,b)=>{c.addEventListener("abort",()=>b(d),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([f,n(l,u)])}return n(l,u)},Request:s}}var ei=ja({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),$h=ei?po({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,lt=ei?$h.fetch:window.fetch,LR=ei?$h.Request:window.Request,ct=ei?Zr:window.AbortController,$R=ei?hr:window.AbortSignal;var Rf=_e(xa(),1);var ti=(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 g=require("@vkontakte/videoplayer-shared");var gr=_e(_a(),1);var ZI=(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)},eE=i=>window.clearTimeout(i),Ch=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",ho=Ch?ZI:window.requestIdleCallback,MR=Ch?eE:window.cancelIdleCallback;var If=_e(Ba(),1);var Ce=require("@vkontakte/videoplayer-shared"),tE=16,Dh=!1;try{Dh=(0,Ce.getCurrentBrowser)().browser===Ce.CurrentClientBrowser.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<=tE}catch(i){console.error(i)}var fo=class{constructor(e){this.bufferFull$=new Ce.Subject;this.error$=new Ce.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:Ce.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;Dh&&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:Ce.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,Ce.assertNever)(t)}}},Mh=fo;var mo=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};var x=require("@vkontakte/videoplayer-shared");var Q=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 fr=class extends Q{};var ri=class extends Q{};var ii=class extends Q{constructor(t,r){super(t,r);this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let a=this.size-this.cursor;for(;a;){let s=this.readString(4);this.compatibleBrands.push(s),a-=4}}};var ai=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var si=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ni=class extends Q{constructor(t,r){super(t,r);this.data=this.content}};var ae=class extends Q{constructor(t,r){super(t,r);let a=this.readUint32();this.version=a>>>24,this.flags=a&16777215}};var Vt=class extends ae{constructor(t,r){super(t,r);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 a=0;a<this.referenceCount;a++){let s=this.readUint32(),n=s>>>31,o=s<<1>>>1,l=this.readUint32();s=this.readUint32();let u=s>>>28,c=s<<3>>>3;this.segments.push({referenceType:n,referencedSize:o,subsegmentDuration:l,SAPType:u,SAPDeltaTime:c})}}get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}};var oi=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ui=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var li=class extends ae{constructor(t,r){super(t,r);switch(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 ci=class extends ae{constructor(t,r){super(t,r);this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var di=class extends ae{constructor(t,r){super(t,r);this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var pi=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var hi=class extends ae{constructor(t,r){super(t,r);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 fi=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var mi=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var bi=class extends ae{constructor(t,r){super(t,r);this.sequenceNumber=this.readUint32()}};var vi=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var gi=class extends ae{constructor(t,r){super(t,r);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 Si=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 yi=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 iE={ftyp:ii,moov:ai,moof:si,mdat:ni,sidx:Vt,trak:oi,mdia:pi,mfhd:bi,tkhd:hi,traf:vi,tfhd:gi,tfdt:Si,trun:yi,minf:fi,sv3d:ui,st3d:li,prhd:ci,proj:mi,equi:di,uuid:ri,unknown:fr},_t=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=iE[e];return r?new r(t,new i):new fr(t,new i)}};var mr=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 sE=new TextDecoder("ascii"),nE=i=>sE.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",oE=i=>{let e=new Vt(i,new _t),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})},uE=(i,e)=>{let r=new _t().parse(i),a=new mr(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)},lE=(i,e)=>{let r=new _t().parse(i),s=new mr(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,f)=>d+f,0):u=n.defaultSampleDuration*l.sampleCount,(Number(o.baseMediaDecodeTime)+u)/e*1e3},cE=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 _t().parse(i),a=new mr(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},Oh={validateData:nE,parseInit:cE,getIndexRange:()=>{},parseSegments:oE,parseFeedableSegmentChunk:uE,getSegmentEndTime:lE};var dt=require("@vkontakte/videoplayer-shared");var Vh=require("@vkontakte/videoplayer-shared");var Bh={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"}},_h=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=Ti(i,t),a=r in Bh,s=a?Bh[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=Ti(l),d=u*2**((o-1)*8)+c,f=t+o,h;return f+d>i.byteLength?h=new DataView(i.buffer,i.byteOffset+f):h=new DataView(i.buffer,i.byteOffset+f,d),{tag:a?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:f,tagSize:f+d,value:h,valueSize:d}},Ti=(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 Ti(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,Vh.assertNever)(e)}},Nt=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=_h(r);if(!e(a))return;a.type==="master"&&Nt(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},Nh=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=_h(i);return Nt(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 Fh=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],dE=[231,22612,22743,167,171,163,160,175],pE=i=>{let e,t,r,a,s=!1,n=!1,o=!1,l,u,c=!1,d=0;return Nt(i,({tag:f,type:h,value:b,valueSize:I})=>{if(f===21419){let v=je(b,h);u=Ti(v)}else f!==21420&&(u=void 0);return f===408125543?(e=b.byteOffset,t=b.byteOffset+I):f===357149030?s=!0:f===290298740?n=!0:f===2807729?r=je(b,h):f===17545?a=je(b,h):f===21420&&u===475249515?l=je(b,h):f===374648427?Nt(b,({tag:v,type:T,value:y})=>v===30321?(c=je(y,T)===1,!1):!0):s&&n&&Fh.includes(f)&&(o=!0),!o}),(0,dt.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,dt.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,dt.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}}}},hE=i=>{if((0,dt.isNullable)(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},fE=(i,e)=>{let t=!1,r=!1,a=o=>(0,dt.isNonNullable)(o.time)&&(0,dt.isNonNullable)(o.position),s=[],n;return Nt(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&&Fh.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}}})},mE=i=>{let e=0,t=!1;try{Nt(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):dE.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},qh={validateData:Nh,parseInit:pE,getIndexRange:hE,parseSegments:fE,parseFeedableSegmentChunk:mE};var To=_e(pf(),1),vr=require("@vkontakte/videoplayer-shared");var hf=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var ff=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},Ft=(i,e)=>{let t=i;t=(0,To.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,To.default)(t,n,(o,l)=>(0,vr.isNullable)(s)?o:(0,vr.isNullable)(l)?s:s.padStart(parseInt(l,10),"0"))}return t},bf=(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,f,h=s.getAttribute("mediaPresentationDuration"),b=n.getAttribute("duration"),v=s.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)f=ff(h);else if(b){let E=ff(b);(0,vr.isNonNullable)(E)&&(f=E)}else v&&(f=parseInt(v,10));let T=0,y=s.getAttribute("profiles")?.split(",")??[],M=y.includes("urn:webm:dash:profile:webm-on-demand:2012")||y.includes("urn:mpeg:dash:profile:webm-on-demand:2012")?"webm":"mp4";for(let E of l){let k=E.getAttribute("mimeType"),z=E.getAttribute("codecs"),j=E.getAttribute("contentType")??k?.split("/")[0],N=E.getAttribute("profiles")?.split(",")??[],Y=E.querySelectorAll("Representation"),w=E.querySelector("SegmentTemplate");if(j==="text"){for(let $ of Y){let U=$.getAttribute("id")||"",re=E.getAttribute("lang"),le=E.getAttribute("label"),Me=$.querySelector("BaseURL")?.textContent?.trim()??"",C=new URL(Me||o,e).toString(),W=U.includes("_auto");a.text.push({id:U,lang:re,label:le,isAuto:W,kind:"text",url:C})}continue}for(let $ of Y){let U=$.getAttribute("mimeType")??k,re=$.getAttribute("codecs")??z??"",le=$.getAttribute("contentType")??U?.split("/")[0]??j,Me=E.getAttribute("profiles")?.split(",")??[],C=parseInt($.getAttribute("width")??"",10),W=parseInt($.getAttribute("height")??"",10),ie=parseInt($.getAttribute("bandwidth")??"",10)/1e3,se=$.getAttribute("frameRate")??"",Te=$.getAttribute("quality")??void 0,bt=se?hf(se):void 0,os=$.getAttribute("id")??(T++).toString(10),qi=le==="video"?`${W}p`:le==="audio"?`${ie}Kbps`:re,K=`${os}@${qi}`,Ie=$.querySelector("BaseURL")?.textContent?.trim()??"",Ee=new URL(Ie||o,e).toString(),Oe=[...y,...N,...Me],tt,Ir=$.querySelector("SegmentBase"),xe=$.querySelector("SegmentTemplate")??w;if(Ir){let Be=$.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ye,us]=Be.split("-").map(zt=>parseInt(zt,10)),gt={from:Ye,to:us},Er=$.querySelector("SegmentBase")?.getAttribute("indexRange"),[ls,Ui]=Er?Er.split("-").map(zt=>parseInt(zt,10)):[],xr=Er?{from:ls,to:Ui}:void 0;tt={type:"byteRange",url:Ee,initRange:gt,indexRange:xr}}else if(xe){let Be={representationId:$.getAttribute("id")??void 0,bandwidth:$.getAttribute("bandwidth")??void 0},Ye=parseInt(xe.getAttribute("timescale")??"",10),us=xe.getAttribute("initialization")??"",gt=xe.getAttribute("media"),Er=parseInt(xe.getAttribute("startNumber")??"",10)??1,ls=Ft(us,Be);if(!gt)throw new ReferenceError("No media attribute in SegmentTemplate");let Ui=xe.querySelectorAll("SegmentTimeline S")??[],xr=[],zt=0,cs="",ds=0;if(Ui.length){let Hi=Er,Ve=0;for(let Kt of Ui){let We=parseInt(Kt.getAttribute("d")??"",10),At=parseInt(Kt.getAttribute("r")??"",10)||0,ji=parseInt(Kt.getAttribute("t")??"",10);Ve=Number.isFinite(ji)?ji:Ve;let ps=We/Ye*1e3,am=Ve/Ye*1e3;for(let Gi=0;Gi<At+1;Gi++){let sm=Ft(gt,{...Be,segmentNumber:Hi.toString(10),segmentTime:(Ve+Gi*We).toString(10)}),Mo=(am??0)+Gi*ps,nm=Mo+ps;Hi++,xr.push({time:{from:Mo,to:nm},url:sm})}Ve+=(At+1)*We,zt+=(At+1)*ps}ds=Ve/Ye*1e3,cs=Ft(gt,{...Be,segmentNumber:Hi.toString(10),segmentTime:Ve.toString(10)})}else if((0,vr.isNonNullable)(f)){let Ve=parseInt(xe.getAttribute("duration")??"",10)/Ye*1e3,Kt=Math.ceil(f/Ve),We=0;for(let At=1;At<Kt;At++){let ji=Ft(gt,{...Be,segmentNumber:At.toString(10),segmentTime:We.toString(10)});xr.push({time:{from:We,to:We+Ve},url:ji}),We+=Ve}ds=We,cs=Ft(gt,{...Be,segmentNumber:Kt.toString(10),segmentTime:We.toString(10)})}let im={time:{from:ds,to:1/0},url:cs};tt={type:"template",baseUrl:Ee,segmentTemplateUrl:gt,initUrl:ls,totalSegmentsDurationMs:zt,segments:xr,nextSegmentBeyondManifest:im,timescale:Ye}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!le||!U)continue;let vt={video:"video",audio:"audio",text:"text"}[le];vt&&a[vt].push({id:K,kind:vt,segmentReference:tt,profiles:Oe,duration:f,bitrate:ie,mime:U,codecs:re,width:C,height:W,fps:bt,quality:Te})}}return{dynamic:u,liveAvailabilityStartTime:d,duration:f,container:M,representations:a}};var Eo=_e(_a(),1);var vf=require("@vkontakte/videoplayer-shared"),gf=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s})=>{let n=(s?Et(s):void 0)??(0,vf.videoSizeToQuality)({width:e,height:t});return n&&{id:i,quality:n,bitrate:r,size:{width:e,height:t},fps:a}},Sf=({id:i,bitrate:e})=>({id:i,bitrate:e}),yf=(i,e,t)=>{let r=e.indexOf(t);return(0,Eo.default)(i,Math.round(i.length*r/e.length))??(0,Eo.default)(i,-1)},Tf=({id:i,lang:e,label:t,url:r,isAuto:a})=>({id:i,url:r,isAuto:a,type:"internal",language:e,label:t}),xo=i=>"url"in i,qt=i=>i.type==="template",Ii=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var Ei=class{constructor(e,t,r,a,{fetcher:s,tuning:n,getCurrentPosition:o,isActiveLowLatency:l,compatibilityMode:u=!1,manifest:c}){this.currentSegmentLength$=new x.ValueSubject(0);this.onLastSegment$=new x.ValueSubject(!1);this.fullyBuffered$=new x.ValueSubject(!1);this.playingRepresentation$=new x.ValueSubject(void 0);this.playingRepresentationInit$=new x.ValueSubject(void 0);this.error$=new x.Subject;this.gaps=[];this.subscription=new x.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ct;this.destroyAbortController=new ct;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,x.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,x.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 Mh(this.sourceBuffer),this.subscription.add((0,x.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>this.error$.next({id:"SegmentEjection",category:x.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:n}))),this.subscription.add((0,x.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:x.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{if(!this.sourceBuffer)return;let o=Math.min(this.bufferLimit,mo(this.sourceBuffer.buffered)*.8);this.bufferLimit=o,this.pruneBuffer(this.getCurrentPosition(),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,x.assertNonNullable)(r,"No init buffer for starting representation"),(0,x.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,x.abortable)(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let t=this.representations.get(e);(0,x.assertNonNullable)(t,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,x.isNullable)(a)||(0,x.isNullable)(r)?yield this.loadInit(t,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,x.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal);let s=this.getCurrentPosition();(0,x.isNonNullable)(s)&&(this.isLive||(r.forEach(n=>n.status="none"),this.pruneBuffer(s,1/0,!0)),this.maintain(s))}.bind(this));this.seekLive=(0,x.abortable)(this.destroyAbortController.signal,async function*(e){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(let o of this.representations.keys()){let l=e.find(d=>d.id===o);l&&this.representations.set(o,l);let u=this.representations.get(o);if(!u||!qt(u.segmentReference))return;let c=this.getActualLiveStartingSegments(u.segmentReference);this.segments.set(u.id,c)}let t=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(t);(0,x.assertNonNullable)(r);let a=this.segments.get(t);(0,x.assertNonNullable)(a,"No segments for starting representation");let s=this.initData.get(t);if((0,x.assertNonNullable)(s,"No init buffer for starting representation"),!(s instanceof ArrayBuffer))return;let n=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),n&&(yield this.sourceBufferTaskQueue.remove(n.from*1e3,n.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(s,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));switch(this.fetcher=s,this.tuning=n,this.compatibilityMode=u,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isActiveLowLatency=l,this.isLive=!!c?.dynamic,this.container=r,r){case"mp4":this.containerParser=Oh;break;case"webm":this.containerParser=qh;break;default:(0,x.assertNever)(r)}this.initData=new Map(a.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(a.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 ct,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,x.isNullable)(e)||(0,x.isNullable)(this.downloadingRepresentationId)||(0,x.isNullable)(this.playingRepresentationId)||(0,x.isNullable)(this.sourceBuffer)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if((0,x.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=Pt(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)&&mo(this.sourceBuffer.buffered)>=this.bufferLimit){let u=Pt(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,gr.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&&Pt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,gr.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,x.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?.representations[this.kind].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){for(let t of e?.representations[this.kind].values()??[]){if(!t||!qt(t.segmentReference))return;let r=t.segmentReference.segments.map(o=>({...o,status:"none",size:void 0})),a=this.segments.get(t.id)??[],s=(0,gr.default)(a,-1)?.time.to??0,n=r?.findIndex(o=>Math.floor(s)>=Math.floor(o.time.from)&&Math.floor(s)<=Math.floor(o.time.to));if(n===-1){this.liveUpdateSegmentIndex=0;let o=this.getActualLiveStartingSegments(t.segmentReference);this.segments.set(t.id,o)}else{let o=r.slice(n+1);this.segments.set(t.id,[...a,...o])}}}updateLowLatencyLive(e){if(this.isActiveLowLatency())for(let t of this.representations.values()){let r=t.segmentReference;if(!qt(r))return;let a=Math.round(e.segment.time.to*r.timescale/1e3).toString(10),s=Ft(r.segmentTemplateUrl,{segmentTime:a}),n=this.segments.get(t.id)??[],o=n.find(u=>Math.floor(u.time.from)===Math.floor(e.segment.time.from));o&&(o.time.to=e.segment.time.to),!!n.find(u=>Math.floor(u.time.from)===Math.floor(e.segment.time.to))||n.push({status:"none",time:{from:e.segment.time.to,to:1/0},url:s})}}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:f,to:h}},b)=>{let I=f<=r&&h>=r,v=f>r||I||b===0&&r===0,T=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&f<=r+T||h<=r+T;return(d==="none"||d==="partially_ejected"&&v&&y&&this.sourceBuffer&&!ti(this.sourceBuffer.buffered,r))&&v&&y});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 f=s[d];if(n+=f.byte.to+1-f.byte.from,o+=f.time.to+1-f.time.from,f.status==="none"||f.status==="partially_ejected")l.push(f);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,x.abortable)(o,async function*(){let c=(0,x.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(this.isActiveLowLatency()){let f=t.segmentReference.timescale;a.segment.time.to=this.containerParser.getSegmentEndTime(d,f)}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]),Ii(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,x.abortable)(n,async function*(){let l=(0,x.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(u,l),(0,x.fromEvent)(window,"online").pipe((0,x.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),Ii(l)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(qt(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,gr.default)(e,0).byte.from,to:(0,gr.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:x.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}}}}prepareTemplateFetchSegmentParams(e,t){if(!qt(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:x.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||!this.representations.get(t)))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=this.containerParser.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}){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,f=l==="byteRange",h=f?d.byte.to-d.byte.from+1:u;if(c.representationId!==t||!(!f||d.byte.from>=r&&d.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let I=f?d.byte.from-r:0,v=f?d.byte.to-r:e.byteLength,T=I<a,y=v<=a;if(d.status==="downloading"&&T&&y){d.status="downloaded";let M=new DataView(e.buffer,e.byteOffset+I,h);this.sourceBufferTaskQueue.append(M,s).then(E=>E&&!s.aborted?this.onSegmentFullyAppended(c,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&T&&(c.loadedBytes=Math.min(h,a-I),c.loadedBytes>c.feedingBytes)){let M=new DataView(e.buffer,e.byteOffset+I+c.feedingBytes,c.loadedBytes-c.feedingBytes),E=c.loadedBytes===h?M:this.containerParser.parseFeedableSegmentChunk(M);E?.byteLength&&(d.status="partially_fed",c.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,s).then(k=>{if(s.aborted)n();else if(k)c.fedBytes+=E.byteLength,c.fedBytes===h&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<h)return;n()}}))}}}onSegmentFullyAppended(e,t){this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",xo(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.isActiveLowLatency()&&this.updateLowLatencyLive(e),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=ho(()=>(0,If.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,x.abortable)(this.destroyAbortController.signal,async function*(){let o=(0,x.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,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 f=c;this.isLive&&qt(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),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:x.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||(0,x.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=xo(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 f of this.segments.values())for(let h of f)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(d)){s=c,n=d;break}}if(o=isFinite(s)&&isFinite(n),!o&&r){a=0,s=1/0,n=-1/0;let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let d of c)d.time.from>e+u&&d.status==="fed"&&l(d)}return o=isFinite(s)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(s,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let a={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){a=void 0;break}o>r.time.from&&o<r.time.to&&(a.from=o),n<r.time.to&&n>r.time.from&&(a.to=n)}}a&&a.to-a.from>1&&!this.gaps.some(s=>a&&s.from===a.from&&s.to===a.to)&&this.gaps.push(a)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=ho(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:x.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if((0,x.isNullable)(this.sourceBuffer)||(0,x.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 xi=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var Ef=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 Ga=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 ct;this.subscription=new X.Subscription;this.fetchManifest=(0,X.abortable)(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=xi(t));let r=yield lt(t,{signal:this.abortAllController.signal}).catch(Pi);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 N=new URL(u,location.href);N.searchParams.append("bytes",`${r.from}-${r.to}`),u=N.toString();break}default:(0,X.assertNever)(t)}this.requestQuic&&(u=xi(u));let d=this.abortAllController.signal,f;if(n){let N=new ct;if(f=(0,X.merge)((0,X.fromEvent)(this.abortAllController.signal,"abort"),(0,X.fromEvent)(n,"abort")).subscribe(()=>{try{N.abort()}catch(Y){Pi(Y)}}),this.abortAllController.signal.aborted||n.aborted)try{N.abort()}catch(Y){Pi(Y)}d=N.signal}let h=(0,X.now)(),b=yield lt(u,{priority:s,headers:c,signal:d}).catch(Pi),I=(0,X.now)();if(!b)return f?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(I-h),!b.ok||!b.body)return f?.unsubscribe(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`));if(this.onHeadersReceived(b.headers),!a&&!o)return f?.unsubscribe(),b.arrayBuffer();let[v,T]=b.body.tee(),y=v.getReader();o&&this.throughputEstimator?.trackStream(T,l);let M=0,E=new Uint8Array(0),k=!1,z=N=>{f?.unsubscribe(),k=!0,Pi(N)},j=(0,X.abortable)(d,async function*({done:N,value:Y}){if(M===0&&this.lastRequestFirstBytes$.next((0,X.now)()-h),d.aborted){f?.unsubscribe();return}if(!N&&Y){let w=new Uint8Array(E.length+Y.length);w.set(E),w.set(Y,E.length),E=w,M+=Y.byteLength,a?.(new DataView(E.buffer),M),yield y?.read().then(j,z)}}.bind(this));return yield y?.read().then(j,z),f?.unsubscribe(),k?null:E.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 f=new DataView(d,a-n,s-n+1);if(!t.validateData(f))throw new Error("Invalid media file");let h=t.parseInit(f),b=e.indexRange??t.getIndexRange(h);if(!b)throw new ReferenceError("No way to load representation index");let I;if(l)I=new DataView(d,b.from-n,b.to-b.from+1);else{let T=yield this.fetch(e.url,{range:b,priority:r,measureThroughput:!1});if(!T)return null;I=new DataView(T)}let v=t.parseSegments(I,h,b);return{init:h,dataView:new DataView(d),segments:v}}.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}=Ef(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()}},Pi=i=>{if(!Ii(i))throw i};var Ut=(i,e,t)=>t*e+(1-t)*i,Po=(i,e)=>i.reduce((t,r)=>t+r,0)/e,xf=(i,e,t,r)=>{let a=0,s=t,n=Po(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 ki=require("@vkontakte/videoplayer-shared"),kt=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 ki.ValueSubject(e.initial),this.debounced$=new ki.ValueSubject(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new pe(`raw_${t}`),this.smoothedSeries$=new pe(`smoothed_${t}`),this.reportedSeries$=new pe(`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,ki.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 Ya=class extends kt{constructor(t){super(t);this.slow=this.fast=t.initial}updateSmoothedValue(t){this.slow=Ut(this.slow,t,this.params.emaAlphaSlow),this.fast=Ut(this.fast,t,this.params.emaAlphaFast);let r=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=r(this.slow,this.fast)}};var Wa=class extends kt{constructor(t){super(t);this.emaSmoothed=t.initial}updateSmoothedValue(t){let r=Po(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ut(this.emaSmoothed,t,this.params.emaAlpha);let a=xf(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=a?this.emaSmoothed:r}};var Qa=class extends kt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?Ut(this.smoothed,t,this.params.emaAlpha):t}};var Ht=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new Ya({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new Wa({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 Qa({initial:e,label:"liveEdgeDelay",...t})}};var Pf=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};var pt=()=>window.ManagedMediaSource||window.MediaSource,za=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),kf=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),wf=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var Af=["timeupdate","progress","play","seeked","stalled","waiting"];var Ka=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new g.Subscription;this.representationSubscription=new g.Subscription;this.state$=new H("none");this.currentVideoRepresentation$=new g.ValueSubject(void 0);this.currentVideoRepresentationInit$=new g.ValueSubject(void 0);this.currentVideoSegmentLength$=new g.ValueSubject(0);this.currentAudioSegmentLength$=new g.ValueSubject(0);this.error$=new g.Subject;this.lastConnectionType$=new g.ValueSubject(void 0);this.lastConnectionReused$=new g.ValueSubject(void 0);this.lastRequestFirstBytes$=new g.ValueSubject(void 0);this.isLive$=new g.ValueSubject(!1);this.liveDuration$=new g.ValueSubject(0);this.liveAvailabilityStartTime$=new g.ValueSubject(void 0);this.bufferLength$=new g.ValueSubject(0);this.liveLoadBufferLength$=new g.ValueSubject(0);this.livePositionFromPlayer$=new g.ValueSubject(0);this.timeInWaiting=0;this.isActiveLowLatency=!1;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new g.Subject;this.gapWatchdogActive=!1;this.destroyController=new ct;this.initManifest=(0,g.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?.representations.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:g.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,g.abortable)(this.destroyController.signal,async function*(){let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(a=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:g.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:a})});if(!e)return null;let t;try{t=bf(e??"",this.manifestUrlString)}catch(a){this.error$.next({id:"ManifestParsing",category:g.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:a})}if(!t)return null;let r=({kind:a,mime:s,codecs:n})=>!!(this.element?.canPlayType?.(s)&&pt()?.isTypeSupported?.(`${s}; codecs="${n}"`)||a==="text");return 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)),{...t,representations:(0,Rf.default)(Object.entries(t.representations).map(([a,s])=>[a,s.filter(r)]))}}.bind(this));this.initRepresentations=(0,g.abortable)(this.destroyController.signal,async function*(e,t,r){(0,g.assertNonNullable)(this.manifest),(0,g.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=h=>{this.representationSubscription.add((0,g.fromEvent)(h,"error").pipe((0,g.filter)(b=>!!this.element?.played.length)).subscribe(b=>{this.error$.next({id:"VideoSource",category:g.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:b})}))};this.source=this.tuning.useManagedMediaSource?wf():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 h=document.createElement("source");a(h),h.type="application/x-mpegurl",h.src=r.url,this.element.appendChild(h)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency=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,manifest:this.manifest};if(this.videoBufferManager=new Ei("video",this.source,this.manifest.container,this.manifest.representations.video,n),this.bufferManagers=[this.videoBufferManager],(0,g.isNonNullable)(t)&&(this.audioBufferManager=new Ei("audio",this.source,this.manifest.container,this.manifest.representations.audio,n),this.bufferManagers.push(this.audioBufferManager)),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,g.interval)(1e3).subscribe(h=>{if(this.element?.paused){let b=eo(this.manifestUrlString,2);this.manifestUrlString=de(this.manifestUrlString,b+1e3,2)}})),this.representationSubscription.add((0,g.merge)(...Af.filter(h=>h!=="waiting").map(h=>(0,g.fromEvent)(this.element,h))).pipe((0,g.map)(h=>this.element?Pt(this.element.buffered,this.element.currentTime*1e3):0),(0,g.filterChanged)(),(0,g.filter)(h=>!!h),(0,g.tap)(h=>{this.stallWatchdogSubscription?.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe((0,g.filter)(b=>this.isActiveLowLatency&&!!b)).subscribe(b=>this.liveEstimatedDelay.next(b))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(b=>{if(!this.isActiveLowLatency)return;let I=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=b-I,M=1+Math.sign(y)*T;Math.abs(y)<v?M=1:Math.abs(y)>v*2&&(M=1+Math.sign(y)*T*2),Pf(this.element,M)})),this.representationSubscription.add(this.bufferLength$.subscribe(b=>{let I=0;if(b){let v=(this.element?.currentTime??0)*1e3;I=Math.min(...this.bufferManagers.map(y=>y.getLiveSegmentsToLoadState(this.manifest)?.to??v))-v}this.liveLoadBufferLength$.getValue()!==I&&this.liveLoadBufferLength$.next(I)}));let h=0;this.representationSubscription.add((0,g.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,g.throttle)(1e3)).subscribe(async({liveLoadBufferLength:b,bufferLength:I})=>{if((0,g.assertNonNullable)(this.element),this.isUpdatingLive)return;let v=this.element.playbackRate,T=eo(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,M=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*v),E=this.tuning.dashCmafLive.normalizedActualBufferOffset*v,k=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*v,z=this.isActiveLowLatency?I:b,j=3;if(this.isActiveLowLatency?j=0:z<M+k&&z>=M?j=1:T!==0&&z<M&&(j=2),isFinite(b)&&(h=b>h?b:h),j===2||j===1){let N=h-(M+E),Y=this.normolizeLiveOffset(Math.trunc(T+N/v)),w=Math.abs(Y-T),$;!b||w<=this.tuning.dashCmafLive.offsetCalculationError?$=T:Y>0&&w>this.tuning.dashCmafLive.offsetCalculationError?$=Y:$=0,this.manifestUrlString=de(this.manifestUrlString,$,2)}j!==3&&j!==0&&(h=0,this.updateLive())}))}let o=(0,g.merge)(...this.bufferManagers.map(h=>h.fullyBuffered$)).pipe((0,g.map)(()=>this.bufferManagers.every(h=>h.fullyBuffered$.getValue()))),l=(0,g.merge)(...this.bufferManagers.map(h=>h.onLastSegment$)).pipe((0,g.map)(()=>this.bufferManagers.some(h=>h.onLastSegment$.getValue())));this.representationSubscription.add((0,g.merge)(this.forceEnded$,(0,g.combine)({allBuffersFull:o,someBufferEnded:l}).pipe((0,g.filter)(({allBuffersFull:h,someBufferEnded:b})=>h&&b))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{this.source?.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:g.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add((0,g.merge)(...this.bufferManagers.map(h=>h.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.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$)),this.source.readyState!=="open"&&(yield new Promise(h=>this.source?.addEventListener("sourceopen",h)));let u=this.manifest.duration??0,c=(h,b)=>Math.max(h,b.duration??0),d=this.manifest.representations.audio.reduce(c,u),f=this.manifest.representations.video.reduce(c,u);(d||f)&&(this.source.duration=Math.max(d,f)/1e3),this.audioBufferManager&&(0,g.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.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,g.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:g.ErrorCategory.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Ga({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Ht.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){(0,g.assertNonNullable)(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency=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?.representations.video),await this.audioBufferManager?.seekLive(this.manifest?.representations.audio))}initBuffer(){(0,g.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,g.merge)(...Af.map(e=>(0,g.fromEvent)(this.element,e)),(0,g.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:g.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,g.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,g.fromEvent)(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&ti(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`);this.isLive$.getValue()&&this.seekLive(this.liveLastSeekOffset)}};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=(0,g.interval)(1e3).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:g.ErrorCategory.FATAL,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t)}seek(e,t){(0,g.assertNonNullable)(this.element),(0,g.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),ti(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)}getRepresentations(){return this.manifest?.representations}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency&&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 Ja=class{constructor(e,t){this.fov=e,this.orientation=t}};var Xa=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 Lf=`attribute vec2 a_vertex;
|
|
38
38
|
attribute vec2 a_texel;
|
|
39
39
|
|
|
40
40
|
varying vec2 v_texel;
|
|
@@ -45,7 +45,7 @@ void main(void) {
|
|
|
45
45
|
// save texel vector to pass to fragment shader
|
|
46
46
|
v_texel = a_texel;
|
|
47
47
|
}
|
|
48
|
-
`;var
|
|
48
|
+
`;var $f=`#ifdef GL_ES
|
|
49
49
|
precision highp float;
|
|
50
50
|
precision highp int;
|
|
51
51
|
#else
|
|
@@ -88,5 +88,5 @@ void main(void) {
|
|
|
88
88
|
// sample using new coordinates
|
|
89
89
|
gl_FragColor = texture2D(u_texture, tc);
|
|
90
90
|
}
|
|
91
|
-
`;var Ja=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 za(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ka(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(Pf,this.gl.VERTEX_SHADER),r=this.createShader(kf,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,f=t+a;return[s,n,o,l,u,c,d,f]}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 Gt=class{constructor(e){this.subscription=new D.Subscription;this.videoState=new H("stopped");this.elementSize$=new D.ValueSubject(void 0);this.textTracksManager=new Le;this.droppedFramesManager=new Na;this.videoTracks$=new D.ValueSubject([]);this.audioTracks=[];this.audioRepresentations=new Map;this.videoTrackSwitchHistory=new Va;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"),P(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"),P(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="ready"&&P(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset?.pause(),this.video.pause()):r?.to==="playing"&&P(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"&&P(this.params.desiredState.playbackState,"paused");return;default:return(0,D.assertNever)(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Ja(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=be(e.container),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 Qa({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=Se(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:D.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.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$:this.videoTracks$.pipe((0,D.map)(u=>u.map(({track:c})=>c)))}),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(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,D.filter)(D.isNonNullable),(0,D.once)()),e.firstBytesEvent$),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(Re(this.video,t.playbackRate,r.playbackRateState$,a)),s((0,D.observeElementSize)(this.video),this.elementSize$),s($e(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(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"){let c=[];this.audioTracks=[],this.textTracks=[];let d=this.player.getRepresentations();(0,D.assertNonNullable)(d,"Manifest not loaded or empty");let f=Array.from(d.audio).sort((g,T)=>T.bitrate-g.bitrate),h=Array.from(d.video).sort((g,T)=>T.bitrate-g.bitrate),b=Array.from(d.text);if(!this.params.tuning.isAudioDisabled)for(let g of f){let T=ff(g);T&&this.audioTracks.push({track:T,representation:g})}for(let g of h){let T=hf(g);if(T){c.push({track:T,representation:g});let y=!this.params.tuning.isAudioDisabled&&mf(f,h,g);y&&this.audioRepresentations.set(g.id,y)}}this.videoTracks$.next(c);for(let g of b){let T=bf(g);T&&this.textTracks.push({track:T,representation:g})}this.params.output.availableVideoTracks$.next(c.map(({track:g})=>g)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:g})=>g)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:g})=>g));let I=this.selectVideoRepresentation();(0,D.assertNonNullable)(I),this.player.initRepresentations(I.id,this.audioRepresentations.get(I.id)?.id,this.params.sourceHls)}else u==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a));let n=u=>e.error$.next({id:"RepresentationSwitch",category:D.ErrorCategory.WTF,message:"Switching representations threw",thrown:u});this.subscription.add((0,D.merge)(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,D.fromEvent)(this.video,"progress")).subscribe(()=>{let u=this.player.state$.getState(),c=this.player.state$.getTransition();if(u!=="running"||c||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoRepresentation(),f=this.params.desiredState.autoVideoTrackLimits.getTransition();f&&this.params.output.autoVideoTrackLimits$.next(f.to);let h=this.params.desiredState.autoVideoTrackSwitching.getState(),b=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(d){let I=d.id;!this.params.output.elementVisible$.getValue()&&h&&(I=this.videoTracks$.getValue().map(T=>T.representation).sort((T,y)=>y.bitrate-T.bitrate).filter(T=>{let y=(0,D.videoSizeToQuality)(T),M=(0,D.videoSizeToQuality)(d);if(y&&M)return(0,D.isLowerOrEqual)(y,M)&&(0,D.isLowerOrEqual)(y,b)}).map(T=>T.id)[0]),this.player.switchRepresentation("video",I).catch(n);let g=this.audioRepresentations.get(d.id);g&&this.player.switchRepresentation("audio",g.id).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,D.filterChanged)(),(0,D.map)(u=>u&&this.videoTracks$.getValue().find(({representation:{id:c}})=>c===u)?.track)).subscribe(e.currentVideoTrack$,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,D.map)(({to:u})=>u==="ready"),(0,D.filterChanged)());this.subscription.add((0,D.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,D.merge)(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=(0,D.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,D.observableFrom)(["init"])).pipe((0,D.debounce)(0));this.subscription.add(l.subscribe(this.syncPlayback,a))}selectVideoRepresentation(){let e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.videoTrack.getState()?.id,r=this.videoTracks$.getValue().find(({track:{id:d}})=>d===t)?.track,a=this.params.output.currentVideoTrack$.getValue(),s=Pt(this.video.buffered,this.video.currentTime*1e3),n=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,o=Math.min(s/Math.min(n,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),l=Math.max(r&&!e?this.audioRepresentations.get(r.id)?.bitrate??0:0,a?this.audioRepresentations.get(a.id)?.bitrate??0:0),u=xt(this.videoTracks$.getValue().map(({track:d})=>d),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:l,forwardBufferHealth:o,current:a,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),c=e?u??r:r??u;return c&&this.videoTracks$.getValue().find(({track:d})=>d===c)?.representation}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ye(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.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),ge(this.video)}};var ki=class extends Gt{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 wi=class extends Gt{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"&&!this.player.isActiveLowLatency){let s=e.position$.getValue()+(a-1);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 wf=_e(Ma(),1);var q=require("@vkontakte/videoplayer-shared"),Ge={};var Sr=(i,e)=>new q.Observable(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),Ai=class{constructor(e){this.subscription=new q.Subscription;this.videoState=new H("initializing");this.textTracksManager=new Le;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,q.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,q.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,q.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,q.assertNever)(e)}break;default:(0,q.assertNever)(t)}};this.video=be(e.container),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),ge(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:q.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,wf.default)(import("hls.js").then(a=>{e||(Ge.Hls=a.default,Ge.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){(0,q.assertNonNullable)(Ge.Hls,"hls.js not loaded"),this.hls=new Ge.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,q.assertNonNullable)(Ge.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=u=>{t.error$.next({id:"HlsJsProvider",category:q.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},a=Se(this.video),s=(u,c)=>this.subscription.add(u.subscribe(c,r));s(a.timeUpdate$,t.position$),s(a.durationChange$,t.duration$),s(a.ended$,t.endedEvent$),s(a.looped$,t.loopedEvent$),s(a.error$,t.error$),s(a.isBuffering$,t.isBuffering$),s(a.currentBuffer$,t.currentBuffer$),s(a.loadStart$,t.firstBytesEvent$),s(a.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(Re(this.video,e.playbackRate,a.playbackRateState$,r)),s($e(this.video),t.elementVisible$),this.subscription.add(Sr(this.hls,Ge.Events.ERROR).subscribe(u=>{u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:q.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"),P(e.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),P(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(Sr(this.hls,Ge.Events.MANIFEST_PARSED).pipe((0,q.map)(({levels:u})=>u.reduce((c,d)=>{let f=d.name||d.height.toString(10),{width:h,height:b}=d,I=Et(d.attrs.QUALITY??"")??(0,q.videoSizeToQuality)({width:h,height:b});if(!I)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,T={id:f.toString(),quality:I,bitrate:d.bitrate/1e3,size:{width:h,height:b},fps:g};return this.trackLevels.set(f,{track:T,level:d}),c.push(T),c},[]))),t.availableVideoTracks$),s(Sr(this.hls,Ge.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){let c=[];for(let d of u.subtitleTracks){let f=d.name,h=d.attrs.URI||"",b=d.lang,I="internal";c.push({id:f,url:h,language:b,type:I})}e.internalTextTracks.startTransitionTo(c)}}),s(Sr(this.hls,Ge.Events.LEVEL_LOADING).pipe((0,q.map)(({url:u})=>oe(u))),t.hostname$),s(Sr(this.hls,Ge.Events.FRAG_CHANGED),u=>{let{video:c,audio:d}=u.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3)}),this.subscription.add(It(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:r}));let n=u=>Array.from(this.trackLevels.values()).find(({level:c})=>c===u)?.track,o=Sr(this.hls,Ge.Events.LEVEL_SWITCHED).pipe((0,q.map)(({level:u})=>n(this.hls.levels[u])));o.pipe((0,q.filter)(q.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(It(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),u=>{if((0,q.isNullable)(u))return;let c=this.trackLevels.get(u.id)?.level;if(!c)return;let d=this.hls.levels.indexOf(c),f=this.hls.currentLevel,h=this.hls.levels[f];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let l=(0,q.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,q.observableFrom)(["init"])).pipe((0,q.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 ye(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:q.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("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"),P(this.params.desiredState.playbackState,"stopped",!0)}};var Af="X-Playback-Duration",Io=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(Af)?parseInt(e.headers.get(Af),10):void 0};var _=require("@vkontakte/videoplayer-shared");var xo=_e(Ia(),1);var Xa=require("@vkontakte/videoplayer-shared");var KE=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,Xa.videoSizeToQuality)({width:t,height:r})}return e??null},JE=(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,xo.default)(o[1].split(",").map(g=>g.split("="))),c=u.QUALITY??`stream-${u.BANDWIDTH}`,d=KE(u),f;u.BANDWIDTH&&(f=parseInt(u.BANDWIDTH,10)/1e3||void 0),!f&&u["AVERAGE-BANDWIDTH"]&&(f=parseInt(u["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=u["FRAME-RATE"]?parseFloat(u["FRAME-RATE"]):void 0,b;if(u.RESOLUTION){let[g,T]=u.RESOLUTION.split("x").map(y=>parseInt(y,10));g&&T&&(b={width:g,height:T})}let I=new URL(t[++s],e).toString();d&&r.push({id:c,quality:d,url:I,bandwidth:f,size:b,fps:h})}if(l){let u=(0,xo.default)(l[1].split(",").map(h=>h.split("=")).map(([h,b])=>[h,b.replace(/^"|"$/g,"")])),c=u.URI?.replace(/playlist$/,"subtitles.vtt"),d=u.LANGUAGE,f=u.NAME;c&&d&&a.push({type:"internal",id:d,label:f,language:d,url:c,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:a}},XE=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),Eo=0,Rf=async(i,e=i,t)=>{let a=await(await lt(i)).text();Eo+=1;try{let{qualityManifests:s,textTracks:n}=JE(a,e);return{qualityManifests:s,textTracks:n}}catch{if(Eo<=t.manifestRetryMaxCount)return await XE((0,Xa.getExponentialDelay)(Eo-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Rf(i,e,t)}return{qualityManifests:[],textTracks:[]}},Za=Rf;var Ri=class{constructor(e){this.subscription=new _.Subscription;this.videoState=new H("stopped");this.textTracksManager=new Le;this.manifests$=new _.ValueSubject([]);this.liveOffset=new nt;this.manifestStartTime$=new _.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"),P(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"?P(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),P(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.pause()):a?.to==="playing"&&P(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"&&(P(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,_.assertNever)(t)}};this.params=e,this.video=be(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:_.VideoQuality.INVARIANT,url:this.params.source.url},Za(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:_.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:_.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 _.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:_.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=Se(this.video),s=(o,l)=>this.subscription.add(o.subscribe(l,r));s(a.ended$,e.endedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.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(Re(this.video,t.playbackRate,a.playbackRateState$,r)),s($e(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),P(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,_.filterChanged)(),(0,_.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,_.isNonNullable)(u.to)){let d=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let f=this.manifests$.getValue().find(h=>h.id===d);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(oe(f.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,_.combine)({startTime:this.manifestStartTime$.pipe((0,_.filter)(_.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,_.map)(o=>o.map(({id:l,quality:u,size:c,bandwidth:d,fps:f})=>({id:l,quality:u,size:c,fps:f,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=(0,_.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,_.observableFrom)(["init"])).pipe((0,_.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ge(this.video)}prepare(){let e=this.selectManifest();if((0,_.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(),Io(n).then(o=>{if(!(0,_.isNullable)(o))this.maxSeekBackTime$.next(o);else{let l=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if((0,_.isNullable)(l)||!isFinite(l))try{lt(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();Io(d).then(f=>{(0,_.isNullable)(f)||this.maxSeekBackTime$.next(f)})}})}catch{}}})}playIfAllowed(){ye(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_.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 Li=class{constructor(e){this.subscription=new G.Subscription;this.videoState=new H("stopped");this.textTracksManager=new Le;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"),P(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"?P(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):a?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):a?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,G.assertNever)(t)}};this.params=e,this.video=be(e.container),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(oe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Za(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=Se(this.video),s=(o,l)=>this.subscription.add(o.subscribe(l));if(s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),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(Re(this.video,t.playbackRate,a.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),P(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 f=this.manifests$.getValue().find(h=>h.id===d);if(f){this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(oe(f.url));let h=this.params.desiredState.playbackRate.getState(),b=this.params.output.element$.getValue()?.playbackRate;if(h!==b){let I=this.params.output.element$.getValue();I&&(this.params.desiredState.playbackRate.setState(h),I.playbackRate=h)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),l&&l.from==="changing_manifest"&&this.videoState.setState(l.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe((0,G.map)(o=>o.map(({id:l,quality:u,size:c,bandwidth:d,fps:f})=>({id:l,quality:u,size:c,fps:f,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!(0,G.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),ge(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(){ye(this.video).then(e=>{e||(this.videoState.setState("paused"),P(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 $i=class{constructor(e){this.subscription=new J.Subscription;this.videoState=new H("stopped");this.trackUrls={};this.textTracksManager=new Le;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"),P(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"?P(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):r?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return(0,J.assertNever)(e)}};this.params=e,this.video=be(e.container),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=Se(this.video),s=(o,l)=>this.subscription.add(o.subscribe(l,r));s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),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(Re(this.video,t.playbackRate,a.playbackRateState$,r)),s($e(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),P(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),ge(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=Ei(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(oe(t))}playIfAllowed(){ye(this.video).then(e=>{e||(this.videoState.setState("paused"),P(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=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 $f=require("@vkontakte/videoplayer-shared"),Lf=["stun:videostun.mycdn.me:80"],ZE=1e3,ex=3,Po=()=>null,es=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=Po;this.externalStopCallback=Po;this.externalErrorCallback=Po;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:Lf}]};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:$f.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),ZE)}normalizeOptions(e={}){let t={stunServerList:Lf,maxRetryNumber:ex,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ci=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"),P(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"),P(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):r?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&P(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=be(e.container),this.liveStreamClient=new es(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),ge(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=Se(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(a.timeUpdate$,e.liveTime$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s($e(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,P(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(){ye(this.video).then(e=>{e||(this.videoState.setState("paused"),P(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 Di=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 S=require("@vkontakte/videoplayer-shared");var ht=require("@vkontakte/videoplayer-shared"),Cf=(0,ht.getCurrentBrowser)().device===ht.CurrentClientDevice.Android,ts=document.createElement("video"),ix='video/mp4; codecs="avc1.42000a,mp4a.40.2"',ax='video/mp4; codecs="hev1.1.6.L93.B0"',Df='video/webm; codecs="vp09.00.10.08"',Mf='video/webm; codecs="av01.0.00M.08"',sx='audio/mp4; codecs="mp4a.40.2"',nx='audio/webm; codecs="opus"',Wt={mms:Wa(),mse:Tf(),hls:!!(ts.canPlayType?.("application/x-mpegurl")||ts.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},De={mp4:!!ts.canPlayType?.("video/mp4"),webm:!!ts.canPlayType?.("video/webm"),cmaf:!0},Ze={h264:!!pt()?.isTypeSupported?.(ix),h265:!!pt()?.isTypeSupported?.(ax),vp9:!!pt()?.isTypeSupported?.(Df),av1:!!pt()?.isTypeSupported?.(Mf),aac:!!pt()?.isTypeSupported?.(sx),opus:!!pt()?.isTypeSupported?.(nx)},Mi=(Ze.h264||Ze.h265)&&Ze.aac,Qt,ox=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:Mf}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:Df}})]);Qt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{ox()}catch(i){console.error(i)}var yr=Wt.hls&&De.mp4,Of=()=>Object.keys(Ze).filter(i=>Ze[i]),Bf=(i,e=!1,t=!1)=>{let r=Wt.mse||Wt.mms&&t;return i.filter(a=>{switch(a){case"DASH_SEP":return r&&De.mp4&&Mi;case"DASH_WEBM":return r&&De.webm&&Ze.vp9&&Ze.opus;case"DASH_WEBM_AV1":return r&&De.webm&&Ze.av1&&Ze.opus;case"DASH_LIVE":return Wt.mse&&De.mp4&&Mi;case"DASH_LIVE_CMAF":return r&&De.mp4&&Mi&&De.cmaf;case"DASH_ONDEMAND":return r&&De.mp4&&Mi;case"HLS":case"HLS_ONDEMAND":return yr||e&&Wt.mse&&De.mp4&&Mi;case"HLS_LIVE":case"HLS_LIVE_CMAF":return yr;case"MPEG":return De.mp4;case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Wt.webrtc&&Wt.ws&&Ze.h264&&(De.mp4||De.webm);default:return(0,ht.assertNever)(a)}})},wt=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,ht.assertNever)(i)}return[e,t]},Vf=({webmCodec:i,androidPreferredFormat:e})=>{if(Cf)switch(e){case"mpeg":return["MPEG",...wt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...wt(i),"DASH_SEP","DASH_ONDEMAND","MPEG"];case"dash":return[...wt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return["DASH_SEP","DASH_ONDEMAND","MPEG",...wt(i),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...wt(i),"MPEG","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...wt(i),"DASH_ONDEMAND","HLS","HLS_ONDEMAND"];default:(0,ht.assertNever)(e)}return yr?[...wt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]:[...wt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]},_f=({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;if(Cf)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,ht.assertNever)(i)}else yr?o=n:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},ko=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"];var ft=require("@vkontakte/videoplayer-shared"),Nf=i=>new ft.Observable(e=>{let t=new ft.Subscription,r=i.desiredPlaybackState$.stateChangeStarted$.pipe((0,ft.map)(({from:u,to:c})=>`${u}-${c}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe((0,ft.map)(({type:u})=>u!==void 0)),n=new ft.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 ux={chunkDuration:5e3,maxParallelRequests:5},Oi=class{constructor(e){this.current$=new S.ValueSubject({type:void 0});this.providerError$=new S.Subject;this.noAvailableProvidersError$=new S.Subject;this.providerOutput={position$:new S.ValueSubject(0),duration$:new S.ValueSubject(1/0),volume$:new S.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new S.ValueSubject(void 0),currentVideoSegmentLength$:new S.ValueSubject(0),currentAudioSegmentLength$:new S.ValueSubject(0),availableVideoTracks$:new S.ValueSubject([]),availableAudioTracks$:new S.ValueSubject([]),isAudioAvailable$:new S.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new S.ValueSubject(!1),autoVideoTrackLimits$:new S.ValueSubject(void 0),currentBuffer$:new S.ValueSubject(void 0),isBuffering$:new S.ValueSubject(!0),error$:new S.Subject,warning$:new S.Subject,willSeekEvent$:new S.Subject,seekedEvent$:new S.Subject,loopedEvent$:new S.Subject,endedEvent$:new S.Subject,firstBytesEvent$:new S.Subject,firstFrameEvent$:new S.Subject,canplay$:new S.Subject,isLive$:new S.ValueSubject(void 0),isLowLatency$:new S.ValueSubject(!1),canChangePlaybackSpeed$:new S.ValueSubject(!0),liveTime$:new S.ValueSubject(void 0),liveBufferTime$:new S.ValueSubject(void 0),availableTextTracks$:new S.ValueSubject([]),currentTextTrack$:new S.ValueSubject(void 0),hostname$:new S.ValueSubject(void 0),httpConnectionType$:new S.ValueSubject(void 0),httpConnectionReused$:new S.ValueSubject(void 0),inPiP$:new S.ValueSubject(!1),inFullscreen$:new S.ValueSubject(!1),element$:new S.ValueSubject(void 0),elementVisible$:new S.ValueSubject(!0),availableSources$:new S.ValueSubject(void 0),is3DVideo$:new S.ValueSubject(!1)};this.subscription=new S.Subscription;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=Bf([..._f(this.params.tuning),...Vf(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>(0,S.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 Di(s);let n=[...ko(!0),...ko(!1)];this.chromecastFormatsIterator=new Di(n.filter(o=>(0,S.isNonNullable)(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources)}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()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,S.isNullable)(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:S.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,S.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":{let o=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,S.assertNonNullable)(o),new ki({...n,source:o,sourceHls:l})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,S.assertNonNullable)(o),new wi({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,S.assertNonNullable)(o),yr||!this.params.tuning.useHlsJs?new Li({...n,source:o}):new Ai({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,S.assertNonNullable)(o),new Ri({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,S.assertNonNullable)(o),new $i({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,S.assertNonNullable)(o),new Ph({...n,source:o,config:{...ux,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,S.assertNonNullable)(o),new Ci({container:r,source:o,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH_LIVE_WEBM":throw new Error("DASH_LIVE_WEBM is no longer supported");default:return(0,S.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,S.assertNonNullable)(o),new jr({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,S.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,S.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,S.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,Ff.default)(Object.entries(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new S.Subscription,t=!1,r=0;return e.add((0,S.merge)(this.providerOutput.error$,Nf({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,S.map)(a=>({id:`ProviderHangup:${a}`,category:S.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,S.filter)(({to:s})=>s==="playing"),(0,S.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===S.ErrorCategory.NETWORK,o=a.category===S.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 O=require("@vkontakte/videoplayer-shared");var lx=5e3,qf="one_video_throughput",Uf="one_video_rtt",Bi=window.navigator.connection,Hf=()=>{let i=Bi?.downlink;if((0,O.isNonNullable)(i)&&i!==10)return i*1e3},jf=()=>{let i=Bi?.rtt;if((0,O.isNonNullable)(i)&&i!==3e3)return i},Gf=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},wo=class i{constructor(e){this.subscription=new O.Subscription;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=i.load(qf)||(e.useBrowserEstimation?Hf():void 0)||lx,r=i.load(Uf)??(e.useBrowserEstimation?jf():void 0)??0;if(this.throughput$=new O.ValueSubject(t),this.rtt$=new O.ValueSubject(r),this.rttAdjustedThroughput$=new O.ValueSubject(Gf(t,r,e.rttPenaltyRequestSize)),this.throughput=Ht.getSmoothedValue(t,-1,e),this.rtt=Ht.getSmoothedValue(r,1,e),e.useBrowserEstimation){let a=()=>{let n=Hf();n&&this.throughput.next(n);let o=jf();(0,O.isNonNullable)(o)&&this.rtt.next(o)};Bi&&"onchange"in Bi&&this.subscription.add((0,O.fromEvent)(Bi,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{O.safeStorage.set(qf,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{O.safeStorage.set(Uf,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,O.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,O.map)(({throughput:a,rtt:s})=>Gf(a,s,e.rttPenaltyRequestSize)),(0,O.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,O.now)(),a=new O.Subscription;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add((0,O.fromEvent)(e,"progress").pipe((0,O.once)()).subscribe(s=>{t=s.loaded,r=(0,O.now)()}));break;case 1:case 0:a.add((0,O.fromEvent)(e,"loadstart").subscribe(()=>{t=0,r=(0,O.now)()}));break}a.add((0,O.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,O.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,O.now)(),n=0,o=(0,O.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,O.now)()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){if((0,O.now)()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=d.byteLength;else{let h=o-s;h&&this.addRawSpeed(n,h,1,t),n=d.byteLength,s=(0,O.now)()}o=(0,O.now)()}else a+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,O.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,O.now)()-o,this.concurrentDownloads.size),n=0,o=(0,O.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=O.safeStorage.get(e);if((0,O.isNonNullable)(t))return parseInt(t,10)??void 0}},Yf=wo;var Vi=require("@vkontakte/videoplayer-shared"),Wf={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:10}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:Vi.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Vi.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:3e4,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,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,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:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},Qf=i=>({...(0,Vi.fillWithDefault)(i,Wf),configName:[...i.configName??[],...Wf.configName]});var p=require("@vkontakte/videoplayer-shared");var mt=require("@vkontakte/videoplayer-shared"),Ao=({seekState:i,position$:e})=>(0,mt.merge)(i.stateChangeEnded$.pipe((0,mt.map)(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),(0,mt.filter)(mt.isNonNullable)),e.pipe((0,mt.filter)(()=>i.getState().state==="none")));var zf=require("@vkontakte/videoplayer-shared"),Kf=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return(0,zf.assertNonNullable)(e,`Wrong container or containerId {${i.container}}`),e};var rs=require("@vkontakte/videoplayer-shared"),Jf=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe((0,rs.filter)(a=>a.length>0),(0,rs.once)()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t?.getValue().find(r))&&e.startTransitionTo(i)};var _i=class{constructor(e={configName:[]}){this.subscription=new p.Subscription;this.logger=new p.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new p.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),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 p.ValueSubject("stopped"),position$:new p.ValueSubject(0),duration$:new p.ValueSubject(1/0),muted$:new p.ValueSubject(!1),volume$:new p.ValueSubject(1),availableQualities$:new p.ValueSubject([]),availableQualitiesFps$:new p.ValueSubject({}),availableAudioTracks$:new p.ValueSubject([]),isAudioAvailable$:new p.ValueSubject(!0),currentQuality$:new p.ValueSubject(void 0),isAutoQualityEnabled$:new p.ValueSubject(!0),autoQualityLimitingAvailable$:new p.ValueSubject(!1),autoQualityLimits$:new p.ValueSubject({}),currentPlaybackRate$:new p.ValueSubject(1),currentBuffer$:new p.ValueSubject({start:0,end:0}),isBuffering$:new p.ValueSubject(!0),isStalled$:new p.ValueSubject(!1),isEnded$:new p.ValueSubject(!1),isLooped$:new p.ValueSubject(!1),isLive$:new p.ValueSubject(void 0),canChangePlaybackSpeed$:new p.ValueSubject(void 0),atLiveEdge$:new p.ValueSubject(void 0),atLiveDurationEdge$:new p.ValueSubject(void 0),liveTime$:new p.ValueSubject(void 0),liveBufferTime$:new p.ValueSubject(void 0),currentFormat$:new p.ValueSubject(void 0),availableTextTracks$:new p.ValueSubject([]),currentTextTrack$:new p.ValueSubject(void 0),throughputEstimation$:new p.ValueSubject(void 0),rttEstimation$:new p.ValueSubject(void 0),videoBitrate$:new p.ValueSubject(void 0),hostname$:new p.ValueSubject(void 0),httpConnectionType$:new p.ValueSubject(void 0),httpConnectionReused$:new p.ValueSubject(void 0),surface$:new p.ValueSubject("none"),chromecastState$:new p.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new p.ValueSubject(void 0),intrinsicVideoSize$:new p.ValueSubject(void 0),availableSources$:new p.ValueSubject(void 0),is3DVideo$:new p.ValueSubject(!1),currentVideoSegmentLength$:new p.ValueSubject(0),currentAudioSegmentLength$:new p.ValueSubject(0)};this.events={inited$:new p.Subject,ready$:new p.Subject,started$:new p.Subject,playing$:new p.Subject,paused$:new p.Subject,stopped$:new p.Subject,willStart$:new p.Subject,willResume$:new p.Subject,willPause$:new p.Subject,willStop$:new p.Subject,willDestruct$:new p.Subject,watchCoverageRecord$:new p.Subject,watchCoverageLive$:new p.Subject,managedError$:new p.Subject,fatalError$:new p.Subject,ended$:new p.Subject,looped$:new p.Subject,seeked$:new p.Subject,willSeek$:new p.Subject,firstBytes$:new p.Subject,firstFrame$:new p.Subject,canplay$:new p.Subject,log$:new p.Subject};this.experimental={element$:new p.ValueSubject(void 0),tuningConfigName$:new p.ValueSubject([]),enableDebugTelemetry$:new p.ValueSubject(!1),dumpTelemetry:Th};if(this.initLogs(),this.tuning=Qf(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Wi({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Yf(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,(f,h)=>{let b=typeof h;return["number","string","boolean"].includes(b)?h:h===null?null:`<${b}>`})),u=`Player.${String(r)}`,c=`Exception calling ${u} (${l.join(", ")})`;throw this.events.fatalError$.next({id:u,category:p.ErrorCategory.WTF,message:c,thrown:o}),o}}}})}initVideo(e){return this.config=e,this.domContainer=Kf(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Oi({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}),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&&!Kr()?(0,p.fromEvent)(document,"visibilitychange").pipe((0,p.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}setQuality(e){(0,p.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,p.filter)(r=>r.length>0),(0,p.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,p.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 Jf(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,p.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return(0,p.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,p.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,p.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,p.filter)(({from:e})=>e==="stopped"),(0,p.once)()).subscribe(()=>{this.initedAt=(0,p.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:p.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,p.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,p.map)(n=>n.destination),(0,p.filterChanged)()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe((0,p.map)(n=>n.map(({quality:o})=>o).sort((o,l)=>(0,p.isInvariantQuality)(o)?1:(0,p.isInvariantQuality)(l)?-1:(0,p.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.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,p.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,p.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,p.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,p.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,p.combine)({hasLiveOffsetByPaused:(0,p.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,p.map)(n=>n.to),(0,p.filterChanged)(),(0,p.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,p.combine)({atLiveEdge:(0,p.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Ao({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,p.map)(({isLive:n,position:o,isLowLatency:l})=>{let u=this.getActiveLiveDelay(l);return n&&Math.abs(o)<u/1e3}),(0,p.filterChanged)(),(0,p.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,p.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,p.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,p.map)(({isLive:n,position:o,duration:l})=>n&&(Math.abs(l)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,p.filterChanged)(),(0,p.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,p.map)(n=>n.muted),(0,p.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,p.map)(n=>n.volume),(0,p.filterChanged)()).subscribe(this.info.volume$)).add(Ao({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,p.merge)(e.providerOutput.endedEvent$.pipe((0,p.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,p.mapTo)(!1))).pipe((0,p.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.noAvailableProvidersError$.pipe((0,p.map)(n=>({id:n?`No${n}`:"NoProviders",category:p.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,p.once)(),(0,p.map)(n=>n??(0,p.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe((0,p.once)(),(0,p.map)(()=>(0,p.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,p.once)(),(0,p.map)(()=>(0,p.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 p.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new p.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,p.filter)(({to:n})=>n==="playing"),(0,p.once)()).subscribe(()=>r.next(!1)));let a=0,s=(0,p.merge)(e.providerOutput.isBuffering$,t,r).pipe((0,p.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),(0,p.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,p.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,p.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,p.map)(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new p.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,p.filterChanged)((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,p.filter)(r=>r.length>0),(0,p.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,p.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,p.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,p.assertNonNullable)(this.providerContainer),(0,p.assertNonNullable)(e),yh(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Sh(t)),this.providerContainer.current$.subscribe(({type:t})=>Yr("provider",t)),e.duration$.subscribe(t=>Yr("duration",t)),e.availableVideoTracks$.pipe((0,p.filter)(t=>!!t.length),(0,p.once)()).subscribe(t=>Yr("tracks",t)),this.events.fatalError$.subscribe(new pe("fatalError")),this.events.managedError$.subscribe(new pe("managedError")),e.position$.subscribe(new pe("position")),e.currentVideoTrack$.pipe((0,p.map)(t=>t?.quality)).subscribe(new pe("quality")),this.info.currentBuffer$.subscribe(new pe("buffer")),e.isBuffering$.subscribe(new pe("isBuffering"))].forEach(t=>this.subscription.add(t)),Yr("codecs",Of())}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:p.ErrorCategory.DOM,message:String(a)})})};this.subscription.add((0,p.merge)((0,p.fromEvent)(document,"visibilitychange"),(0,p.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 et=require("@vkontakte/videoplayer-shared"),cx=`@vkontakte/videoplayer-core@${ls}`;
|
|
91
|
+
`;var Za=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 Ja(this.params.fov,this.params.orientation),this.cameraRotationManager=new Xa(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(Lf,this.gl.VERTEX_SHADER),r=this.createShader($f,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,f=t+a;return[s,n,o,l,u,c,d,f]}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 Gt=class{constructor(e){this.subscription=new D.Subscription;this.videoState=new H("stopped");this.elementSize$=new D.ValueSubject(void 0);this.textTracksManager=new Le;this.droppedFramesManager=new qa;this.videoTracks$=new D.ValueSubject([]);this.audioTracks=[];this.audioRepresentations=new Map;this.videoTrackSwitchHistory=new Na;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"),P(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"),P(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="ready"&&P(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset?.pause(),this.video.pause()):r?.to==="playing"&&P(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"&&P(this.params.desiredState.playbackState,"paused");return;default:return(0,D.assertNever)(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Za(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=be(e.container),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 Ka({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=Se(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:D.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.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$:this.videoTracks$.pipe((0,D.map)(u=>u.map(({track:c})=>c)))}),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(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,D.filter)(D.isNonNullable),(0,D.once)()),e.firstBytesEvent$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(Je(this.video,t.isLooped,a)),this.subscription.add(ge(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Re(this.video,t.playbackRate,r.playbackRateState$,a)),s((0,D.observeElementSize)(this.video),this.elementSize$),s($e(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(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"){let c=[];this.audioTracks=[],this.textTracks=[];let d=this.player.getRepresentations();(0,D.assertNonNullable)(d,"Manifest not loaded or empty");let f=Array.from(d.audio).sort((v,T)=>T.bitrate-v.bitrate),h=Array.from(d.video).sort((v,T)=>T.bitrate-v.bitrate),b=Array.from(d.text);if(!this.params.tuning.isAudioDisabled)for(let v of f){let T=Sf(v);T&&this.audioTracks.push({track:T,representation:v})}for(let v of h){let T=gf(v);if(T){c.push({track:T,representation:v});let y=!this.params.tuning.isAudioDisabled&&yf(f,h,v);y&&this.audioRepresentations.set(v.id,y)}}this.videoTracks$.next(c);for(let v of b){let T=Tf(v);T&&this.textTracks.push({track:T,representation:v})}this.params.output.availableVideoTracks$.next(c.map(({track:v})=>v)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:v})=>v)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:v})=>v));let I=this.selectVideoRepresentation();(0,D.assertNonNullable)(I),this.player.initRepresentations(I.id,this.audioRepresentations.get(I.id)?.id,this.params.sourceHls)}else u==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a));let n=u=>e.error$.next({id:"RepresentationSwitch",category:D.ErrorCategory.WTF,message:"Switching representations threw",thrown:u});this.subscription.add((0,D.merge)(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,D.fromEvent)(this.video,"progress")).subscribe(()=>{let u=this.player.state$.getState(),c=this.player.state$.getTransition();if(u!=="running"||c||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoRepresentation(),f=this.params.desiredState.autoVideoTrackLimits.getTransition();f&&this.params.output.autoVideoTrackLimits$.next(f.to);let h=this.params.desiredState.autoVideoTrackSwitching.getState(),b=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(d){let I=d.id;!this.params.output.elementVisible$.getValue()&&h&&(I=this.videoTracks$.getValue().map(T=>T.representation).sort((T,y)=>y.bitrate-T.bitrate).filter(T=>{let y=(0,D.videoSizeToQuality)(T),M=(0,D.videoSizeToQuality)(d);if(y&&M)return(0,D.isLowerOrEqual)(y,M)&&(0,D.isLowerOrEqual)(y,b)}).map(T=>T.id)[0]),this.player.switchRepresentation("video",I).catch(n);let v=this.audioRepresentations.get(d.id);v&&this.player.switchRepresentation("audio",v.id).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,D.filterChanged)(),(0,D.map)(u=>u&&this.videoTracks$.getValue().find(({representation:{id:c}})=>c===u)?.track)).subscribe(e.currentVideoTrack$,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,D.map)(({to:u})=>u==="ready"),(0,D.filterChanged)());this.subscription.add((0,D.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,D.merge)(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=(0,D.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,D.observableFrom)(["init"])).pipe((0,D.debounce)(0));this.subscription.add(l.subscribe(this.syncPlayback,a))}selectVideoRepresentation(){let e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.videoTrack.getState()?.id,r=this.videoTracks$.getValue().find(({track:{id:d}})=>d===t)?.track,a=this.params.output.currentVideoTrack$.getValue(),s=Pt(this.video.buffered,this.video.currentTime*1e3),n=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,o=Math.min(s/Math.min(n,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),l=Math.max(r&&!e?this.audioRepresentations.get(r.id)?.bitrate??0:0,a?this.audioRepresentations.get(a.id)?.bitrate??0:0),u=xt(this.videoTracks$.getValue().map(({track:d})=>d),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:l,forwardBufferHealth:o,current:a,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),c=e?u??r:r??u;return c&&this.videoTracks$.getValue().find(({track:d})=>d===c)?.representation}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ye(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.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 wi=class extends Gt{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 Ai=class extends Gt{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"&&!this.player.isActiveLowLatency){let s=e.position$.getValue()+(a-1);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 Cf=_e(Ba(),1);var q=require("@vkontakte/videoplayer-shared"),Ge={};var Sr=(i,e)=>new q.Observable(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),Ri=class{constructor(e){this.subscription=new q.Subscription;this.videoState=new H("initializing");this.textTracksManager=new Le;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,q.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,q.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,q.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,q.assertNever)(e)}break;default:(0,q.assertNever)(t)}};this.video=be(e.container),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),ve(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:q.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Cf.default)(import("hls.js").then(a=>{e||(Ge.Hls=a.default,Ge.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){(0,q.assertNonNullable)(Ge.Hls,"hls.js not loaded"),this.hls=new Ge.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,q.assertNonNullable)(Ge.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=u=>{t.error$.next({id:"HlsJsProvider",category:q.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},a=Se(this.video),s=(u,c)=>this.subscription.add(u.subscribe(c,r));s(a.timeUpdate$,t.position$),s(a.durationChange$,t.duration$),s(a.ended$,t.endedEvent$),s(a.looped$,t.loopedEvent$),s(a.error$,t.error$),s(a.isBuffering$,t.isBuffering$),s(a.currentBuffer$,t.currentBuffer$),s(a.loadStart$,t.firstBytesEvent$),s(a.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(ge(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Re(this.video,e.playbackRate,a.playbackRateState$,r)),s($e(this.video),t.elementVisible$),this.subscription.add(Sr(this.hls,Ge.Events.ERROR).subscribe(u=>{u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:q.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"),P(e.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),P(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(Sr(this.hls,Ge.Events.MANIFEST_PARSED).pipe((0,q.map)(({levels:u})=>u.reduce((c,d)=>{let f=d.name||d.height.toString(10),{width:h,height:b}=d,I=Et(d.attrs.QUALITY??"")??(0,q.videoSizeToQuality)({width:h,height:b});if(!I)return c;let v=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,T={id:f.toString(),quality:I,bitrate:d.bitrate/1e3,size:{width:h,height:b},fps:v};return this.trackLevels.set(f,{track:T,level:d}),c.push(T),c},[]))),t.availableVideoTracks$),s(Sr(this.hls,Ge.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){let c=[];for(let d of u.subtitleTracks){let f=d.name,h=d.attrs.URI||"",b=d.lang,I="internal";c.push({id:f,url:h,language:b,type:I})}e.internalTextTracks.startTransitionTo(c)}}),s(Sr(this.hls,Ge.Events.LEVEL_LOADING).pipe((0,q.map)(({url:u})=>oe(u))),t.hostname$),s(Sr(this.hls,Ge.Events.FRAG_CHANGED),u=>{let{video:c,audio:d}=u.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3)}),this.subscription.add(It(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:r}));let n=u=>Array.from(this.trackLevels.values()).find(({level:c})=>c===u)?.track,o=Sr(this.hls,Ge.Events.LEVEL_SWITCHED).pipe((0,q.map)(({level:u})=>n(this.hls.levels[u])));o.pipe((0,q.filter)(q.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(It(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),u=>{if((0,q.isNullable)(u))return;let c=this.trackLevels.get(u.id)?.level;if(!c)return;let d=this.hls.levels.indexOf(c),f=this.hls.currentLevel,h=this.hls.levels[f];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let l=(0,q.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,q.observableFrom)(["init"])).pipe((0,q.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 ye(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:q.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("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"),P(this.params.desiredState.playbackState,"stopped",!0)}};var Df="X-Playback-Duration",ko=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(Df)?parseInt(e.headers.get(Df),10):void 0};var _=require("@vkontakte/videoplayer-shared");var Ao=_e(xa(),1);var es=require("@vkontakte/videoplayer-shared");var tx=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,es.videoSizeToQuality)({width:t,height:r})}return e??null},rx=(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,Ao.default)(o[1].split(",").map(v=>v.split("="))),c=u.QUALITY??`stream-${u.BANDWIDTH}`,d=tx(u),f;u.BANDWIDTH&&(f=parseInt(u.BANDWIDTH,10)/1e3||void 0),!f&&u["AVERAGE-BANDWIDTH"]&&(f=parseInt(u["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=u["FRAME-RATE"]?parseFloat(u["FRAME-RATE"]):void 0,b;if(u.RESOLUTION){let[v,T]=u.RESOLUTION.split("x").map(y=>parseInt(y,10));v&&T&&(b={width:v,height:T})}let I=new URL(t[++s],e).toString();d&&r.push({id:c,quality:d,url:I,bandwidth:f,size:b,fps:h})}if(l){let u=(0,Ao.default)(l[1].split(",").map(h=>h.split("=")).map(([h,b])=>[h,b.replace(/^"|"$/g,"")])),c=u.URI?.replace(/playlist$/,"subtitles.vtt"),d=u.LANGUAGE,f=u.NAME;c&&d&&a.push({type:"internal",id:d,label:f,language:d,url:c,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:a}},ix=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),wo=0,Mf=async(i,e=i,t)=>{let a=await(await lt(i)).text();wo+=1;try{let{qualityManifests:s,textTracks:n}=rx(a,e);return{qualityManifests:s,textTracks:n}}catch{if(wo<=t.manifestRetryMaxCount)return await ix((0,es.getExponentialDelay)(wo-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Mf(i,e,t)}return{qualityManifests:[],textTracks:[]}},ts=Mf;var Li=class{constructor(e){this.subscription=new _.Subscription;this.videoState=new H("stopped");this.textTracksManager=new Le;this.manifests$=new _.ValueSubject([]);this.liveOffset=new nt;this.manifestStartTime$=new _.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"),P(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"?P(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),P(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.pause()):a?.to==="playing"&&P(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"&&(P(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,_.assertNever)(t)}};this.params=e,this.video=be(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:_.VideoQuality.INVARIANT,url:this.params.source.url},ts(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:_.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:_.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 _.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:_.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=Se(this.video),s=(o,l)=>this.subscription.add(o.subscribe(l,r));s(a.ended$,e.endedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.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(ge(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Re(this.video,t.playbackRate,a.playbackRateState$,r)),s($e(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),P(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,_.filterChanged)(),(0,_.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,_.isNonNullable)(u.to)){let d=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let f=this.manifests$.getValue().find(h=>h.id===d);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(oe(f.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,_.combine)({startTime:this.manifestStartTime$.pipe((0,_.filter)(_.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,_.map)(o=>o.map(({id:l,quality:u,size:c,bandwidth:d,fps:f})=>({id:l,quality:u,size:c,fps:f,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=(0,_.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,_.observableFrom)(["init"])).pipe((0,_.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,_.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(),ko(n).then(o=>{if(!(0,_.isNullable)(o))this.maxSeekBackTime$.next(o);else{let l=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if((0,_.isNullable)(l)||!isFinite(l))try{lt(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();ko(d).then(f=>{(0,_.isNullable)(f)||this.maxSeekBackTime$.next(f)})}})}catch{}}})}playIfAllowed(){ye(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_.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 $i=class{constructor(e){this.subscription=new G.Subscription;this.videoState=new H("stopped");this.textTracksManager=new Le;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"),P(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"?P(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):a?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):a?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,G.assertNever)(t)}};this.params=e,this.video=be(e.container),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(oe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),ts(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=Se(this.video),s=(o,l)=>this.subscription.add(o.subscribe(l));if(s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(Je(this.video,t.isLooped,r)),this.subscription.add(ge(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Re(this.video,t.playbackRate,a.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),P(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 f=this.manifests$.getValue().find(h=>h.id===d);if(f){this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(oe(f.url));let h=this.params.desiredState.playbackRate.getState(),b=this.params.output.element$.getValue()?.playbackRate;if(h!==b){let I=this.params.output.element$.getValue();I&&(this.params.desiredState.playbackRate.setState(h),I.playbackRate=h)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),l&&l.from==="changing_manifest"&&this.videoState.setState(l.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe((0,G.map)(o=>o.map(({id:l,quality:u,size:c,bandwidth:d,fps:f})=>({id:l,quality:u,size:c,fps:f,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!(0,G.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(){ye(this.video).then(e=>{e||(this.videoState.setState("paused"),P(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 Ci=class{constructor(e){this.subscription=new J.Subscription;this.videoState=new H("stopped");this.trackUrls={};this.textTracksManager=new Le;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"),P(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"?P(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):r?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return(0,J.assertNever)(e)}};this.params=e,this.video=be(e.container),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=Se(this.video),s=(o,l)=>this.subscription.add(o.subscribe(l,r));s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(Je(this.video,t.isLooped,r)),this.subscription.add(ge(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Re(this.video,t.playbackRate,a.playbackRateState$,r)),s($e(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),P(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=xi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(oe(t))}playIfAllowed(){ye(this.video).then(e=>{e||(this.videoState.setState("paused"),P(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=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 Bf=require("@vkontakte/videoplayer-shared"),Of=["stun:videostun.mycdn.me:80"],ax=1e3,sx=3,Ro=()=>null,rs=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=Ro;this.externalStopCallback=Ro;this.externalErrorCallback=Ro;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:Of}]};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:Bf.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),ax)}normalizeOptions(e={}){let t={stunServerList:Of,maxRetryNumber:sx,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Di=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"),P(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"),P(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):r?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&P(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=be(e.container),this.liveStreamClient=new rs(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=Se(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(a.timeUpdate$,e.liveTime$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s($e(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(ge(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,P(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(){ye(this.video).then(e=>{e||(this.videoState.setState("paused"),P(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 Mi=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 S=require("@vkontakte/videoplayer-shared");var ht=require("@vkontakte/videoplayer-shared"),Vf=(0,ht.getCurrentBrowser)().device===ht.CurrentClientDevice.Android,is=document.createElement("video"),ux='video/mp4; codecs="avc1.42000a,mp4a.40.2"',lx='video/mp4; codecs="hev1.1.6.L93.B0"',_f='video/webm; codecs="vp09.00.10.08"',Nf='video/webm; codecs="av01.0.00M.08"',cx='audio/mp4; codecs="mp4a.40.2"',dx='audio/webm; codecs="opus"',Wt={mms:za(),mse:kf(),hls:!!(is.canPlayType?.("application/x-mpegurl")||is.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},De={mp4:!!is.canPlayType?.("video/mp4"),webm:!!is.canPlayType?.("video/webm"),cmaf:!0},Ze={h264:!!pt()?.isTypeSupported?.(ux),h265:!!pt()?.isTypeSupported?.(lx),vp9:!!pt()?.isTypeSupported?.(_f),av1:!!pt()?.isTypeSupported?.(Nf),aac:!!pt()?.isTypeSupported?.(cx),opus:!!pt()?.isTypeSupported?.(dx)},Oi=(Ze.h264||Ze.h265)&&Ze.aac,Qt,px=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:_f}})]);Qt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{px()}catch(i){console.error(i)}var yr=Wt.hls&&De.mp4,Ff=()=>Object.keys(Ze).filter(i=>Ze[i]),qf=(i,e=!1,t=!1)=>{let r=Wt.mse||Wt.mms&&t;return i.filter(a=>{switch(a){case"DASH_SEP":return r&&De.mp4&&Oi;case"DASH_WEBM":return r&&De.webm&&Ze.vp9&&Ze.opus;case"DASH_WEBM_AV1":return r&&De.webm&&Ze.av1&&Ze.opus;case"DASH_LIVE":return Wt.mse&&De.mp4&&Oi;case"DASH_LIVE_CMAF":return r&&De.mp4&&Oi&&De.cmaf;case"DASH_ONDEMAND":return r&&De.mp4&&Oi;case"HLS":case"HLS_ONDEMAND":return yr||e&&Wt.mse&&De.mp4&&Oi;case"HLS_LIVE":case"HLS_LIVE_CMAF":return yr;case"MPEG":return De.mp4;case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Wt.webrtc&&Wt.ws&&Ze.h264&&(De.mp4||De.webm);default:return(0,ht.assertNever)(a)}})},wt=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,ht.assertNever)(i)}return[e,t]},Uf=({webmCodec:i,androidPreferredFormat:e})=>{if(Vf)switch(e){case"mpeg":return["MPEG",...wt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...wt(i),"DASH_SEP","DASH_ONDEMAND","MPEG"];case"dash":return[...wt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return["DASH_SEP","DASH_ONDEMAND","MPEG",...wt(i),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...wt(i),"MPEG","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...wt(i),"DASH_ONDEMAND","HLS","HLS_ONDEMAND"];default:(0,ht.assertNever)(e)}return yr?[...wt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]:[...wt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]},Hf=({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;if(Vf)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,ht.assertNever)(i)}else yr?o=n:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Lo=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"];var ft=require("@vkontakte/videoplayer-shared"),jf=i=>new ft.Observable(e=>{let t=new ft.Subscription,r=i.desiredPlaybackState$.stateChangeStarted$.pipe((0,ft.map)(({from:u,to:c})=>`${u}-${c}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe((0,ft.map)(({type:u})=>u!==void 0)),n=new ft.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 Tr=null,as=null;function $o(){return Tr||(Tr=new(window.AudioContext||window.webkitAudioContext)),as||(as=new GainNode(Tr,{gain:1}),as.connect(Tr.destination)),Tr.resume().catch(),{audioCtx:Tr,gainNode:as}}var ss=require("@vkontakte/videoplayer-shared"),Bi=class{constructor(e,t,r){this.video$=e;this.volumeMultiplier=t;!r||!this.isSupported()||t===1||this.video$.subscribe(a=>this.listener(a))}isSupported(){let{browser:e}=(0,ss.getCurrentBrowser)();return e!==ss.CurrentClientBrowser.Safari&&"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}listener(e){if(!e)return;let{volumeMultiplier:t}=this,{audioCtx:r,gainNode:a}=$o();a.gain.value=t;try{new MediaElementAudioSourceNode(r,{mediaElement:e}).connect(a)}catch{}}destroy(){let{gainNode:e}=$o();e.gain.value=1}};var hx={chunkDuration:5e3,maxParallelRequests:5},Vi=class{constructor(e){this.current$=new S.ValueSubject({type:void 0});this.providerError$=new S.Subject;this.noAvailableProvidersError$=new S.Subject;this.providerOutput={position$:new S.ValueSubject(0),duration$:new S.ValueSubject(1/0),volume$:new S.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new S.ValueSubject(void 0),currentVideoSegmentLength$:new S.ValueSubject(0),currentAudioSegmentLength$:new S.ValueSubject(0),availableVideoTracks$:new S.ValueSubject([]),availableAudioTracks$:new S.ValueSubject([]),isAudioAvailable$:new S.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new S.ValueSubject(!1),autoVideoTrackLimits$:new S.ValueSubject(void 0),currentBuffer$:new S.ValueSubject(void 0),isBuffering$:new S.ValueSubject(!0),error$:new S.Subject,warning$:new S.Subject,willSeekEvent$:new S.Subject,seekedEvent$:new S.Subject,loopedEvent$:new S.Subject,endedEvent$:new S.Subject,firstBytesEvent$:new S.Subject,firstFrameEvent$:new S.Subject,canplay$:new S.Subject,isLive$:new S.ValueSubject(void 0),isLowLatency$:new S.ValueSubject(!1),canChangePlaybackSpeed$:new S.ValueSubject(!0),liveTime$:new S.ValueSubject(void 0),liveBufferTime$:new S.ValueSubject(void 0),availableTextTracks$:new S.ValueSubject([]),currentTextTrack$:new S.ValueSubject(void 0),hostname$:new S.ValueSubject(void 0),httpConnectionType$:new S.ValueSubject(void 0),httpConnectionReused$:new S.ValueSubject(void 0),inPiP$:new S.ValueSubject(!1),inFullscreen$:new S.ValueSubject(!1),element$:new S.ValueSubject(void 0),elementVisible$:new S.ValueSubject(!0),availableSources$:new S.ValueSubject(void 0),is3DVideo$:new S.ValueSubject(!1)};this.subscription=new S.Subscription;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=qf([...Hf(this.params.tuning),...Uf(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>(0,S.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 Mi(s);let n=[...Lo(!0),...Lo(!1)];this.chromecastFormatsIterator=new Mi(n.filter(o=>(0,S.isNonNullable)(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new Bi(this.providerOutput.element$,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,S.isNullable)(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:S.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,S.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":{let o=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,S.assertNonNullable)(o),new wi({...n,source:o,sourceHls:l})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,S.assertNonNullable)(o),new Ai({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,S.assertNonNullable)(o),yr||!this.params.tuning.useHlsJs?new $i({...n,source:o}):new Ri({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,S.assertNonNullable)(o),new Li({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,S.assertNonNullable)(o),new Ci({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,S.assertNonNullable)(o),new Lh({...n,source:o,config:{...hx,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,S.assertNonNullable)(o),new Di({container:r,source:o,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH_LIVE_WEBM":throw new Error("DASH_LIVE_WEBM is no longer supported");default:return(0,S.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,S.assertNonNullable)(o),new Gr({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,S.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,S.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,S.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,Gf.default)(Object.entries(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new S.Subscription,t=!1,r=0;return e.add((0,S.merge)(this.providerOutput.error$,jf({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,S.map)(a=>({id:`ProviderHangup:${a}`,category:S.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,S.filter)(({to:s})=>s==="playing"),(0,S.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===S.ErrorCategory.NETWORK,o=a.category===S.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 O=require("@vkontakte/videoplayer-shared");var fx=5e3,Yf="one_video_throughput",Wf="one_video_rtt",_i=window.navigator.connection,Qf=()=>{let i=_i?.downlink;if((0,O.isNonNullable)(i)&&i!==10)return i*1e3},zf=()=>{let i=_i?.rtt;if((0,O.isNonNullable)(i)&&i!==3e3)return i},Kf=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},Co=class i{constructor(e){this.subscription=new O.Subscription;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=i.load(Yf)||(e.useBrowserEstimation?Qf():void 0)||fx,r=i.load(Wf)??(e.useBrowserEstimation?zf():void 0)??0;if(this.throughput$=new O.ValueSubject(t),this.rtt$=new O.ValueSubject(r),this.rttAdjustedThroughput$=new O.ValueSubject(Kf(t,r,e.rttPenaltyRequestSize)),this.throughput=Ht.getSmoothedValue(t,-1,e),this.rtt=Ht.getSmoothedValue(r,1,e),e.useBrowserEstimation){let a=()=>{let n=Qf();n&&this.throughput.next(n);let o=zf();(0,O.isNonNullable)(o)&&this.rtt.next(o)};_i&&"onchange"in _i&&this.subscription.add((0,O.fromEvent)(_i,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{O.safeStorage.set(Yf,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{O.safeStorage.set(Wf,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,O.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,O.map)(({throughput:a,rtt:s})=>Kf(a,s,e.rttPenaltyRequestSize)),(0,O.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,O.now)(),a=new O.Subscription;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add((0,O.fromEvent)(e,"progress").pipe((0,O.once)()).subscribe(s=>{t=s.loaded,r=(0,O.now)()}));break;case 1:case 0:a.add((0,O.fromEvent)(e,"loadstart").subscribe(()=>{t=0,r=(0,O.now)()}));break}a.add((0,O.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,O.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,O.now)(),n=0,o=(0,O.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,O.now)()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){if((0,O.now)()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=d.byteLength;else{let h=o-s;h&&this.addRawSpeed(n,h,1,t),n=d.byteLength,s=(0,O.now)()}o=(0,O.now)()}else a+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,O.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,O.now)()-o,this.concurrentDownloads.size),n=0,o=(0,O.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=O.safeStorage.get(e);if((0,O.isNonNullable)(t))return parseInt(t,10)??void 0}},Jf=Co;var Ni=require("@vkontakte/videoplayer-shared"),Xf={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:10}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:Ni.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Ni.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:3e4,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,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,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:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,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},Zf=i=>({...(0,Ni.fillWithDefault)(i,Xf),configName:[...i.configName??[],...Xf.configName]});var p=require("@vkontakte/videoplayer-shared");var mt=require("@vkontakte/videoplayer-shared"),Do=({seekState:i,position$:e})=>(0,mt.merge)(i.stateChangeEnded$.pipe((0,mt.map)(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),(0,mt.filter)(mt.isNonNullable)),e.pipe((0,mt.filter)(()=>i.getState().state==="none")));var em=require("@vkontakte/videoplayer-shared"),tm=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return(0,em.assertNonNullable)(e,`Wrong container or containerId {${i.container}}`),e};var ns=require("@vkontakte/videoplayer-shared"),rm=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe((0,ns.filter)(a=>a.length>0),(0,ns.once)()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t?.getValue().find(r))&&e.startTransitionTo(i)};var Fi=class{constructor(e={configName:[]}){this.subscription=new p.Subscription;this.logger=new p.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new p.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),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 p.ValueSubject("stopped"),position$:new p.ValueSubject(0),duration$:new p.ValueSubject(1/0),muted$:new p.ValueSubject(!1),volume$:new p.ValueSubject(1),availableQualities$:new p.ValueSubject([]),availableQualitiesFps$:new p.ValueSubject({}),availableAudioTracks$:new p.ValueSubject([]),isAudioAvailable$:new p.ValueSubject(!0),currentQuality$:new p.ValueSubject(void 0),isAutoQualityEnabled$:new p.ValueSubject(!0),autoQualityLimitingAvailable$:new p.ValueSubject(!1),autoQualityLimits$:new p.ValueSubject({}),currentPlaybackRate$:new p.ValueSubject(1),currentBuffer$:new p.ValueSubject({start:0,end:0}),isBuffering$:new p.ValueSubject(!0),isStalled$:new p.ValueSubject(!1),isEnded$:new p.ValueSubject(!1),isLooped$:new p.ValueSubject(!1),isLive$:new p.ValueSubject(void 0),canChangePlaybackSpeed$:new p.ValueSubject(void 0),atLiveEdge$:new p.ValueSubject(void 0),atLiveDurationEdge$:new p.ValueSubject(void 0),liveTime$:new p.ValueSubject(void 0),liveBufferTime$:new p.ValueSubject(void 0),currentFormat$:new p.ValueSubject(void 0),availableTextTracks$:new p.ValueSubject([]),currentTextTrack$:new p.ValueSubject(void 0),throughputEstimation$:new p.ValueSubject(void 0),rttEstimation$:new p.ValueSubject(void 0),videoBitrate$:new p.ValueSubject(void 0),hostname$:new p.ValueSubject(void 0),httpConnectionType$:new p.ValueSubject(void 0),httpConnectionReused$:new p.ValueSubject(void 0),surface$:new p.ValueSubject("none"),chromecastState$:new p.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new p.ValueSubject(void 0),intrinsicVideoSize$:new p.ValueSubject(void 0),availableSources$:new p.ValueSubject(void 0),is3DVideo$:new p.ValueSubject(!1),currentVideoSegmentLength$:new p.ValueSubject(0),currentAudioSegmentLength$:new p.ValueSubject(0)};this.events={inited$:new p.Subject,ready$:new p.Subject,started$:new p.Subject,playing$:new p.Subject,paused$:new p.Subject,stopped$:new p.Subject,willStart$:new p.Subject,willResume$:new p.Subject,willPause$:new p.Subject,willStop$:new p.Subject,willDestruct$:new p.Subject,watchCoverageRecord$:new p.Subject,watchCoverageLive$:new p.Subject,managedError$:new p.Subject,fatalError$:new p.Subject,ended$:new p.Subject,looped$:new p.Subject,seeked$:new p.Subject,willSeek$:new p.Subject,firstBytes$:new p.Subject,firstFrame$:new p.Subject,canplay$:new p.Subject,log$:new p.Subject};this.experimental={element$:new p.ValueSubject(void 0),tuningConfigName$:new p.ValueSubject([]),enableDebugTelemetry$:new p.ValueSubject(!1),dumpTelemetry:kh};if(this.initLogs(),this.tuning=Zf(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new zi({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Jf(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,(f,h)=>{let b=typeof h;return["number","string","boolean"].includes(b)?h:h===null?null:`<${b}>`})),u=`Player.${String(r)}`,c=`Exception calling ${u} (${l.join(", ")})`;throw this.events.fatalError$.next({id:u,category:p.ErrorCategory.WTF,message:c,thrown:o}),o}}}})}initVideo(e){return this.config=e,this.domContainer=tm(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Vi({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&&!Jr()?(0,p.fromEvent)(document,"visibilitychange").pipe((0,p.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}setQuality(e){(0,p.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,p.filter)(r=>r.length>0),(0,p.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,p.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 rm(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,p.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return(0,p.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,p.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,p.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,p.filter)(({from:e})=>e==="stopped"),(0,p.once)()).subscribe(()=>{this.initedAt=(0,p.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:p.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,p.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,p.map)(n=>n.destination),(0,p.filterChanged)()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe((0,p.map)(n=>n.map(({quality:o})=>o).sort((o,l)=>(0,p.isInvariantQuality)(o)?1:(0,p.isInvariantQuality)(l)?-1:(0,p.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.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,p.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,p.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,p.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,p.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,p.combine)({hasLiveOffsetByPaused:(0,p.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,p.map)(n=>n.to),(0,p.filterChanged)(),(0,p.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,p.combine)({atLiveEdge:(0,p.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Do({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,p.map)(({isLive:n,position:o,isLowLatency:l})=>{let u=this.getActiveLiveDelay(l);return n&&Math.abs(o)<u/1e3}),(0,p.filterChanged)(),(0,p.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,p.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,p.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,p.map)(({isLive:n,position:o,duration:l})=>n&&(Math.abs(l)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,p.filterChanged)(),(0,p.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,p.map)(n=>n.muted),(0,p.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,p.map)(n=>n.volume),(0,p.filterChanged)()).subscribe(this.info.volume$)).add(Do({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,p.merge)(e.providerOutput.endedEvent$.pipe((0,p.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,p.mapTo)(!1))).pipe((0,p.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.noAvailableProvidersError$.pipe((0,p.map)(n=>({id:n?`No${n}`:"NoProviders",category:p.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,p.once)(),(0,p.map)(n=>n??(0,p.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe((0,p.once)(),(0,p.map)(()=>(0,p.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,p.once)(),(0,p.map)(()=>(0,p.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 p.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new p.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,p.filter)(({to:n})=>n==="playing"),(0,p.once)()).subscribe(()=>r.next(!1)));let a=0,s=(0,p.merge)(e.providerOutput.isBuffering$,t,r).pipe((0,p.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),(0,p.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,p.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,p.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,p.map)(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new p.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,p.filterChanged)((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,p.filter)(r=>r.length>0),(0,p.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,p.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,p.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,p.assertNonNullable)(this.providerContainer),(0,p.assertNonNullable)(e),Ph(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>xh(t)),this.providerContainer.current$.subscribe(({type:t})=>Wr("provider",t)),e.duration$.subscribe(t=>Wr("duration",t)),e.availableVideoTracks$.pipe((0,p.filter)(t=>!!t.length),(0,p.once)()).subscribe(t=>Wr("tracks",t)),this.events.fatalError$.subscribe(new pe("fatalError")),this.events.managedError$.subscribe(new pe("managedError")),e.position$.subscribe(new pe("position")),e.currentVideoTrack$.pipe((0,p.map)(t=>t?.quality)).subscribe(new pe("quality")),this.info.currentBuffer$.subscribe(new pe("buffer")),e.isBuffering$.subscribe(new pe("isBuffering"))].forEach(t=>this.subscription.add(t)),Wr("codecs",Ff())}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:p.ErrorCategory.DOM,message:String(a)})})};this.subscription.add((0,p.merge)((0,p.fromEvent)(document,"visibilitychange"),(0,p.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 et=require("@vkontakte/videoplayer-shared"),mx=`@vkontakte/videoplayer-core@${hs}`;
|