@vkontakte/videoplayer-core 2.0.117-dev.d9cc3d97.0 → 2.0.118-dev.d798494f.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 +18 -19
- package/es2015.esm.js +18 -19
- package/es2018.cjs.js +22 -23
- package/es2018.esm.js +21 -22
- package/esnext.cjs.js +15 -16
- package/esnext.esm.js +10 -11
- package/evergreen.esm.js +16 -17
- package/package.json +2 -2
- package/types/player/Player.d.ts +0 -1
- package/types/player/types.d.ts +1 -2
- package/types/providers/DashProvider/lib/utils.d.ts +3 -1
- package/types/providers/HlsLiveProvider/index.d.ts +0 -2
- package/types/providers/HlsProvider/manifestDataExtractor.d.ts +1 -1
- package/types/providers/types.d.ts +0 -1
- package/types/utils/tuningConfig.d.ts +0 -2
- package/types/providers/HlsLiveProvider/LiveTextManager.d.ts +0 -42
package/esnext.cjs.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
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.118-dev.d798494f.0
|
|
3
|
+
* Wed, 20 Nov 2024 09:07:27 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-118/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var Gf=Object.create;var va=Object.defineProperty;var Qf=Object.getOwnPropertyDescriptor;var Wf=Object.getOwnPropertyNames;var Yf=Object.getPrototypeOf,zf=Object.prototype.hasOwnProperty;var b=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Kf=(r,e)=>{for(var t in e)va(r,t,{get:e[t],enumerable:!0})},ou=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Wf(e))!zf.call(r,a)&&a!==t&&va(r,a,{get:()=>e[a],enumerable:!(i=Qf(e,a))||i.enumerable});return r};var Oe=(r,e,t)=>(t=r!=null?Gf(Yf(r)):{},ou(e||!r||!r.__esModule?va(t,"default",{value:r,enumerable:!0}):t,r)),Xf=r=>ou(va({},"__esModule",{value:!0}),r);var Le=b((hP,lu)=>{"use strict";lu.exports=function(r){try{return!!r()}catch{return!0}}});var Gi=b((mP,cu)=>{"use strict";var Zf=Le();cu.exports=!Zf(function(){var r=function(){}.bind();return typeof r!="function"||r.hasOwnProperty("prototype")})});var Te=b((fP,hu)=>{"use strict";var du=Gi(),pu=Function.prototype,Ms=pu.call,eb=du&&pu.bind.bind(Ms,Ms);hu.exports=du?eb:function(r){return function(){return Ms.apply(r,arguments)}}});var pi=b((bP,fu)=>{"use strict";var mu=Te(),tb=mu({}.toString),ib=mu("".slice);fu.exports=function(r){return ib(tb(r),8,-1)}});var gu=b((gP,bu)=>{"use strict";var rb=Te(),ab=Le(),sb=pi(),Ds=Object,nb=rb("".split);bu.exports=ab(function(){return!Ds("z").propertyIsEnumerable(0)})?function(r){return sb(r)==="String"?nb(r,""):Ds(r)}:Ds});var hi=b((SP,Su)=>{"use strict";Su.exports=function(r){return r==null}});var Qi=b((vP,vu)=>{"use strict";var ob=hi(),ub=TypeError;vu.exports=function(r){if(ob(r))throw new ub("Can't call method on "+r);return r}});var mi=b((yP,yu)=>{"use strict";var lb=gu(),cb=Qi();yu.exports=function(r){return lb(cb(r))}});var Cs=b((TP,Tu)=>{"use strict";Tu.exports=function(){}});var Qt=b((IP,Iu)=>{"use strict";Iu.exports={}});var se=b((Vs,Eu)=>{"use strict";var Wi=function(r){return r&&r.Math===Math&&r};Eu.exports=Wi(typeof globalThis=="object"&&globalThis)||Wi(typeof window=="object"&&window)||Wi(typeof self=="object"&&self)||Wi(typeof global=="object"&&global)||Wi(typeof Vs=="object"&&Vs)||function(){return this}()||Function("return this")()});var ae=b((EP,xu)=>{"use strict";var Bs=typeof document=="object"&&document.all;xu.exports=typeof Bs>"u"&&Bs!==void 0?function(r){return typeof r=="function"||r===Bs}:function(r){return typeof r=="function"}});var wu=b((xP,ku)=>{"use strict";var db=se(),pb=ae(),Pu=db.WeakMap;ku.exports=pb(Pu)&&/native code/.test(String(Pu))});var _e=b((PP,Au)=>{"use strict";var hb=ae();Au.exports=function(r){return typeof r=="object"?r!==null:hb(r)}});var Ne=b((kP,Ru)=>{"use strict";var mb=Le();Ru.exports=!mb(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ea=b((wP,Lu)=>{"use strict";var fb=se(),$u=_e(),Os=fb.document,bb=$u(Os)&&$u(Os.createElement);Lu.exports=function(r){return bb?Os.createElement(r):{}}});var _s=b((AP,Mu)=>{"use strict";var gb=Ne(),Sb=Le(),vb=Ea();Mu.exports=!gb&&!Sb(function(){return Object.defineProperty(vb("div"),"a",{get:function(){return 7}}).a!==7})});var Ns=b((RP,Du)=>{"use strict";var yb=Ne(),Tb=Le();Du.exports=yb&&Tb(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var nt=b(($P,Cu)=>{"use strict";var Ib=_e(),Eb=String,xb=TypeError;Cu.exports=function(r){if(Ib(r))return r;throw new xb(Eb(r)+" is not an object")}});var Me=b((LP,Vu)=>{"use strict";var Pb=Gi(),xa=Function.prototype.call;Vu.exports=Pb?xa.bind(xa):function(){return xa.apply(xa,arguments)}});var Pa=b((MP,Bu)=>{"use strict";Bu.exports={}});var gt=b((DP,_u)=>{"use strict";var Fs=Pa(),qs=se(),kb=ae(),Ou=function(r){return kb(r)?r:void 0};_u.exports=function(r,e){return arguments.length<2?Ou(Fs[r])||Ou(qs[r]):Fs[r]&&Fs[r][e]||qs[r]&&qs[r][e]}});var Yi=b((CP,Nu)=>{"use strict";var wb=Te();Nu.exports=wb({}.isPrototypeOf)});var fi=b((VP,Uu)=>{"use strict";var Ab=se(),Fu=Ab.navigator,qu=Fu&&Fu.userAgent;Uu.exports=qu?String(qu):""});var Hs=b((BP,Yu)=>{"use strict";var Wu=se(),Us=fi(),Hu=Wu.process,ju=Wu.Deno,Gu=Hu&&Hu.versions||ju&&ju.version,Qu=Gu&&Gu.v8,ze,ka;Qu&&(ze=Qu.split("."),ka=ze[0]>0&&ze[0]<4?1:+(ze[0]+ze[1]));!ka&&Us&&(ze=Us.match(/Edge\/(\d+)/),(!ze||ze[1]>=74)&&(ze=Us.match(/Chrome\/(\d+)/),ze&&(ka=+ze[1])));Yu.exports=ka});var js=b((OP,Ku)=>{"use strict";var zu=Hs(),Rb=Le(),$b=se(),Lb=$b.String;Ku.exports=!!Object.getOwnPropertySymbols&&!Rb(function(){var r=Symbol("symbol detection");return!Lb(r)||!(Object(r)instanceof Symbol)||!Symbol.sham&&zu&&zu<41})});var Gs=b((_P,Xu)=>{"use strict";var Mb=js();Xu.exports=Mb&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Qs=b((NP,Ju)=>{"use strict";var Db=gt(),Cb=ae(),Vb=Yi(),Bb=Gs(),Ob=Object;Ju.exports=Bb?function(r){return typeof r=="symbol"}:function(r){var e=Db("Symbol");return Cb(e)&&Vb(e.prototype,Ob(r))}});var zi=b((FP,Zu)=>{"use strict";var _b=String;Zu.exports=function(r){try{return _b(r)}catch{return"Object"}}});var St=b((qP,el)=>{"use strict";var Nb=ae(),Fb=zi(),qb=TypeError;el.exports=function(r){if(Nb(r))return r;throw new qb(Fb(r)+" is not a function")}});var Ki=b((UP,tl)=>{"use strict";var Ub=St(),Hb=hi();tl.exports=function(r,e){var t=r[e];return Hb(t)?void 0:Ub(t)}});var rl=b((HP,il)=>{"use strict";var Ws=Me(),Ys=ae(),zs=_e(),jb=TypeError;il.exports=function(r,e){var t,i;if(e==="string"&&Ys(t=r.toString)&&!zs(i=Ws(t,r))||Ys(t=r.valueOf)&&!zs(i=Ws(t,r))||e!=="string"&&Ys(t=r.toString)&&!zs(i=Ws(t,r)))return i;throw new jb("Can't convert object to primitive value")}});var Ke=b((jP,al)=>{"use strict";al.exports=!0});var ol=b((GP,nl)=>{"use strict";var sl=se(),Gb=Object.defineProperty;nl.exports=function(r,e){try{Gb(sl,r,{value:e,configurable:!0,writable:!0})}catch{sl[r]=e}return e}});var Xi=b((QP,cl)=>{"use strict";var Qb=Ke(),Wb=se(),Yb=ol(),ul="__core-js_shared__",ll=cl.exports=Wb[ul]||Yb(ul,{});(ll.versions||(ll.versions=[])).push({version:"3.38.0",mode:Qb?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Ks=b((WP,pl)=>{"use strict";var dl=Xi();pl.exports=function(r,e){return dl[r]||(dl[r]=e||{})}});var Ji=b((YP,hl)=>{"use strict";var zb=Qi(),Kb=Object;hl.exports=function(r){return Kb(zb(r))}});var Xe=b((zP,ml)=>{"use strict";var Xb=Te(),Jb=Ji(),Zb=Xb({}.hasOwnProperty);ml.exports=Object.hasOwn||function(e,t){return Zb(Jb(e),t)}});var Xs=b((KP,fl)=>{"use strict";var eg=Te(),tg=0,ig=Math.random(),rg=eg(1 .toString);fl.exports=function(r){return"Symbol("+(r===void 0?"":r)+")_"+rg(++tg+ig,36)}});var ge=b((XP,gl)=>{"use strict";var ag=se(),sg=Ks(),bl=Xe(),ng=Xs(),og=js(),ug=Gs(),bi=ag.Symbol,Js=sg("wks"),lg=ug?bi.for||bi:bi&&bi.withoutSetter||ng;gl.exports=function(r){return bl(Js,r)||(Js[r]=og&&bl(bi,r)?bi[r]:lg("Symbol."+r)),Js[r]}});var Tl=b((JP,yl)=>{"use strict";var cg=Me(),Sl=_e(),vl=Qs(),dg=Ki(),pg=rl(),hg=ge(),mg=TypeError,fg=hg("toPrimitive");yl.exports=function(r,e){if(!Sl(r)||vl(r))return r;var t=dg(r,fg),i;if(t){if(e===void 0&&(e="default"),i=cg(t,r,e),!Sl(i)||vl(i))return i;throw new mg("Can't convert object to primitive value")}return e===void 0&&(e="number"),pg(r,e)}});var Zs=b((ZP,Il)=>{"use strict";var bg=Tl(),gg=Qs();Il.exports=function(r){var e=bg(r,"string");return gg(e)?e:e+""}});var Wt=b(xl=>{"use strict";var Sg=Ne(),vg=_s(),yg=Ns(),wa=nt(),El=Zs(),Tg=TypeError,en=Object.defineProperty,Ig=Object.getOwnPropertyDescriptor,tn="enumerable",rn="configurable",an="writable";xl.f=Sg?yg?function(e,t,i){if(wa(e),t=El(t),wa(i),typeof e=="function"&&t==="prototype"&&"value"in i&&an in i&&!i[an]){var a=Ig(e,t);a&&a[an]&&(e[t]=i.value,i={configurable:rn in i?i[rn]:a[rn],enumerable:tn in i?i[tn]:a[tn],writable:!1})}return en(e,t,i)}:en:function(e,t,i){if(wa(e),t=El(t),wa(i),vg)try{return en(e,t,i)}catch{}if("get"in i||"set"in i)throw new Tg("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Zi=b((tk,Pl)=>{"use strict";Pl.exports=function(r,e){return{enumerable:!(r&1),configurable:!(r&2),writable:!(r&4),value:e}}});var gi=b((ik,kl)=>{"use strict";var Eg=Ne(),xg=Wt(),Pg=Zi();kl.exports=Eg?function(r,e,t){return xg.f(r,e,Pg(1,t))}:function(r,e,t){return r[e]=t,r}});var Aa=b((rk,Al)=>{"use strict";var kg=Ks(),wg=Xs(),wl=kg("keys");Al.exports=function(r){return wl[r]||(wl[r]=wg(r))}});var Ra=b((ak,Rl)=>{"use strict";Rl.exports={}});var un=b((sk,Ml)=>{"use strict";var Ag=wu(),Ll=se(),Rg=_e(),$g=gi(),sn=Xe(),nn=Xi(),Lg=Aa(),Mg=Ra(),$l="Object already initialized",on=Ll.TypeError,Dg=Ll.WeakMap,$a,er,La,Cg=function(r){return La(r)?er(r):$a(r,{})},Vg=function(r){return function(e){var t;if(!Rg(e)||(t=er(e)).type!==r)throw new on("Incompatible receiver, "+r+" required");return t}};Ag||nn.state?(Je=nn.state||(nn.state=new Dg),Je.get=Je.get,Je.has=Je.has,Je.set=Je.set,$a=function(r,e){if(Je.has(r))throw new on($l);return e.facade=r,Je.set(r,e),e},er=function(r){return Je.get(r)||{}},La=function(r){return Je.has(r)}):(Yt=Lg("state"),Mg[Yt]=!0,$a=function(r,e){if(sn(r,Yt))throw new on($l);return e.facade=r,$g(r,Yt,e),e},er=function(r){return sn(r,Yt)?r[Yt]:{}},La=function(r){return sn(r,Yt)});var Je,Yt;Ml.exports={set:$a,get:er,has:La,enforce:Cg,getterFor:Vg}});var ln=b((nk,Bl)=>{"use strict";var Bg=Gi(),Vl=Function.prototype,Dl=Vl.apply,Cl=Vl.call;Bl.exports=typeof Reflect=="object"&&Reflect.apply||(Bg?Cl.bind(Dl):function(){return Cl.apply(Dl,arguments)})});var cn=b((ok,Ol)=>{"use strict";var Og=pi(),_g=Te();Ol.exports=function(r){if(Og(r)==="Function")return _g(r)}});var ql=b(Fl=>{"use strict";var _l={}.propertyIsEnumerable,Nl=Object.getOwnPropertyDescriptor,Ng=Nl&&!_l.call({1:2},1);Fl.f=Ng?function(e){var t=Nl(this,e);return!!t&&t.enumerable}:_l});var jl=b(Hl=>{"use strict";var Fg=Ne(),qg=Me(),Ug=ql(),Hg=Zi(),jg=mi(),Gg=Zs(),Qg=Xe(),Wg=_s(),Ul=Object.getOwnPropertyDescriptor;Hl.f=Fg?Ul:function(e,t){if(e=jg(e),t=Gg(t),Wg)try{return Ul(e,t)}catch{}if(Qg(e,t))return Hg(!qg(Ug.f,e,t),e[t])}});var dn=b((ck,Gl)=>{"use strict";var Yg=Le(),zg=ae(),Kg=/#|\.prototype\./,tr=function(r,e){var t=Jg[Xg(r)];return t===eS?!0:t===Zg?!1:zg(e)?Yg(e):!!e},Xg=tr.normalize=function(r){return String(r).replace(Kg,".").toLowerCase()},Jg=tr.data={},Zg=tr.NATIVE="N",eS=tr.POLYFILL="P";Gl.exports=tr});var ir=b((dk,Wl)=>{"use strict";var Ql=cn(),tS=St(),iS=Gi(),rS=Ql(Ql.bind);Wl.exports=function(r,e){return tS(r),e===void 0?r:iS?rS(r,e):function(){return r.apply(e,arguments)}}});var Fe=b((pk,zl)=>{"use strict";var rr=se(),aS=ln(),sS=cn(),nS=ae(),oS=jl().f,uS=dn(),Si=Pa(),lS=ir(),vi=gi(),Yl=Xe();Xi();var cS=function(r){var e=function(t,i,a){if(this instanceof e){switch(arguments.length){case 0:return new r;case 1:return new r(t);case 2:return new r(t,i)}return new r(t,i,a)}return aS(r,this,arguments)};return e.prototype=r.prototype,e};zl.exports=function(r,e){var t=r.target,i=r.global,a=r.stat,s=r.proto,n=i?rr:a?rr[t]:rr[t]&&rr[t].prototype,o=i?Si:Si[t]||vi(Si,t,{})[t],u=o.prototype,l,c,d,p,m,f,g,y,I;for(p in e)l=uS(i?p:t+(a?".":"#")+p,r.forced),c=!l&&n&&Yl(n,p),f=o[p],c&&(r.dontCallGetSet?(I=oS(n,p),g=I&&I.value):g=n[p]),m=c&&g?g:e[p],!(!l&&!s&&typeof f==typeof m)&&(r.bind&&c?y=lS(m,rr):r.wrap&&c?y=cS(m):s&&nS(m)?y=sS(m):y=m,(r.sham||m&&m.sham||f&&f.sham)&&vi(y,"sham",!0),vi(o,p,y),s&&(d=t+"Prototype",Yl(Si,d)||vi(Si,d,{}),vi(Si[d],p,m),r.real&&u&&(l||!u[p])&&vi(u,p,m)))}});var Jl=b((hk,Xl)=>{"use strict";var pn=Ne(),dS=Xe(),Kl=Function.prototype,pS=pn&&Object.getOwnPropertyDescriptor,hn=dS(Kl,"name"),hS=hn&&function(){}.name==="something",mS=hn&&(!pn||pn&&pS(Kl,"name").configurable);Xl.exports={EXISTS:hn,PROPER:hS,CONFIGURABLE:mS}});var ec=b((mk,Zl)=>{"use strict";var fS=Math.ceil,bS=Math.floor;Zl.exports=Math.trunc||function(e){var t=+e;return(t>0?bS:fS)(t)}});var Ma=b((fk,tc)=>{"use strict";var gS=ec();tc.exports=function(r){var e=+r;return e!==e||e===0?0:gS(e)}});var rc=b((bk,ic)=>{"use strict";var SS=Ma(),vS=Math.max,yS=Math.min;ic.exports=function(r,e){var t=SS(r);return t<0?vS(t+e,0):yS(t,e)}});var sc=b((gk,ac)=>{"use strict";var TS=Ma(),IS=Math.min;ac.exports=function(r){var e=TS(r);return e>0?IS(e,9007199254740991):0}});var Da=b((Sk,nc)=>{"use strict";var ES=sc();nc.exports=function(r){return ES(r.length)}});var lc=b((vk,uc)=>{"use strict";var xS=mi(),PS=rc(),kS=Da(),oc=function(r){return function(e,t,i){var a=xS(e),s=kS(a);if(s===0)return!r&&-1;var n=PS(i,s),o;if(r&&t!==t){for(;s>n;)if(o=a[n++],o!==o)return!0}else for(;s>n;n++)if((r||n in a)&&a[n]===t)return r||n||0;return!r&&-1}};uc.exports={includes:oc(!0),indexOf:oc(!1)}});var pc=b((yk,dc)=>{"use strict";var wS=Te(),mn=Xe(),AS=mi(),RS=lc().indexOf,$S=Ra(),cc=wS([].push);dc.exports=function(r,e){var t=AS(r),i=0,a=[],s;for(s in t)!mn($S,s)&&mn(t,s)&&cc(a,s);for(;e.length>i;)mn(t,s=e[i++])&&(~RS(a,s)||cc(a,s));return a}});var fn=b((Tk,hc)=>{"use strict";hc.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var fc=b((Ik,mc)=>{"use strict";var LS=pc(),MS=fn();mc.exports=Object.keys||function(e){return LS(e,MS)}});var gc=b(bc=>{"use strict";var DS=Ne(),CS=Ns(),VS=Wt(),BS=nt(),OS=mi(),_S=fc();bc.f=DS&&!CS?Object.defineProperties:function(e,t){BS(e);for(var i=OS(t),a=_S(t),s=a.length,n=0,o;s>n;)VS.f(e,o=a[n++],i[o]);return e}});var bn=b((xk,Sc)=>{"use strict";var NS=gt();Sc.exports=NS("document","documentElement")});var yn=b((Pk,Pc)=>{"use strict";var FS=nt(),qS=gc(),vc=fn(),US=Ra(),HS=bn(),jS=Ea(),GS=Aa(),yc=">",Tc="<",Sn="prototype",vn="script",Ec=GS("IE_PROTO"),gn=function(){},xc=function(r){return Tc+vn+yc+r+Tc+"/"+vn+yc},Ic=function(r){r.write(xc("")),r.close();var e=r.parentWindow.Object;return r=null,e},QS=function(){var r=jS("iframe"),e="java"+vn+":",t;return r.style.display="none",HS.appendChild(r),r.src=String(e),t=r.contentWindow.document,t.open(),t.write(xc("document.F=Object")),t.close(),t.F},Ca,Va=function(){try{Ca=new ActiveXObject("htmlfile")}catch{}Va=typeof document<"u"?document.domain&&Ca?Ic(Ca):QS():Ic(Ca);for(var r=vc.length;r--;)delete Va[Sn][vc[r]];return Va()};US[Ec]=!0;Pc.exports=Object.create||function(e,t){var i;return e!==null?(gn[Sn]=FS(e),i=new gn,gn[Sn]=null,i[Ec]=e):i=Va(),t===void 0?i:qS.f(i,t)}});var wc=b((kk,kc)=>{"use strict";var WS=Le();kc.exports=!WS(function(){function r(){}return r.prototype.constructor=null,Object.getPrototypeOf(new r)!==r.prototype})});var In=b((wk,Rc)=>{"use strict";var YS=Xe(),zS=ae(),KS=Ji(),XS=Aa(),JS=wc(),Ac=XS("IE_PROTO"),Tn=Object,ZS=Tn.prototype;Rc.exports=JS?Tn.getPrototypeOf:function(r){var e=KS(r);if(YS(e,Ac))return e[Ac];var t=e.constructor;return zS(t)&&e instanceof t?t.prototype:e instanceof Tn?ZS:null}});var yi=b((Ak,$c)=>{"use strict";var ev=gi();$c.exports=function(r,e,t,i){return i&&i.enumerable?r[e]=t:ev(r,e,t),r}});var kn=b((Rk,Dc)=>{"use strict";var tv=Le(),iv=ae(),rv=_e(),av=yn(),Lc=In(),sv=yi(),nv=ge(),ov=Ke(),Pn=nv("iterator"),Mc=!1,vt,En,xn;[].keys&&(xn=[].keys(),"next"in xn?(En=Lc(Lc(xn)),En!==Object.prototype&&(vt=En)):Mc=!0);var uv=!rv(vt)||tv(function(){var r={};return vt[Pn].call(r)!==r});uv?vt={}:ov&&(vt=av(vt));iv(vt[Pn])||sv(vt,Pn,function(){return this});Dc.exports={IteratorPrototype:vt,BUGGY_SAFARI_ITERATORS:Mc}});var Ba=b(($k,Vc)=>{"use strict";var lv=ge(),cv=lv("toStringTag"),Cc={};Cc[cv]="z";Vc.exports=String(Cc)==="[object z]"});var ar=b((Lk,Bc)=>{"use strict";var dv=Ba(),pv=ae(),Oa=pi(),hv=ge(),mv=hv("toStringTag"),fv=Object,bv=Oa(function(){return arguments}())==="Arguments",gv=function(r,e){try{return r[e]}catch{}};Bc.exports=dv?Oa:function(r){var e,t,i;return r===void 0?"Undefined":r===null?"Null":typeof(t=gv(e=fv(r),mv))=="string"?t:bv?Oa(e):(i=Oa(e))==="Object"&&pv(e.callee)?"Arguments":i}});var _c=b((Mk,Oc)=>{"use strict";var Sv=Ba(),vv=ar();Oc.exports=Sv?{}.toString:function(){return"[object "+vv(this)+"]"}});var sr=b((Dk,Fc)=>{"use strict";var yv=Ba(),Tv=Wt().f,Iv=gi(),Ev=Xe(),xv=_c(),Pv=ge(),Nc=Pv("toStringTag");Fc.exports=function(r,e,t,i){var a=t?r:r&&r.prototype;a&&(Ev(a,Nc)||Tv(a,Nc,{configurable:!0,value:e}),i&&!yv&&Iv(a,"toString",xv))}});var Uc=b((Ck,qc)=>{"use strict";var kv=kn().IteratorPrototype,wv=yn(),Av=Zi(),Rv=sr(),$v=Qt(),Lv=function(){return this};qc.exports=function(r,e,t,i){var a=e+" Iterator";return r.prototype=wv(kv,{next:Av(+!i,t)}),Rv(r,a,!1,!0),$v[a]=Lv,r}});var jc=b((Vk,Hc)=>{"use strict";var Mv=Te(),Dv=St();Hc.exports=function(r,e,t){try{return Mv(Dv(Object.getOwnPropertyDescriptor(r,e)[t]))}catch{}}});var Qc=b((Bk,Gc)=>{"use strict";var Cv=_e();Gc.exports=function(r){return Cv(r)||r===null}});var Yc=b((Ok,Wc)=>{"use strict";var Vv=Qc(),Bv=String,Ov=TypeError;Wc.exports=function(r){if(Vv(r))return r;throw new Ov("Can't set "+Bv(r)+" as a prototype")}});var wn=b((_k,zc)=>{"use strict";var _v=jc(),Nv=_e(),Fv=Qi(),qv=Yc();zc.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var r=!1,e={},t;try{t=_v(Object.prototype,"__proto__","set"),t(e,[]),r=e instanceof Array}catch{}return function(a,s){return Fv(a),qv(s),Nv(a)&&(r?t(a,s):a.__proto__=s),a}}():void 0)});var nd=b((Nk,sd)=>{"use strict";var Uv=Fe(),Hv=Me(),_a=Ke(),rd=Jl(),jv=ae(),Gv=Uc(),Kc=In(),Xc=wn(),Qv=sr(),Wv=gi(),An=yi(),Yv=ge(),Jc=Qt(),ad=kn(),zv=rd.PROPER,Kv=rd.CONFIGURABLE,Zc=ad.IteratorPrototype,Na=ad.BUGGY_SAFARI_ITERATORS,nr=Yv("iterator"),ed="keys",or="values",td="entries",id=function(){return this};sd.exports=function(r,e,t,i,a,s,n){Gv(t,e,i);var o=function(I){if(I===a&&p)return p;if(!Na&&I&&I in c)return c[I];switch(I){case ed:return function(){return new t(this,I)};case or:return function(){return new t(this,I)};case td:return function(){return new t(this,I)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=r.prototype,d=c[nr]||c["@@iterator"]||a&&c[a],p=!Na&&d||o(a),m=e==="Array"&&c.entries||d,f,g,y;if(m&&(f=Kc(m.call(new r)),f!==Object.prototype&&f.next&&(!_a&&Kc(f)!==Zc&&(Xc?Xc(f,Zc):jv(f[nr])||An(f,nr,id)),Qv(f,u,!0,!0),_a&&(Jc[u]=id))),zv&&a===or&&d&&d.name!==or&&(!_a&&Kv?Wv(c,"name",or):(l=!0,p=function(){return Hv(d,this)})),a)if(g={values:o(or),keys:s?p:o(ed),entries:o(td)},n)for(y in g)(Na||l||!(y in c))&&An(c,y,g[y]);else Uv({target:e,proto:!0,forced:Na||l},g);return(!_a||n)&&c[nr]!==p&&An(c,nr,p,{name:a}),Jc[e]=p,g}});var ud=b((Fk,od)=>{"use strict";od.exports=function(r,e){return{value:r,done:e}}});var $n=b((qk,hd)=>{"use strict";var Xv=mi(),Rn=Cs(),ld=Qt(),dd=un(),Jv=Wt().f,Zv=nd(),Fa=ud(),ey=Ke(),ty=Ne(),pd="Array Iterator",iy=dd.set,ry=dd.getterFor(pd);hd.exports=Zv(Array,"Array",function(r,e){iy(this,{type:pd,target:Xv(r),index:0,kind:e})},function(){var r=ry(this),e=r.target,t=r.index++;if(!e||t>=e.length)return r.target=void 0,Fa(void 0,!0);switch(r.kind){case"keys":return Fa(t,!1);case"values":return Fa(e[t],!1)}return Fa([t,e[t]],!1)},"values");var cd=ld.Arguments=ld.Array;Rn("keys");Rn("values");Rn("entries");if(!ey&&ty&&cd.name!=="values")try{Jv(cd,"name",{value:"values"})}catch{}});var fd=b((Uk,md)=>{"use strict";var ay=ge(),sy=Qt(),ny=ay("iterator"),oy=Array.prototype;md.exports=function(r){return r!==void 0&&(sy.Array===r||oy[ny]===r)}});var Ln=b((Hk,gd)=>{"use strict";var uy=ar(),bd=Ki(),ly=hi(),cy=Qt(),dy=ge(),py=dy("iterator");gd.exports=function(r){if(!ly(r))return bd(r,py)||bd(r,"@@iterator")||cy[uy(r)]}});var vd=b((jk,Sd)=>{"use strict";var hy=Me(),my=St(),fy=nt(),by=zi(),gy=Ln(),Sy=TypeError;Sd.exports=function(r,e){var t=arguments.length<2?gy(r):e;if(my(t))return fy(hy(t,r));throw new Sy(by(r)+" is not iterable")}});var Id=b((Gk,Td)=>{"use strict";var vy=Me(),yd=nt(),yy=Ki();Td.exports=function(r,e,t){var i,a;yd(r);try{if(i=yy(r,"return"),!i){if(e==="throw")throw t;return t}i=vy(i,r)}catch(s){a=!0,i=s}if(e==="throw")throw t;if(a)throw i;return yd(i),t}});var Ua=b((Qk,kd)=>{"use strict";var Ty=ir(),Iy=Me(),Ey=nt(),xy=zi(),Py=fd(),ky=Da(),Ed=Yi(),wy=vd(),Ay=Ln(),xd=Id(),Ry=TypeError,qa=function(r,e){this.stopped=r,this.result=e},Pd=qa.prototype;kd.exports=function(r,e,t){var i=t&&t.that,a=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=Ty(e,i),l,c,d,p,m,f,g,y=function(P){return l&&xd(l,"normal",P),new qa(!0,P)},I=function(P){return a?(Ey(P),o?u(P[0],P[1],y):u(P[0],P[1])):o?u(P,y):u(P)};if(s)l=r.iterator;else if(n)l=r;else{if(c=Ay(r),!c)throw new Ry(xy(r)+" is not iterable");if(Py(c)){for(d=0,p=ky(r);p>d;d++)if(m=I(r[d]),m&&Ed(Pd,m))return m;return new qa(!1)}l=wy(r,c)}for(f=s?r.next:l.next;!(g=Iy(f,l)).done;){try{m=I(g.value)}catch(P){xd(l,"throw",P)}if(typeof m=="object"&&m&&Ed(Pd,m))return m}return new qa(!1)}});var Ad=b((Wk,wd)=>{"use strict";var $y=Ne(),Ly=Wt(),My=Zi();wd.exports=function(r,e,t){$y?Ly.f(r,e,My(0,t)):r[e]=t}});var Rd=b(()=>{"use strict";var Dy=Fe(),Cy=Ua(),Vy=Ad();Dy({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Cy(e,function(i,a){Vy(t,i,a)},{AS_ENTRIES:!0}),t}})});var Ld=b((Kk,$d)=>{"use strict";$n();Rd();var By=Pa();$d.exports=By.Object.fromEntries});var Dd=b((Xk,Md)=>{"use strict";Md.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 Vd=b(()=>{"use strict";$n();var Oy=Dd(),_y=se(),Ny=sr(),Cd=Qt();for(Ha in Oy)Ny(_y[Ha],Ha),Cd[Ha]=Cd.Array;var Ha});var Od=b((ew,Bd)=>{"use strict";var Fy=Ld();Vd();Bd.exports=Fy});var Mn=b((tw,_d)=>{"use strict";var qy=Od();_d.exports=qy});var Nd=b(()=>{"use strict"});var Dn=b((aw,Fd)=>{"use strict";var ur=se(),Uy=fi(),Hy=pi(),ja=function(r){return Uy.slice(0,r.length)===r};Fd.exports=function(){return ja("Bun/")?"BUN":ja("Cloudflare-Workers")?"CLOUDFLARE":ja("Deno/")?"DENO":ja("Node.js/")?"NODE":ur.Bun&&typeof Bun.version=="string"?"BUN":ur.Deno&&typeof Deno.version=="object"?"DENO":Hy(ur.process)==="process"?"NODE":ur.window&&ur.document?"BROWSER":"REST"}()});var Ga=b((sw,qd)=>{"use strict";var jy=Dn();qd.exports=jy==="NODE"});var Hd=b((nw,Ud)=>{"use strict";var Gy=Wt();Ud.exports=function(r,e,t){return Gy.f(r,e,t)}});var Qd=b((ow,Gd)=>{"use strict";var Qy=gt(),Wy=Hd(),Yy=ge(),zy=Ne(),jd=Yy("species");Gd.exports=function(r){var e=Qy(r);zy&&e&&!e[jd]&&Wy(e,jd,{configurable:!0,get:function(){return this}})}});var Yd=b((uw,Wd)=>{"use strict";var Ky=Yi(),Xy=TypeError;Wd.exports=function(r,e){if(Ky(e,r))return r;throw new Xy("Incorrect invocation")}});var Vn=b((lw,zd)=>{"use strict";var Jy=Te(),Zy=ae(),Cn=Xi(),eT=Jy(Function.toString);Zy(Cn.inspectSource)||(Cn.inspectSource=function(r){return eT(r)});zd.exports=Cn.inspectSource});var tp=b((cw,ep)=>{"use strict";var tT=Te(),iT=Le(),Kd=ae(),rT=ar(),aT=gt(),sT=Vn(),Xd=function(){},Jd=aT("Reflect","construct"),Bn=/^\s*(?:class|function)\b/,nT=tT(Bn.exec),oT=!Bn.test(Xd),lr=function(e){if(!Kd(e))return!1;try{return Jd(Xd,[],e),!0}catch{return!1}},Zd=function(e){if(!Kd(e))return!1;switch(rT(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return oT||!!nT(Bn,sT(e))}catch{return!0}};Zd.sham=!0;ep.exports=!Jd||iT(function(){var r;return lr(lr.call)||!lr(Object)||!lr(function(){r=!0})||r})?Zd:lr});var rp=b((dw,ip)=>{"use strict";var uT=tp(),lT=zi(),cT=TypeError;ip.exports=function(r){if(uT(r))return r;throw new cT(lT(r)+" is not a constructor")}});var On=b((pw,sp)=>{"use strict";var ap=nt(),dT=rp(),pT=hi(),hT=ge(),mT=hT("species");sp.exports=function(r,e){var t=ap(r).constructor,i;return t===void 0||pT(i=ap(t)[mT])?e:dT(i)}});var op=b((hw,np)=>{"use strict";var fT=Te();np.exports=fT([].slice)});var lp=b((mw,up)=>{"use strict";var bT=TypeError;up.exports=function(r,e){if(r<e)throw new bT("Not enough arguments");return r}});var _n=b((fw,cp)=>{"use strict";var gT=fi();cp.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(gT)});var Wn=b((bw,vp)=>{"use strict";var De=se(),ST=ln(),vT=ir(),dp=ae(),yT=Xe(),Sp=Le(),pp=bn(),TT=op(),hp=Ea(),IT=lp(),ET=_n(),xT=Ga(),jn=De.setImmediate,Gn=De.clearImmediate,PT=De.process,Nn=De.Dispatch,kT=De.Function,mp=De.MessageChannel,wT=De.String,Fn=0,cr={},fp="onreadystatechange",dr,zt,qn,Un;Sp(function(){dr=De.location});var Qn=function(r){if(yT(cr,r)){var e=cr[r];delete cr[r],e()}},Hn=function(r){return function(){Qn(r)}},bp=function(r){Qn(r.data)},gp=function(r){De.postMessage(wT(r),dr.protocol+"//"+dr.host)};(!jn||!Gn)&&(jn=function(e){IT(arguments.length,1);var t=dp(e)?e:kT(e),i=TT(arguments,1);return cr[++Fn]=function(){ST(t,void 0,i)},zt(Fn),Fn},Gn=function(e){delete cr[e]},xT?zt=function(r){PT.nextTick(Hn(r))}:Nn&&Nn.now?zt=function(r){Nn.now(Hn(r))}:mp&&!ET?(qn=new mp,Un=qn.port2,qn.port1.onmessage=bp,zt=vT(Un.postMessage,Un)):De.addEventListener&&dp(De.postMessage)&&!De.importScripts&&dr&&dr.protocol!=="file:"&&!Sp(gp)?(zt=gp,De.addEventListener("message",bp,!1)):fp in hp("script")?zt=function(r){pp.appendChild(hp("script"))[fp]=function(){pp.removeChild(this),Qn(r)}}:zt=function(r){setTimeout(Hn(r),0)});vp.exports={set:jn,clear:Gn}});var Ip=b((gw,Tp)=>{"use strict";var yp=se(),AT=Ne(),RT=Object.getOwnPropertyDescriptor;Tp.exports=function(r){if(!AT)return yp[r];var e=RT(yp,r);return e&&e.value}});var Yn=b((Sw,xp)=>{"use strict";var Ep=function(){this.head=null,this.tail=null};Ep.prototype={add:function(r){var e={item:r,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var r=this.head;if(r){var e=this.head=r.next;return e===null&&(this.tail=null),r.item}}};xp.exports=Ep});var kp=b((vw,Pp)=>{"use strict";var $T=fi();Pp.exports=/ipad|iphone|ipod/i.test($T)&&typeof Pebble<"u"});var Ap=b((yw,wp)=>{"use strict";var LT=fi();wp.exports=/web0s(?!.*chrome)/i.test(LT)});var Vp=b((Tw,Cp)=>{"use strict";var Ii=se(),MT=Ip(),Rp=ir(),zn=Wn().set,DT=Yn(),CT=_n(),VT=kp(),BT=Ap(),Kn=Ga(),$p=Ii.MutationObserver||Ii.WebKitMutationObserver,Lp=Ii.document,Mp=Ii.process,Qa=Ii.Promise,Zn=MT("queueMicrotask"),Ti,Xn,Jn,Wa,Dp;Zn||(pr=new DT,hr=function(){var r,e;for(Kn&&(r=Mp.domain)&&r.exit();e=pr.get();)try{e()}catch(t){throw pr.head&&Ti(),t}r&&r.enter()},!CT&&!Kn&&!BT&&$p&&Lp?(Xn=!0,Jn=Lp.createTextNode(""),new $p(hr).observe(Jn,{characterData:!0}),Ti=function(){Jn.data=Xn=!Xn}):!VT&&Qa&&Qa.resolve?(Wa=Qa.resolve(void 0),Wa.constructor=Qa,Dp=Rp(Wa.then,Wa),Ti=function(){Dp(hr)}):Kn?Ti=function(){Mp.nextTick(hr)}:(zn=Rp(zn,Ii),Ti=function(){zn(hr)}),Zn=function(r){pr.head||Ti(),pr.add(r)});var pr,hr;Cp.exports=Zn});var Op=b((Iw,Bp)=>{"use strict";Bp.exports=function(r,e){try{arguments.length===1?console.error(r):console.error(r,e)}catch{}}});var Ya=b((Ew,_p)=>{"use strict";_p.exports=function(r){try{return{error:!1,value:r()}}catch(e){return{error:!0,value:e}}}});var Kt=b((xw,Np)=>{"use strict";var OT=se();Np.exports=OT.Promise});var Ei=b((Pw,Hp)=>{"use strict";var _T=se(),mr=Kt(),NT=ae(),FT=dn(),qT=Vn(),UT=ge(),Fp=Dn(),HT=Ke(),eo=Hs(),qp=mr&&mr.prototype,jT=UT("species"),to=!1,Up=NT(_T.PromiseRejectionEvent),GT=FT("Promise",function(){var r=qT(mr),e=r!==String(mr);if(!e&&eo===66||HT&&!(qp.catch&&qp.finally))return!0;if(!eo||eo<51||!/native code/.test(r)){var t=new mr(function(s){s(1)}),i=function(s){s(function(){},function(){})},a=t.constructor={};if(a[jT]=i,to=t.then(function(){})instanceof i,!to)return!0}return!e&&(Fp==="BROWSER"||Fp==="DENO")&&!Up});Hp.exports={CONSTRUCTOR:GT,REJECTION_EVENT:Up,SUBCLASSING:to}});var xi=b((kw,Gp)=>{"use strict";var jp=St(),QT=TypeError,WT=function(r){var e,t;this.promise=new r(function(i,a){if(e!==void 0||t!==void 0)throw new QT("Bad Promise constructor");e=i,t=a}),this.resolve=jp(e),this.reject=jp(t)};Gp.exports.f=function(r){return new WT(r)}});var ch=b(()=>{"use strict";var YT=Fe(),zT=Ke(),Ja=Ga(),Mt=se(),Ai=Me(),Qp=yi(),Wp=wn(),KT=sr(),XT=Qd(),JT=St(),Xa=ae(),ZT=_e(),eI=Yd(),tI=On(),Jp=Wn().set,no=Vp(),iI=Op(),rI=Ya(),aI=Yn(),Zp=un(),Za=Kt(),oo=Ei(),eh=xi(),es="Promise",th=oo.CONSTRUCTOR,sI=oo.REJECTION_EVENT,nI=oo.SUBCLASSING,io=Zp.getterFor(es),oI=Zp.set,Pi=Za&&Za.prototype,Xt=Za,za=Pi,ih=Mt.TypeError,ro=Mt.document,uo=Mt.process,ao=eh.f,uI=ao,lI=!!(ro&&ro.createEvent&&Mt.dispatchEvent),rh="unhandledrejection",cI="rejectionhandled",Yp=0,ah=1,dI=2,lo=1,sh=2,Ka,zp,pI,Kp,nh=function(r){var e;return ZT(r)&&Xa(e=r.then)?e:!1},oh=function(r,e){var t=e.value,i=e.state===ah,a=i?r.ok:r.fail,s=r.resolve,n=r.reject,o=r.domain,u,l,c;try{a?(i||(e.rejection===sh&&mI(e),e.rejection=lo),a===!0?u=t:(o&&o.enter(),u=a(t),o&&(o.exit(),c=!0)),u===r.promise?n(new ih("Promise-chain cycle")):(l=nh(u))?Ai(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},uh=function(r,e){r.notified||(r.notified=!0,no(function(){for(var t=r.reactions,i;i=t.get();)oh(i,r);r.notified=!1,e&&!r.rejection&&hI(r)}))},lh=function(r,e,t){var i,a;lI?(i=ro.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(r,!1,!0),Mt.dispatchEvent(i)):i={promise:e,reason:t},!sI&&(a=Mt["on"+r])?a(i):r===rh&&iI("Unhandled promise rejection",t)},hI=function(r){Ai(Jp,Mt,function(){var e=r.facade,t=r.value,i=Xp(r),a;if(i&&(a=rI(function(){Ja?uo.emit("unhandledRejection",t,e):lh(rh,e,t)}),r.rejection=Ja||Xp(r)?sh:lo,a.error))throw a.value})},Xp=function(r){return r.rejection!==lo&&!r.parent},mI=function(r){Ai(Jp,Mt,function(){var e=r.facade;Ja?uo.emit("rejectionHandled",e):lh(cI,e,r.value)})},ki=function(r,e,t){return function(i){r(e,i,t)}},wi=function(r,e,t){r.done||(r.done=!0,t&&(r=t),r.value=e,r.state=dI,uh(r,!0))},so=function(r,e,t){if(!r.done){r.done=!0,t&&(r=t);try{if(r.facade===e)throw new ih("Promise can't be resolved itself");var i=nh(e);i?no(function(){var a={done:!1};try{Ai(i,e,ki(so,a,r),ki(wi,a,r))}catch(s){wi(a,s,r)}}):(r.value=e,r.state=ah,uh(r,!1))}catch(a){wi({done:!1},a,r)}}};if(th&&(Xt=function(e){eI(this,za),JT(e),Ai(Ka,this);var t=io(this);try{e(ki(so,t),ki(wi,t))}catch(i){wi(t,i)}},za=Xt.prototype,Ka=function(e){oI(this,{type:es,done:!1,notified:!1,parent:!1,reactions:new aI,rejection:!1,state:Yp,value:void 0})},Ka.prototype=Qp(za,"then",function(e,t){var i=io(this),a=ao(tI(this,Xt));return i.parent=!0,a.ok=Xa(e)?e:!0,a.fail=Xa(t)&&t,a.domain=Ja?uo.domain:void 0,i.state===Yp?i.reactions.add(a):no(function(){oh(a,i)}),a.promise}),zp=function(){var r=new Ka,e=io(r);this.promise=r,this.resolve=ki(so,e),this.reject=ki(wi,e)},eh.f=ao=function(r){return r===Xt||r===pI?new zp(r):uI(r)},!zT&&Xa(Za)&&Pi!==Object.prototype)){Kp=Pi.then,nI||Qp(Pi,"then",function(e,t){var i=this;return new Xt(function(a,s){Ai(Kp,i,a,s)}).then(e,t)},{unsafe:!0});try{delete Pi.constructor}catch{}Wp&&Wp(Pi,za)}YT({global:!0,constructor:!0,wrap:!0,forced:th},{Promise:Xt});KT(Xt,es,!1,!0);XT(es)});var fh=b((Rw,mh)=>{"use strict";var fI=ge(),ph=fI("iterator"),hh=!1;try{dh=0,co={next:function(){return{done:!!dh++}},return:function(){hh=!0}},co[ph]=function(){return this},Array.from(co,function(){throw 2})}catch{}var dh,co;mh.exports=function(r,e){try{if(!e&&!hh)return!1}catch{return!1}var t=!1;try{var i={};i[ph]=function(){return{next:function(){return{done:t=!0}}}},r(i)}catch{}return t}});var po=b(($w,bh)=>{"use strict";var bI=Kt(),gI=fh(),SI=Ei().CONSTRUCTOR;bh.exports=SI||!gI(function(r){bI.all(r).then(void 0,function(){})})});var gh=b(()=>{"use strict";var vI=Fe(),yI=Me(),TI=St(),II=xi(),EI=Ya(),xI=Ua(),PI=po();vI({target:"Promise",stat:!0,forced:PI},{all:function(e){var t=this,i=II.f(t),a=i.resolve,s=i.reject,n=EI(function(){var o=TI(t.resolve),u=[],l=0,c=1;xI(e,function(d){var p=l++,m=!1;c++,yI(o,t,d).then(function(f){m||(m=!0,u[p]=f,--c||a(u))},s)}),--c||a(u)});return n.error&&s(n.value),i.promise}})});var vh=b(()=>{"use strict";var kI=Fe(),wI=Ke(),AI=Ei().CONSTRUCTOR,mo=Kt(),RI=gt(),$I=ae(),LI=yi(),Sh=mo&&mo.prototype;kI({target:"Promise",proto:!0,forced:AI,real:!0},{catch:function(r){return this.then(void 0,r)}});!wI&&$I(mo)&&(ho=RI("Promise").prototype.catch,Sh.catch!==ho&&LI(Sh,"catch",ho,{unsafe:!0}));var ho});var yh=b(()=>{"use strict";var MI=Fe(),DI=Me(),CI=St(),VI=xi(),BI=Ya(),OI=Ua(),_I=po();MI({target:"Promise",stat:!0,forced:_I},{race:function(e){var t=this,i=VI.f(t),a=i.reject,s=BI(function(){var n=CI(t.resolve);OI(e,function(o){DI(n,t,o).then(i.resolve,a)})});return s.error&&a(s.value),i.promise}})});var Th=b(()=>{"use strict";var NI=Fe(),FI=xi(),qI=Ei().CONSTRUCTOR;NI({target:"Promise",stat:!0,forced:qI},{reject:function(e){var t=FI.f(this),i=t.reject;return i(e),t.promise}})});var fo=b((Nw,Ih)=>{"use strict";var UI=nt(),HI=_e(),jI=xi();Ih.exports=function(r,e){if(UI(r),HI(e)&&e.constructor===r)return e;var t=jI.f(r),i=t.resolve;return i(e),t.promise}});var Ph=b(()=>{"use strict";var GI=Fe(),QI=gt(),Eh=Ke(),WI=Kt(),xh=Ei().CONSTRUCTOR,YI=fo(),zI=QI("Promise"),KI=Eh&&!xh;GI({target:"Promise",stat:!0,forced:Eh||xh},{resolve:function(e){return YI(KI&&this===zI?WI:this,e)}})});var kh=b(()=>{"use strict";ch();gh();vh();yh();Th();Ph()});var $h=b(()=>{"use strict";var XI=Fe(),JI=Ke(),ts=Kt(),ZI=Le(),Ah=gt(),Rh=ae(),eE=On(),wh=fo(),tE=yi(),go=ts&&ts.prototype,iE=!!ts&&ZI(function(){go.finally.call({then:function(){}},function(){})});XI({target:"Promise",proto:!0,real:!0,forced:iE},{finally:function(r){var e=eE(this,Ah("Promise")),t=Rh(r);return this.then(t?function(i){return wh(e,r()).then(function(){return i})}:r,t?function(i){return wh(e,r()).then(function(){throw i})}:r)}});!JI&&Rh(ts)&&(bo=Ah("Promise").prototype.finally,go.finally!==bo&&tE(go,"finally",bo,{unsafe:!0}));var bo});var is=b((Qw,Lh)=>{"use strict";var rE=gt();Lh.exports=rE});var Dh=b((Ww,Mh)=>{"use strict";Nd();kh();$h();var aE=is();Mh.exports=aE("Promise","finally")});var Vh=b((Yw,Ch)=>{"use strict";var sE=Dh();Ch.exports=sE});var rs=b((zw,Bh)=>{"use strict";var nE=Vh();Bh.exports=nE});var Qh=b(()=>{"use strict";var mE=Fe(),fE=Ji(),bE=Da(),gE=Ma(),SE=Cs();mE({target:"Array",proto:!0},{at:function(e){var t=fE(this),i=bE(t),a=gE(e),s=a>=0?a:i+a;return s<0||s>=i?void 0:t[s]}});SE("at")});var Yh=b((WA,Wh)=>{"use strict";Qh();var vE=is();Wh.exports=vE("Array","at")});var Kh=b((YA,zh)=>{"use strict";var yE=Yh();zh.exports=yE});var Ri=b((zA,Xh)=>{"use strict";var TE=Kh();Xh.exports=TE});var Cm=b(()=>{"use strict"});var Vm=b(()=>{"use strict"});var Om=b((FM,Bm)=>{"use strict";var rx=_e(),ax=pi(),sx=ge(),nx=sx("match");Bm.exports=function(r){var e;return rx(r)&&((e=r[nx])!==void 0?!!e:ax(r)==="RegExp")}});var Nm=b((qM,_m)=>{"use strict";var ox=ar(),ux=String;_m.exports=function(r){if(ox(r)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return ux(r)}});var qm=b((UM,Fm)=>{"use strict";var lx=nt();Fm.exports=function(){var r=lx(this),e="";return r.hasIndices&&(e+="d"),r.global&&(e+="g"),r.ignoreCase&&(e+="i"),r.multiline&&(e+="m"),r.dotAll&&(e+="s"),r.unicode&&(e+="u"),r.unicodeSets&&(e+="v"),r.sticky&&(e+="y"),e}});var jm=b((HM,Hm)=>{"use strict";var cx=Me(),dx=Xe(),px=Yi(),hx=qm(),Um=RegExp.prototype;Hm.exports=function(r){var e=r.flags;return e===void 0&&!("flags"in Um)&&!dx(r,"flags")&&px(Um,r)?cx(hx,r):e}});var Qm=b((jM,Gm)=>{"use strict";var Fo=Te(),mx=Ji(),fx=Math.floor,_o=Fo("".charAt),bx=Fo("".replace),No=Fo("".slice),gx=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Sx=/\$([$&'`]|\d{1,2})/g;Gm.exports=function(r,e,t,i,a,s){var n=t+r.length,o=i.length,u=Sx;return a!==void 0&&(a=mx(a),u=gx),bx(s,u,function(l,c){var d;switch(_o(c,0)){case"$":return"$";case"&":return r;case"`":return No(e,0,t);case"'":return No(e,n);case"<":d=a[No(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var m=fx(p/10);return m===0?l:m<=o?i[m-1]===void 0?_o(c,1):i[m-1]+_o(c,1):l}d=i[p-1]}return d===void 0?"":d})}});var zm=b(()=>{"use strict";var vx=Fe(),yx=Me(),Uo=Te(),Wm=Qi(),Tx=ae(),Ix=hi(),Ex=Om(),Bi=Nm(),xx=Ki(),Px=jm(),kx=Qm(),wx=ge(),Ax=Ke(),Rx=wx("replace"),$x=TypeError,qo=Uo("".indexOf),Lx=Uo("".replace),Ym=Uo("".slice),Mx=Math.max;vx({target:"String",proto:!0},{replaceAll:function(e,t){var i=Wm(this),a,s,n,o,u,l,c,d,p,m,f=0,g="";if(!Ix(e)){if(a=Ex(e),a&&(s=Bi(Wm(Px(e))),!~qo(s,"g")))throw new $x("`.replaceAll` does not allow non-global regexes");if(n=xx(e,Rx),n)return yx(n,e,i,t);if(Ax&&a)return Lx(Bi(i),e,t)}for(o=Bi(i),u=Bi(e),l=Tx(t),l||(t=Bi(t)),c=u.length,d=Mx(1,c),p=qo(o,u);p!==-1;)m=l?Bi(t(u,p,o)):kx(u,o,p,[],void 0,t),g+=Ym(o,f,p)+m,f=p+c,p=p+d>o.length?-1:qo(o,u,p+d);return f<o.length&&(g+=Ym(o,f)),g}})});var Xm=b((WM,Km)=>{"use strict";Cm();Vm();zm();var Dx=is();Km.exports=Dx("String","replaceAll")});var Zm=b((YM,Jm)=>{"use strict";var Cx=Xm();Jm.exports=Cx});var tf=b((zM,ef)=>{"use strict";var Vx=Zm();ef.exports=Vx});var Zx={};Kf(Zx,{ChromecastState:()=>ji,HttpConnectionType:()=>ya,Observable:()=>pt.Observable,PlaybackState:()=>be,Player:()=>pa,SDK_VERSION:()=>Jx,Subject:()=>pt.Subject,Subscription:()=>pt.Subscription,Surface:()=>Ta,VERSION:()=>Ls,ValueSubject:()=>pt.ValueSubject,VideoFormat:()=>bt,VideoQuality:()=>pt.VideoQuality});module.exports=Xf(Zx);var Ls="2.0.117-dev.d9cc3d97.0";var be=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(be||{}),bt=(k=>(k.MPEG="MPEG",k.DASH="DASH",k.DASH_SEP="DASH_SEP",k.DASH_SEP_VK="DASH_SEP",k.DASH_WEBM="DASH_WEBM",k.DASH_WEBM_AV1="DASH_WEBM_AV1",k.DASH_STREAMS="DASH_STREAMS",k.DASH_WEBM_VK="DASH_WEBM",k.DASH_ONDEMAND="DASH_ONDEMAND",k.DASH_ONDEMAND_VK="DASH_ONDEMAND",k.DASH_LIVE="DASH_LIVE",k.DASH_LIVE_CMAF="DASH_LIVE_CMAF",k.DASH_LIVE_WEBM="DASH_LIVE_WEBM",k.HLS="HLS",k.HLS_ONDEMAND="HLS_ONDEMAND",k.HLS_JS="HLS",k.HLS_LIVE="HLS_LIVE",k.HLS_LIVE_CMAF="HLS_LIVE_CMAF",k.WEB_RTC_LIVE="WEB_RTC_LIVE",k))(bt||{});var ji=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(ji||{}),ya=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(ya||{});var Ta=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Ta||{});var F=require("@vkontakte/videoplayer-shared");var uu=r=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",r),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});var Ia=class{constructor(e){this.connection$=new F.ValueSubject(void 0);this.castState$=new F.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new F.Subject;this.realCastState$=new F.ValueSubject("NOT_AVAILABLE");this.subscription=new F.Subscription;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=(0,F.isNonNullable)(window.chrome?.cast),a=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},a||uu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:F.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,F.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,F.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,F.isNullable)(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add((0,F.fromEvent)(i,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=i.getCurrentSession()?.getMediaSession()?.media?.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return(0,F.assertNever)(a.sessionState)}})).add((0,F.merge)((0,F.fromEvent)(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,F.tap)(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),(0,F.map)(a=>a.castState)),(0,F.observableFrom)([i.getCastState()])).pipe((0,F.filterChanged)(),(0,F.map)(Jf),(0,F.tap)(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=(0,F.isNonNullable)(this.connection$.getValue());if(s&&!n){let o=i.getCurrentSession();(0,F.assertNonNullable)(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;((0,F.isNullable)(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a==="CONNECTED"?(0,F.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":a)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:F.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},Jf=r=>{switch(r){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return(0,F.assertNever)(r)}};var Rf=Oe(Mn(),1);var Fh=Oe(rs(),1);var So=require("@vkontakte/videoplayer-shared");var he=(r,e=0,t=0)=>{switch(t){case 0:return r.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return r;let i=new URL(r);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(r);return!i.searchParams.get("offset_p")&&e===0?r:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:(0,So.assertNever)(t)}return r},vo=(r,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(r);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(r);return Number(t.searchParams.get("offset_p")??0)}default:(0,So.assertNever)(e)}};var A=(r,e,t=!1)=>{let i=r.getTransition();(t||!i||i.to===e)&&r.setState(e)};var ot=require("@vkontakte/videoplayer-shared"),q=class{constructor(e){this.transitionStarted$=new ot.Subject;this.transitionEnded$=new ot.Subject;this.transitionUpdated$=new ot.Subject;this.forceChanged$=new ot.Subject;this.stateChangeStarted$=(0,ot.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,ot.merge)(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,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:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||(0,ot.isNonNullable)(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};var Oh=require("@vkontakte/videoplayer-shared"),_h=r=>{switch(r){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return(0,Oh.assertNever)(r)}};var $=require("@vkontakte/videoplayer-shared");var oE=5,uE=5,lE=500,Nh=7e3,fr=class{constructor(e){this.subscription=new $.Subscription;this.loadMediaTimeoutSubscription=new $.Subscription;this.videoState=new q("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=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: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="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(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,$.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,$.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,$.assertNever)(e)}break}default:(0,$.assertNever)(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(_h(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 $.Subscription;this.subscription.add(e),this.subscription.add((0,$.merge)(this.videoState.stateChangeStarted$.pipe((0,$.map)(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe((0,$.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 $.Subject;e.add(a.pipe((0,$.debounce)(lE)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,$.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)>oE)&&a.next(o),s=o})),e.add((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,$.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,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,$.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(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<uE&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),A(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:(0,$.assertNever)(n)}}),t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let i=(0,$.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,$.observableFrom)(["init"])).pipe((0,$.debounce)(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),A(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?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),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),A(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&A(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,i,a,s;switch(e){case"MPEG":{let l=t[e];(0,$.assertNonNullable)(l);let c=(0,$.getHighestQuality)(Object.keys(l));(0,$.assertNonNullable)(c);let d=l[c];(0,$.assertNonNullable)(d),i=d,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];(0,$.assertNonNullable)(l),i=l.url,a="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=t[e];(0,$.assertNonNullable)(l),i=l.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];(0,$.assertNonNullable)(l),i=l.url,a="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];(0,$.assertNonNullable)(l),i=he(l.url),a="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:$.ErrorCategory.VIDEO_PIPELINE,message:l,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,$.assertNever)(e)}let n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,a);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return(0,$.isNonNullable)(o)&&(n.metadata.title=o),(0,$.isNonNullable)(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((a,s)=>{this.loadMediaTimeoutSubscription.add((0,$.timeout)(Nh).subscribe(()=>s(`timeout(${Nh})`)))});(0,Fh.default)(Promise.race([t,i]).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:$.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Eo=require("@vkontakte/videoplayer-shared");var qh=require("@vkontakte/videoplayer-shared"),Uh=r=>{try{r.pause(),r.playbackRate=0,(0,qh.clearVideoElement)(r),r.remove()}catch(e){console.error(e)}};var as=require("@vkontakte/videoplayer-shared"),yo=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)}},To=window.WeakMap?new WeakMap:new yo,Io=window.WeakMap?new WeakMap:new Map,cE=(r,e=20)=>{let t=0;return(0,as.fromEvent)(r,"ratechange").subscribe(i=>{t++,t>=e&&(r.currentTime=r.currentTime,t=0)})},Ie=(r,{audioVideoSyncRate:e})=>{let t=r.querySelector("video"),i=!!t;t?(0,Eo.clearVideoElement)(t):(t=document.createElement("video"),r.appendChild(t)),To.set(t,i);let a=new as.Subscription;return a.add(cE(t,e)),Io.set(t,a),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},Ee=r=>{Io.get(r)?.unsubscribe(),Io.delete(r);let t=To.get(r);To.delete(r),t?(0,Eo.clearVideoElement)(r):Uh(r)};var L=require("@vkontakte/videoplayer-shared");var Dt=require("@vkontakte/videoplayer-shared"),ss=(r,e,t,{equal:i=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=r.getState(),o=e(),u=(0,Dt.isNullable)(a),l=new Dt.Subscription;return a&&l.add(a.subscribe(c=>{let d=r.getState();i(c,d)&&r.setState(c)},s)),i(o,n)||(t(n),u&&r.setState(n)),l.add(r.stateChangeStarted$.subscribe(c=>{t(c.to),u&&r.setState(c.to)},s)),l},ut=(r,e,t)=>ss(e,()=>r.loop,i=>{(0,Dt.isNonNullable)(i)&&(r.loop=i)},{onError:t}),xe=(r,e,t,i)=>ss(e,()=>({muted:r.muted,volume:r.volume}),a=>{(0,Dt.isNonNullable)(a)&&(r.muted=a.muted,r.volume=a.volume)},{equal:(a,s)=>a===s||a?.muted===s?.muted&&a?.volume===s?.volume,changed$:t,onError:i}),qe=(r,e,t,i)=>ss(e,()=>r.playbackRate,a=>{(0,Dt.isNonNullable)(a)&&(r.playbackRate=a)},{changed$:t,onError:i}),Ct=ss;var dE=r=>["__",r.language,r.label].join("|"),pE=(r,e)=>{if(r.id===e)return!0;let[t,i,a]=e.split("|");return r.language===i&&r.label===a},xo=class r{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,i){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(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Ct(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},u)=>o===n[u].id),changed$:this.available$.pipe((0,L.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(Ct(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},u)=>o===n[u].id),changed$:this.available$.pipe((0,L.map)(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(Ct(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(Ct(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 i=this.current$.getValue();i&&this.select(i)})),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(i=>this.htmlTextTrackToITextTrack(i))),(0,L.filterChanged)((i,a)=>i.length===a.length&&i.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:i})=>i==="showing")),(0,L.map)(i=>i&&this.htmlTextTrackToITextTrack(i).id),(0,L.filterChanged)()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add((0,L.fromEvent)(e,"addtrack").subscribe(i=>{i.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))};i.track?.addEventListener("cuechange",a)})),this.subscription.add((0,L.fromEvent)(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let a=i;(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(r.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,a=e.id?e.id:dE(e),s=this.externalTracks.has(a),n=(s?this.externalTracks.get(a)?.isAuto:this.internalTracks.get(a)?.isAuto)??a.includes("auto");return s?{id:a,type:"external",isAuto:n,language:t,label:i,url:this.externalTracks.get(a)?.url}:{id:a,type:"internal",isAuto:n,language:t,label:i,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(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:a,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===a&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(a=>a.id===i)).forEach(([,i])=>this.detach(i))}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)||!pE(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"),i=>i.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)}},Ue=xo;var Tt=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 Hh=r=>{let e=r;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Po=r=>{let e=Hh(r);return!!(e&&e.fullscreenElement&&e.fullscreenElement===r)},jh=r=>{let e=Hh(r);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===r)};var D=require("@vkontakte/videoplayer-shared");var hE=3,Gh=(r,e,t=hE)=>{let i=0,a=0;for(let s=0;s<r.length;s++){let n=r.start(s),o=r.end(s);if(n<=e&&e<=o){if(i=n,a=o,!t)return{from:i,to:a};for(let u=s-1;u>=0;u--)r.end(u)+t>=i&&(i=r.start(u));for(let u=s+1;u<r.length;u++)r.start(u)-t<=a&&(a=r.end(u))}}return{from:i,to:a}};var Pe=r=>{let e=k=>(0,D.fromEvent)(r,k).pipe((0,D.mapTo)(void 0)),i=(0,D.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(k=>(0,D.fromEvent)(r,k))).pipe((0,D.map)(k=>k.type==="ended"?r.readyState<2:r.readyState<3),(0,D.filterChanged)()),a=(0,D.merge)((0,D.fromEvent)(r,"progress"),(0,D.fromEvent)(r,"timeupdate")).pipe((0,D.map)(()=>Gh(r.buffered,r.currentTime))),s=D.clientChecker.isSafari?(0,D.combine)({play:e("play").pipe((0,D.once)()),playing:e("playing")}).pipe((0,D.mapTo)(void 0)):e("playing"),n=(0,D.fromEvent)(r,"volumechange").pipe((0,D.map)(()=>({muted:r.muted,volume:r.volume}))),o=(0,D.fromEvent)(r,"ratechange").pipe((0,D.map)(()=>r.playbackRate)),u=(0,D.fromEvent)(r,"error").pipe((0,D.filter)(()=>!!(r.error||r.played.length)),(0,D.map)(()=>{let k=r.error;return{id:k?`MediaError#${k.code}`:"HtmlVideoError",category:D.ErrorCategory.VIDEO_PIPELINE,message:k?k.message:"Error event from HTML video element",thrown:r.error??void 0}})),l=(0,D.fromEvent)(r,"timeupdate").pipe((0,D.map)(()=>r.currentTime)),c=new D.Subject,d=.3,p;l.subscribe(k=>{r.loop&&(0,D.isNonNullable)(p)&&(0,D.isNonNullable)(k)&&p>=r.duration-d&&k<=d&&c.next(p),p=k});let m=e("pause").pipe((0,D.filter)(()=>!r.error&&p!==r.duration)),f=(0,D.fromEvent)(r,"enterpictureinpicture"),g=(0,D.fromEvent)(r,"leavepictureinpicture"),y=new D.ValueSubject(jh(r));f.subscribe(()=>y.next(!0)),g.subscribe(()=>y.next(!1));let I=new D.ValueSubject(Po(r));return(0,D.fromEvent)(r,"fullscreenchange").pipe((0,D.map)(()=>Po(r))).subscribe(I),{playing$:s,pause$:m,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:(0,D.fromEvent)(r,"durationchange").pipe((0,D.map)(()=>r.duration)),isBuffering$:i,currentBuffer$:a,volumeState$:n,playbackRateState$:o,inPiP$:y,inFullscreen$:I}};var It=require("@vkontakte/videoplayer-shared"),Vt=r=>{switch(r){case"mobile":return It.VideoQuality.Q_144P;case"lowest":return It.VideoQuality.Q_240P;case"low":return It.VideoQuality.Q_360P;case"sd":case"medium":return It.VideoQuality.Q_480P;case"hd":case"high":return It.VideoQuality.Q_720P;case"fullhd":case"full":return It.VideoQuality.Q_1080P;case"quadhd":case"quad":return It.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return It.VideoQuality.Q_2160P}};var Bt=Oe(Ri(),1),M=require("@vkontakte/videoplayer-shared");var ko=!1,Et={},Jh=r=>{ko=r},Zh=()=>{Et={}},em=r=>{r(Et)},br=(r,e)=>{ko&&(Et.meta=Et.meta??{},Et.meta[r]=e)},Se=class{constructor(e){this.name=e}next(e){if(!ko)return;Et.series=Et.series??{};let t=Et.series[this.name]??[];t.push([Date.now(),e]),Et.series[this.name]=t}};var IE=new Se("best_bitrate"),im=(r,e,t)=>(e-t)*Math.pow(2,-10*r)+t;var wo=r=>(e,t)=>r*(Number(e.bitrate)-Number(t.bitrate)),gr=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,M.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},rm='Assertion "ABR Tracks is empty array" failed',ns=(r,e,t,i)=>{let a=[...e].sort(wo(1)),s=[...t].sort(wo(1)),n=s.filter(u=>(0,M.isNonNullable)(u.bitrate)&&(0,M.isNonNullable)(r.bitrate)?r.bitrate/u.bitrate>i:!0),o=(0,Bt.default)(s,Math.round(s.length*a.indexOf(r)/(a.length+1)))??(0,Bt.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,Bt.default)(n,-1):(0,Bt.default)(s,0)},tm=r=>"quality"in r,am=(r,e,t,i)=>{let a=(0,M.isNonNullable)(i?.last?.bitrate)&&(0,M.isNonNullable)(t?.bitrate)&&i.last.bitrate<t.bitrate?r.trackCooldownIncreaseQuality:r.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&(0,M.now)()-i.history[t.id]<=a&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!s&&i.recordSelection(t),s&&i?.last){let n=i.last;i?.recordSwitch(n);let o=tm(n)?"video":"audio",u=tm(n)?n.quality:n.bitrate;return e({message:`
|
|
6
|
+
"use strict";var Hf=Object.create;var Sa=Object.defineProperty;var jf=Object.getOwnPropertyDescriptor;var Gf=Object.getOwnPropertyNames;var Qf=Object.getPrototypeOf,Wf=Object.prototype.hasOwnProperty;var b=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Yf=(r,e)=>{for(var t in e)Sa(r,t,{get:e[t],enumerable:!0})},su=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Gf(e))!Wf.call(r,a)&&a!==t&&Sa(r,a,{get:()=>e[a],enumerable:!(i=jf(e,a))||i.enumerable});return r};var Be=(r,e,t)=>(t=r!=null?Hf(Qf(r)):{},su(e||!r||!r.__esModule?Sa(t,"default",{value:r,enumerable:!0}):t,r)),zf=r=>su(Sa({},"__esModule",{value:!0}),r);var Re=b((dP,ou)=>{"use strict";ou.exports=function(r){try{return!!r()}catch{return!0}}});var ji=b((pP,uu)=>{"use strict";var Jf=Re();uu.exports=!Jf(function(){var r=function(){}.bind();return typeof r!="function"||r.hasOwnProperty("prototype")})});var ve=b((hP,du)=>{"use strict";var lu=ji(),cu=Function.prototype,$s=cu.call,Xf=lu&&cu.bind.bind($s,$s);du.exports=lu?Xf:function(r){return function(){return $s.apply(r,arguments)}}});var di=b((mP,hu)=>{"use strict";var pu=ve(),Zf=pu({}.toString),eb=pu("".slice);hu.exports=function(r){return eb(Zf(r),8,-1)}});var fu=b((fP,mu)=>{"use strict";var tb=ve(),ib=Re(),rb=di(),Ls=Object,ab=tb("".split);mu.exports=ib(function(){return!Ls("z").propertyIsEnumerable(0)})?function(r){return rb(r)==="String"?ab(r,""):Ls(r)}:Ls});var pi=b((bP,bu)=>{"use strict";bu.exports=function(r){return r==null}});var Gi=b((gP,gu)=>{"use strict";var sb=pi(),nb=TypeError;gu.exports=function(r){if(sb(r))throw new nb("Can't call method on "+r);return r}});var hi=b((SP,Su)=>{"use strict";var ob=fu(),ub=Gi();Su.exports=function(r){return ob(ub(r))}});var Ms=b((vP,vu)=>{"use strict";vu.exports=function(){}});var Gt=b((yP,yu)=>{"use strict";yu.exports={}});var se=b((Cs,Tu)=>{"use strict";var Qi=function(r){return r&&r.Math===Math&&r};Tu.exports=Qi(typeof globalThis=="object"&&globalThis)||Qi(typeof window=="object"&&window)||Qi(typeof self=="object"&&self)||Qi(typeof global=="object"&&global)||Qi(typeof Cs=="object"&&Cs)||function(){return this}()||Function("return this")()});var ae=b((TP,Iu)=>{"use strict";var Ds=typeof document=="object"&&document.all;Iu.exports=typeof Ds>"u"&&Ds!==void 0?function(r){return typeof r=="function"||r===Ds}:function(r){return typeof r=="function"}});var Pu=b((IP,xu)=>{"use strict";var lb=se(),cb=ae(),Eu=lb.WeakMap;xu.exports=cb(Eu)&&/native code/.test(String(Eu))});var Oe=b((EP,ku)=>{"use strict";var db=ae();ku.exports=function(r){return typeof r=="object"?r!==null:db(r)}});var _e=b((xP,Au)=>{"use strict";var pb=Re();Au.exports=!pb(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ia=b((PP,Ru)=>{"use strict";var hb=se(),wu=Oe(),Vs=hb.document,mb=wu(Vs)&&wu(Vs.createElement);Ru.exports=function(r){return mb?Vs.createElement(r):{}}});var Bs=b((kP,$u)=>{"use strict";var fb=_e(),bb=Re(),gb=Ia();$u.exports=!fb&&!bb(function(){return Object.defineProperty(gb("div"),"a",{get:function(){return 7}}).a!==7})});var Os=b((AP,Lu)=>{"use strict";var Sb=_e(),vb=Re();Lu.exports=Sb&&vb(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var at=b((wP,Mu)=>{"use strict";var yb=Oe(),Tb=String,Ib=TypeError;Mu.exports=function(r){if(yb(r))return r;throw new Ib(Tb(r)+" is not an object")}});var $e=b((RP,Cu)=>{"use strict";var Eb=ji(),Ea=Function.prototype.call;Cu.exports=Eb?Ea.bind(Ea):function(){return Ea.apply(Ea,arguments)}});var xa=b(($P,Du)=>{"use strict";Du.exports={}});var ft=b((LP,Bu)=>{"use strict";var _s=xa(),Ns=se(),xb=ae(),Vu=function(r){return xb(r)?r:void 0};Bu.exports=function(r,e){return arguments.length<2?Vu(_s[r])||Vu(Ns[r]):_s[r]&&_s[r][e]||Ns[r]&&Ns[r][e]}});var Wi=b((MP,Ou)=>{"use strict";var Pb=ve();Ou.exports=Pb({}.isPrototypeOf)});var mi=b((CP,Fu)=>{"use strict";var kb=se(),_u=kb.navigator,Nu=_u&&_u.userAgent;Fu.exports=Nu?String(Nu):""});var qs=b((DP,Qu)=>{"use strict";var Gu=se(),Fs=mi(),qu=Gu.process,Uu=Gu.Deno,Hu=qu&&qu.versions||Uu&&Uu.version,ju=Hu&&Hu.v8,Ye,Pa;ju&&(Ye=ju.split("."),Pa=Ye[0]>0&&Ye[0]<4?1:+(Ye[0]+Ye[1]));!Pa&&Fs&&(Ye=Fs.match(/Edge\/(\d+)/),(!Ye||Ye[1]>=74)&&(Ye=Fs.match(/Chrome\/(\d+)/),Ye&&(Pa=+Ye[1])));Qu.exports=Pa});var Us=b((VP,Yu)=>{"use strict";var Wu=qs(),Ab=Re(),wb=se(),Rb=wb.String;Yu.exports=!!Object.getOwnPropertySymbols&&!Ab(function(){var r=Symbol("symbol detection");return!Rb(r)||!(Object(r)instanceof Symbol)||!Symbol.sham&&Wu&&Wu<41})});var Hs=b((BP,zu)=>{"use strict";var $b=Us();zu.exports=$b&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var js=b((OP,Ku)=>{"use strict";var Lb=ft(),Mb=ae(),Cb=Wi(),Db=Hs(),Vb=Object;Ku.exports=Db?function(r){return typeof r=="symbol"}:function(r){var e=Lb("Symbol");return Mb(e)&&Cb(e.prototype,Vb(r))}});var Yi=b((_P,Ju)=>{"use strict";var Bb=String;Ju.exports=function(r){try{return Bb(r)}catch{return"Object"}}});var bt=b((NP,Xu)=>{"use strict";var Ob=ae(),_b=Yi(),Nb=TypeError;Xu.exports=function(r){if(Ob(r))return r;throw new Nb(_b(r)+" is not a function")}});var zi=b((FP,Zu)=>{"use strict";var Fb=bt(),qb=pi();Zu.exports=function(r,e){var t=r[e];return qb(t)?void 0:Fb(t)}});var tl=b((qP,el)=>{"use strict";var Gs=$e(),Qs=ae(),Ws=Oe(),Ub=TypeError;el.exports=function(r,e){var t,i;if(e==="string"&&Qs(t=r.toString)&&!Ws(i=Gs(t,r))||Qs(t=r.valueOf)&&!Ws(i=Gs(t,r))||e!=="string"&&Qs(t=r.toString)&&!Ws(i=Gs(t,r)))return i;throw new Ub("Can't convert object to primitive value")}});var ze=b((UP,il)=>{"use strict";il.exports=!0});var sl=b((HP,al)=>{"use strict";var rl=se(),Hb=Object.defineProperty;al.exports=function(r,e){try{Hb(rl,r,{value:e,configurable:!0,writable:!0})}catch{rl[r]=e}return e}});var Ki=b((jP,ul)=>{"use strict";var jb=ze(),Gb=se(),Qb=sl(),nl="__core-js_shared__",ol=ul.exports=Gb[nl]||Qb(nl,{});(ol.versions||(ol.versions=[])).push({version:"3.38.0",mode:jb?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Ys=b((GP,cl)=>{"use strict";var ll=Ki();cl.exports=function(r,e){return ll[r]||(ll[r]=e||{})}});var Ji=b((QP,dl)=>{"use strict";var Wb=Gi(),Yb=Object;dl.exports=function(r){return Yb(Wb(r))}});var Ke=b((WP,pl)=>{"use strict";var zb=ve(),Kb=Ji(),Jb=zb({}.hasOwnProperty);pl.exports=Object.hasOwn||function(e,t){return Jb(Kb(e),t)}});var zs=b((YP,hl)=>{"use strict";var Xb=ve(),Zb=0,eg=Math.random(),tg=Xb(1 .toString);hl.exports=function(r){return"Symbol("+(r===void 0?"":r)+")_"+tg(++Zb+eg,36)}});var be=b((zP,fl)=>{"use strict";var ig=se(),rg=Ys(),ml=Ke(),ag=zs(),sg=Us(),ng=Hs(),fi=ig.Symbol,Ks=rg("wks"),og=ng?fi.for||fi:fi&&fi.withoutSetter||ag;fl.exports=function(r){return ml(Ks,r)||(Ks[r]=sg&&ml(fi,r)?fi[r]:og("Symbol."+r)),Ks[r]}});var vl=b((KP,Sl)=>{"use strict";var ug=$e(),bl=Oe(),gl=js(),lg=zi(),cg=tl(),dg=be(),pg=TypeError,hg=dg("toPrimitive");Sl.exports=function(r,e){if(!bl(r)||gl(r))return r;var t=lg(r,hg),i;if(t){if(e===void 0&&(e="default"),i=ug(t,r,e),!bl(i)||gl(i))return i;throw new pg("Can't convert object to primitive value")}return e===void 0&&(e="number"),cg(r,e)}});var Js=b((JP,yl)=>{"use strict";var mg=vl(),fg=js();yl.exports=function(r){var e=mg(r,"string");return fg(e)?e:e+""}});var Qt=b(Il=>{"use strict";var bg=_e(),gg=Bs(),Sg=Os(),ka=at(),Tl=Js(),vg=TypeError,Xs=Object.defineProperty,yg=Object.getOwnPropertyDescriptor,Zs="enumerable",en="configurable",tn="writable";Il.f=bg?Sg?function(e,t,i){if(ka(e),t=Tl(t),ka(i),typeof e=="function"&&t==="prototype"&&"value"in i&&tn in i&&!i[tn]){var a=yg(e,t);a&&a[tn]&&(e[t]=i.value,i={configurable:en in i?i[en]:a[en],enumerable:Zs in i?i[Zs]:a[Zs],writable:!1})}return Xs(e,t,i)}:Xs:function(e,t,i){if(ka(e),t=Tl(t),ka(i),gg)try{return Xs(e,t,i)}catch{}if("get"in i||"set"in i)throw new vg("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Xi=b((ZP,El)=>{"use strict";El.exports=function(r,e){return{enumerable:!(r&1),configurable:!(r&2),writable:!(r&4),value:e}}});var bi=b((ek,xl)=>{"use strict";var Tg=_e(),Ig=Qt(),Eg=Xi();xl.exports=Tg?function(r,e,t){return Ig.f(r,e,Eg(1,t))}:function(r,e,t){return r[e]=t,r}});var Aa=b((tk,kl)=>{"use strict";var xg=Ys(),Pg=zs(),Pl=xg("keys");kl.exports=function(r){return Pl[r]||(Pl[r]=Pg(r))}});var wa=b((ik,Al)=>{"use strict";Al.exports={}});var nn=b((rk,$l)=>{"use strict";var kg=Pu(),Rl=se(),Ag=Oe(),wg=bi(),rn=Ke(),an=Ki(),Rg=Aa(),$g=wa(),wl="Object already initialized",sn=Rl.TypeError,Lg=Rl.WeakMap,Ra,Zi,$a,Mg=function(r){return $a(r)?Zi(r):Ra(r,{})},Cg=function(r){return function(e){var t;if(!Ag(e)||(t=Zi(e)).type!==r)throw new sn("Incompatible receiver, "+r+" required");return t}};kg||an.state?(Je=an.state||(an.state=new Lg),Je.get=Je.get,Je.has=Je.has,Je.set=Je.set,Ra=function(r,e){if(Je.has(r))throw new sn(wl);return e.facade=r,Je.set(r,e),e},Zi=function(r){return Je.get(r)||{}},$a=function(r){return Je.has(r)}):(Wt=Rg("state"),$g[Wt]=!0,Ra=function(r,e){if(rn(r,Wt))throw new sn(wl);return e.facade=r,wg(r,Wt,e),e},Zi=function(r){return rn(r,Wt)?r[Wt]:{}},$a=function(r){return rn(r,Wt)});var Je,Wt;$l.exports={set:Ra,get:Zi,has:$a,enforce:Mg,getterFor:Cg}});var on=b((ak,Dl)=>{"use strict";var Dg=ji(),Cl=Function.prototype,Ll=Cl.apply,Ml=Cl.call;Dl.exports=typeof Reflect=="object"&&Reflect.apply||(Dg?Ml.bind(Ll):function(){return Ml.apply(Ll,arguments)})});var un=b((sk,Vl)=>{"use strict";var Vg=di(),Bg=ve();Vl.exports=function(r){if(Vg(r)==="Function")return Bg(r)}});var Nl=b(_l=>{"use strict";var Bl={}.propertyIsEnumerable,Ol=Object.getOwnPropertyDescriptor,Og=Ol&&!Bl.call({1:2},1);_l.f=Og?function(e){var t=Ol(this,e);return!!t&&t.enumerable}:Bl});var Ul=b(ql=>{"use strict";var _g=_e(),Ng=$e(),Fg=Nl(),qg=Xi(),Ug=hi(),Hg=Js(),jg=Ke(),Gg=Bs(),Fl=Object.getOwnPropertyDescriptor;ql.f=_g?Fl:function(e,t){if(e=Ug(e),t=Hg(t),Gg)try{return Fl(e,t)}catch{}if(jg(e,t))return qg(!Ng(Fg.f,e,t),e[t])}});var ln=b((uk,Hl)=>{"use strict";var Qg=Re(),Wg=ae(),Yg=/#|\.prototype\./,er=function(r,e){var t=Kg[zg(r)];return t===Xg?!0:t===Jg?!1:Wg(e)?Qg(e):!!e},zg=er.normalize=function(r){return String(r).replace(Yg,".").toLowerCase()},Kg=er.data={},Jg=er.NATIVE="N",Xg=er.POLYFILL="P";Hl.exports=er});var tr=b((lk,Gl)=>{"use strict";var jl=un(),Zg=bt(),eS=ji(),tS=jl(jl.bind);Gl.exports=function(r,e){return Zg(r),e===void 0?r:eS?tS(r,e):function(){return r.apply(e,arguments)}}});var Ne=b((ck,Wl)=>{"use strict";var ir=se(),iS=on(),rS=un(),aS=ae(),sS=Ul().f,nS=ln(),gi=xa(),oS=tr(),Si=bi(),Ql=Ke();Ki();var uS=function(r){var e=function(t,i,a){if(this instanceof e){switch(arguments.length){case 0:return new r;case 1:return new r(t);case 2:return new r(t,i)}return new r(t,i,a)}return iS(r,this,arguments)};return e.prototype=r.prototype,e};Wl.exports=function(r,e){var t=r.target,i=r.global,a=r.stat,s=r.proto,n=i?ir:a?ir[t]:ir[t]&&ir[t].prototype,o=i?gi:gi[t]||Si(gi,t,{})[t],u=o.prototype,l,c,d,h,m,f,g,y,I;for(h in e)l=nS(i?h:t+(a?".":"#")+h,r.forced),c=!l&&n&&Ql(n,h),f=o[h],c&&(r.dontCallGetSet?(I=sS(n,h),g=I&&I.value):g=n[h]),m=c&&g?g:e[h],!(!l&&!s&&typeof f==typeof m)&&(r.bind&&c?y=oS(m,ir):r.wrap&&c?y=uS(m):s&&aS(m)?y=rS(m):y=m,(r.sham||m&&m.sham||f&&f.sham)&&Si(y,"sham",!0),Si(o,h,y),s&&(d=t+"Prototype",Ql(gi,d)||Si(gi,d,{}),Si(gi[d],h,m),r.real&&u&&(l||!u[h])&&Si(u,h,m)))}});var Kl=b((dk,zl)=>{"use strict";var cn=_e(),lS=Ke(),Yl=Function.prototype,cS=cn&&Object.getOwnPropertyDescriptor,dn=lS(Yl,"name"),dS=dn&&function(){}.name==="something",pS=dn&&(!cn||cn&&cS(Yl,"name").configurable);zl.exports={EXISTS:dn,PROPER:dS,CONFIGURABLE:pS}});var Xl=b((pk,Jl)=>{"use strict";var hS=Math.ceil,mS=Math.floor;Jl.exports=Math.trunc||function(e){var t=+e;return(t>0?mS:hS)(t)}});var La=b((hk,Zl)=>{"use strict";var fS=Xl();Zl.exports=function(r){var e=+r;return e!==e||e===0?0:fS(e)}});var tc=b((mk,ec)=>{"use strict";var bS=La(),gS=Math.max,SS=Math.min;ec.exports=function(r,e){var t=bS(r);return t<0?gS(t+e,0):SS(t,e)}});var rc=b((fk,ic)=>{"use strict";var vS=La(),yS=Math.min;ic.exports=function(r){var e=vS(r);return e>0?yS(e,9007199254740991):0}});var Ma=b((bk,ac)=>{"use strict";var TS=rc();ac.exports=function(r){return TS(r.length)}});var oc=b((gk,nc)=>{"use strict";var IS=hi(),ES=tc(),xS=Ma(),sc=function(r){return function(e,t,i){var a=IS(e),s=xS(a);if(s===0)return!r&&-1;var n=ES(i,s),o;if(r&&t!==t){for(;s>n;)if(o=a[n++],o!==o)return!0}else for(;s>n;n++)if((r||n in a)&&a[n]===t)return r||n||0;return!r&&-1}};nc.exports={includes:sc(!0),indexOf:sc(!1)}});var cc=b((Sk,lc)=>{"use strict";var PS=ve(),pn=Ke(),kS=hi(),AS=oc().indexOf,wS=wa(),uc=PS([].push);lc.exports=function(r,e){var t=kS(r),i=0,a=[],s;for(s in t)!pn(wS,s)&&pn(t,s)&&uc(a,s);for(;e.length>i;)pn(t,s=e[i++])&&(~AS(a,s)||uc(a,s));return a}});var hn=b((vk,dc)=>{"use strict";dc.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var hc=b((yk,pc)=>{"use strict";var RS=cc(),$S=hn();pc.exports=Object.keys||function(e){return RS(e,$S)}});var fc=b(mc=>{"use strict";var LS=_e(),MS=Os(),CS=Qt(),DS=at(),VS=hi(),BS=hc();mc.f=LS&&!MS?Object.defineProperties:function(e,t){DS(e);for(var i=VS(t),a=BS(t),s=a.length,n=0,o;s>n;)CS.f(e,o=a[n++],i[o]);return e}});var mn=b((Ik,bc)=>{"use strict";var OS=ft();bc.exports=OS("document","documentElement")});var Sn=b((Ek,Ec)=>{"use strict";var _S=at(),NS=fc(),gc=hn(),FS=wa(),qS=mn(),US=Ia(),HS=Aa(),Sc=">",vc="<",bn="prototype",gn="script",Tc=HS("IE_PROTO"),fn=function(){},Ic=function(r){return vc+gn+Sc+r+vc+"/"+gn+Sc},yc=function(r){r.write(Ic("")),r.close();var e=r.parentWindow.Object;return r=null,e},jS=function(){var r=US("iframe"),e="java"+gn+":",t;return r.style.display="none",qS.appendChild(r),r.src=String(e),t=r.contentWindow.document,t.open(),t.write(Ic("document.F=Object")),t.close(),t.F},Ca,Da=function(){try{Ca=new ActiveXObject("htmlfile")}catch{}Da=typeof document<"u"?document.domain&&Ca?yc(Ca):jS():yc(Ca);for(var r=gc.length;r--;)delete Da[bn][gc[r]];return Da()};FS[Tc]=!0;Ec.exports=Object.create||function(e,t){var i;return e!==null?(fn[bn]=_S(e),i=new fn,fn[bn]=null,i[Tc]=e):i=Da(),t===void 0?i:NS.f(i,t)}});var Pc=b((xk,xc)=>{"use strict";var GS=Re();xc.exports=!GS(function(){function r(){}return r.prototype.constructor=null,Object.getPrototypeOf(new r)!==r.prototype})});var yn=b((Pk,Ac)=>{"use strict";var QS=Ke(),WS=ae(),YS=Ji(),zS=Aa(),KS=Pc(),kc=zS("IE_PROTO"),vn=Object,JS=vn.prototype;Ac.exports=KS?vn.getPrototypeOf:function(r){var e=YS(r);if(QS(e,kc))return e[kc];var t=e.constructor;return WS(t)&&e instanceof t?t.prototype:e instanceof vn?JS:null}});var vi=b((kk,wc)=>{"use strict";var XS=bi();wc.exports=function(r,e,t,i){return i&&i.enumerable?r[e]=t:XS(r,e,t),r}});var xn=b((Ak,Lc)=>{"use strict";var ZS=Re(),ev=ae(),tv=Oe(),iv=Sn(),Rc=yn(),rv=vi(),av=be(),sv=ze(),En=av("iterator"),$c=!1,gt,Tn,In;[].keys&&(In=[].keys(),"next"in In?(Tn=Rc(Rc(In)),Tn!==Object.prototype&&(gt=Tn)):$c=!0);var nv=!tv(gt)||ZS(function(){var r={};return gt[En].call(r)!==r});nv?gt={}:sv&&(gt=iv(gt));ev(gt[En])||rv(gt,En,function(){return this});Lc.exports={IteratorPrototype:gt,BUGGY_SAFARI_ITERATORS:$c}});var Va=b((wk,Cc)=>{"use strict";var ov=be(),uv=ov("toStringTag"),Mc={};Mc[uv]="z";Cc.exports=String(Mc)==="[object z]"});var rr=b((Rk,Dc)=>{"use strict";var lv=Va(),cv=ae(),Ba=di(),dv=be(),pv=dv("toStringTag"),hv=Object,mv=Ba(function(){return arguments}())==="Arguments",fv=function(r,e){try{return r[e]}catch{}};Dc.exports=lv?Ba:function(r){var e,t,i;return r===void 0?"Undefined":r===null?"Null":typeof(t=fv(e=hv(r),pv))=="string"?t:mv?Ba(e):(i=Ba(e))==="Object"&&cv(e.callee)?"Arguments":i}});var Bc=b(($k,Vc)=>{"use strict";var bv=Va(),gv=rr();Vc.exports=bv?{}.toString:function(){return"[object "+gv(this)+"]"}});var ar=b((Lk,_c)=>{"use strict";var Sv=Va(),vv=Qt().f,yv=bi(),Tv=Ke(),Iv=Bc(),Ev=be(),Oc=Ev("toStringTag");_c.exports=function(r,e,t,i){var a=t?r:r&&r.prototype;a&&(Tv(a,Oc)||vv(a,Oc,{configurable:!0,value:e}),i&&!Sv&&yv(a,"toString",Iv))}});var Fc=b((Mk,Nc)=>{"use strict";var xv=xn().IteratorPrototype,Pv=Sn(),kv=Xi(),Av=ar(),wv=Gt(),Rv=function(){return this};Nc.exports=function(r,e,t,i){var a=e+" Iterator";return r.prototype=Pv(xv,{next:kv(+!i,t)}),Av(r,a,!1,!0),wv[a]=Rv,r}});var Uc=b((Ck,qc)=>{"use strict";var $v=ve(),Lv=bt();qc.exports=function(r,e,t){try{return $v(Lv(Object.getOwnPropertyDescriptor(r,e)[t]))}catch{}}});var jc=b((Dk,Hc)=>{"use strict";var Mv=Oe();Hc.exports=function(r){return Mv(r)||r===null}});var Qc=b((Vk,Gc)=>{"use strict";var Cv=jc(),Dv=String,Vv=TypeError;Gc.exports=function(r){if(Cv(r))return r;throw new Vv("Can't set "+Dv(r)+" as a prototype")}});var Pn=b((Bk,Wc)=>{"use strict";var Bv=Uc(),Ov=Oe(),_v=Gi(),Nv=Qc();Wc.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var r=!1,e={},t;try{t=Bv(Object.prototype,"__proto__","set"),t(e,[]),r=e instanceof Array}catch{}return function(a,s){return _v(a),Nv(s),Ov(a)&&(r?t(a,s):a.__proto__=s),a}}():void 0)});var ad=b((Ok,rd)=>{"use strict";var Fv=Ne(),qv=$e(),Oa=ze(),td=Kl(),Uv=ae(),Hv=Fc(),Yc=yn(),zc=Pn(),jv=ar(),Gv=bi(),kn=vi(),Qv=be(),Kc=Gt(),id=xn(),Wv=td.PROPER,Yv=td.CONFIGURABLE,Jc=id.IteratorPrototype,_a=id.BUGGY_SAFARI_ITERATORS,sr=Qv("iterator"),Xc="keys",nr="values",Zc="entries",ed=function(){return this};rd.exports=function(r,e,t,i,a,s,n){Hv(t,e,i);var o=function(I){if(I===a&&h)return h;if(!_a&&I&&I in c)return c[I];switch(I){case Xc:return function(){return new t(this,I)};case nr:return function(){return new t(this,I)};case Zc:return function(){return new t(this,I)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=r.prototype,d=c[sr]||c["@@iterator"]||a&&c[a],h=!_a&&d||o(a),m=e==="Array"&&c.entries||d,f,g,y;if(m&&(f=Yc(m.call(new r)),f!==Object.prototype&&f.next&&(!Oa&&Yc(f)!==Jc&&(zc?zc(f,Jc):Uv(f[sr])||kn(f,sr,ed)),jv(f,u,!0,!0),Oa&&(Kc[u]=ed))),Wv&&a===nr&&d&&d.name!==nr&&(!Oa&&Yv?Gv(c,"name",nr):(l=!0,h=function(){return qv(d,this)})),a)if(g={values:o(nr),keys:s?h:o(Xc),entries:o(Zc)},n)for(y in g)(_a||l||!(y in c))&&kn(c,y,g[y]);else Fv({target:e,proto:!0,forced:_a||l},g);return(!Oa||n)&&c[sr]!==h&&kn(c,sr,h,{name:a}),Kc[e]=h,g}});var nd=b((_k,sd)=>{"use strict";sd.exports=function(r,e){return{value:r,done:e}}});var wn=b((Nk,dd)=>{"use strict";var zv=hi(),An=Ms(),od=Gt(),ld=nn(),Kv=Qt().f,Jv=ad(),Na=nd(),Xv=ze(),Zv=_e(),cd="Array Iterator",ey=ld.set,ty=ld.getterFor(cd);dd.exports=Jv(Array,"Array",function(r,e){ey(this,{type:cd,target:zv(r),index:0,kind:e})},function(){var r=ty(this),e=r.target,t=r.index++;if(!e||t>=e.length)return r.target=void 0,Na(void 0,!0);switch(r.kind){case"keys":return Na(t,!1);case"values":return Na(e[t],!1)}return Na([t,e[t]],!1)},"values");var ud=od.Arguments=od.Array;An("keys");An("values");An("entries");if(!Xv&&Zv&&ud.name!=="values")try{Kv(ud,"name",{value:"values"})}catch{}});var hd=b((Fk,pd)=>{"use strict";var iy=be(),ry=Gt(),ay=iy("iterator"),sy=Array.prototype;pd.exports=function(r){return r!==void 0&&(ry.Array===r||sy[ay]===r)}});var Rn=b((qk,fd)=>{"use strict";var ny=rr(),md=zi(),oy=pi(),uy=Gt(),ly=be(),cy=ly("iterator");fd.exports=function(r){if(!oy(r))return md(r,cy)||md(r,"@@iterator")||uy[ny(r)]}});var gd=b((Uk,bd)=>{"use strict";var dy=$e(),py=bt(),hy=at(),my=Yi(),fy=Rn(),by=TypeError;bd.exports=function(r,e){var t=arguments.length<2?fy(r):e;if(py(t))return hy(dy(t,r));throw new by(my(r)+" is not iterable")}});var yd=b((Hk,vd)=>{"use strict";var gy=$e(),Sd=at(),Sy=zi();vd.exports=function(r,e,t){var i,a;Sd(r);try{if(i=Sy(r,"return"),!i){if(e==="throw")throw t;return t}i=gy(i,r)}catch(s){a=!0,i=s}if(e==="throw")throw t;if(a)throw i;return Sd(i),t}});var qa=b((jk,xd)=>{"use strict";var vy=tr(),yy=$e(),Ty=at(),Iy=Yi(),Ey=hd(),xy=Ma(),Td=Wi(),Py=gd(),ky=Rn(),Id=yd(),Ay=TypeError,Fa=function(r,e){this.stopped=r,this.result=e},Ed=Fa.prototype;xd.exports=function(r,e,t){var i=t&&t.that,a=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=vy(e,i),l,c,d,h,m,f,g,y=function(P){return l&&Id(l,"normal",P),new Fa(!0,P)},I=function(P){return a?(Ty(P),o?u(P[0],P[1],y):u(P[0],P[1])):o?u(P,y):u(P)};if(s)l=r.iterator;else if(n)l=r;else{if(c=ky(r),!c)throw new Ay(Iy(r)+" is not iterable");if(Ey(c)){for(d=0,h=xy(r);h>d;d++)if(m=I(r[d]),m&&Td(Ed,m))return m;return new Fa(!1)}l=Py(r,c)}for(f=s?r.next:l.next;!(g=yy(f,l)).done;){try{m=I(g.value)}catch(P){Id(l,"throw",P)}if(typeof m=="object"&&m&&Td(Ed,m))return m}return new Fa(!1)}});var kd=b((Gk,Pd)=>{"use strict";var wy=_e(),Ry=Qt(),$y=Xi();Pd.exports=function(r,e,t){wy?Ry.f(r,e,$y(0,t)):r[e]=t}});var Ad=b(()=>{"use strict";var Ly=Ne(),My=qa(),Cy=kd();Ly({target:"Object",stat:!0},{fromEntries:function(e){var t={};return My(e,function(i,a){Cy(t,i,a)},{AS_ENTRIES:!0}),t}})});var Rd=b((Yk,wd)=>{"use strict";wn();Ad();var Dy=xa();wd.exports=Dy.Object.fromEntries});var Ld=b((zk,$d)=>{"use strict";$d.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 Cd=b(()=>{"use strict";wn();var Vy=Ld(),By=se(),Oy=ar(),Md=Gt();for(Ua in Vy)Oy(By[Ua],Ua),Md[Ua]=Md.Array;var Ua});var Vd=b((Xk,Dd)=>{"use strict";var _y=Rd();Cd();Dd.exports=_y});var $n=b((Zk,Bd)=>{"use strict";var Ny=Vd();Bd.exports=Ny});var Od=b(()=>{"use strict"});var Ln=b((iA,_d)=>{"use strict";var or=se(),Fy=mi(),qy=di(),Ha=function(r){return Fy.slice(0,r.length)===r};_d.exports=function(){return Ha("Bun/")?"BUN":Ha("Cloudflare-Workers")?"CLOUDFLARE":Ha("Deno/")?"DENO":Ha("Node.js/")?"NODE":or.Bun&&typeof Bun.version=="string"?"BUN":or.Deno&&typeof Deno.version=="object"?"DENO":qy(or.process)==="process"?"NODE":or.window&&or.document?"BROWSER":"REST"}()});var ja=b((rA,Nd)=>{"use strict";var Uy=Ln();Nd.exports=Uy==="NODE"});var qd=b((aA,Fd)=>{"use strict";var Hy=Qt();Fd.exports=function(r,e,t){return Hy.f(r,e,t)}});var jd=b((sA,Hd)=>{"use strict";var jy=ft(),Gy=qd(),Qy=be(),Wy=_e(),Ud=Qy("species");Hd.exports=function(r){var e=jy(r);Wy&&e&&!e[Ud]&&Gy(e,Ud,{configurable:!0,get:function(){return this}})}});var Qd=b((nA,Gd)=>{"use strict";var Yy=Wi(),zy=TypeError;Gd.exports=function(r,e){if(Yy(e,r))return r;throw new zy("Incorrect invocation")}});var Cn=b((oA,Wd)=>{"use strict";var Ky=ve(),Jy=ae(),Mn=Ki(),Xy=Ky(Function.toString);Jy(Mn.inspectSource)||(Mn.inspectSource=function(r){return Xy(r)});Wd.exports=Mn.inspectSource});var Zd=b((uA,Xd)=>{"use strict";var Zy=ve(),eT=Re(),Yd=ae(),tT=rr(),iT=ft(),rT=Cn(),zd=function(){},Kd=iT("Reflect","construct"),Dn=/^\s*(?:class|function)\b/,aT=Zy(Dn.exec),sT=!Dn.test(zd),ur=function(e){if(!Yd(e))return!1;try{return Kd(zd,[],e),!0}catch{return!1}},Jd=function(e){if(!Yd(e))return!1;switch(tT(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return sT||!!aT(Dn,rT(e))}catch{return!0}};Jd.sham=!0;Xd.exports=!Kd||eT(function(){var r;return ur(ur.call)||!ur(Object)||!ur(function(){r=!0})||r})?Jd:ur});var tp=b((lA,ep)=>{"use strict";var nT=Zd(),oT=Yi(),uT=TypeError;ep.exports=function(r){if(nT(r))return r;throw new uT(oT(r)+" is not a constructor")}});var Vn=b((cA,rp)=>{"use strict";var ip=at(),lT=tp(),cT=pi(),dT=be(),pT=dT("species");rp.exports=function(r,e){var t=ip(r).constructor,i;return t===void 0||cT(i=ip(t)[pT])?e:lT(i)}});var sp=b((dA,ap)=>{"use strict";var hT=ve();ap.exports=hT([].slice)});var op=b((pA,np)=>{"use strict";var mT=TypeError;np.exports=function(r,e){if(r<e)throw new mT("Not enough arguments");return r}});var Bn=b((hA,up)=>{"use strict";var fT=mi();up.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(fT)});var Gn=b((mA,gp)=>{"use strict";var Le=se(),bT=on(),gT=tr(),lp=ae(),ST=Ke(),bp=Re(),cp=mn(),vT=sp(),dp=Ia(),yT=op(),TT=Bn(),IT=ja(),Un=Le.setImmediate,Hn=Le.clearImmediate,ET=Le.process,On=Le.Dispatch,xT=Le.Function,pp=Le.MessageChannel,PT=Le.String,_n=0,lr={},hp="onreadystatechange",cr,Yt,Nn,Fn;bp(function(){cr=Le.location});var jn=function(r){if(ST(lr,r)){var e=lr[r];delete lr[r],e()}},qn=function(r){return function(){jn(r)}},mp=function(r){jn(r.data)},fp=function(r){Le.postMessage(PT(r),cr.protocol+"//"+cr.host)};(!Un||!Hn)&&(Un=function(e){yT(arguments.length,1);var t=lp(e)?e:xT(e),i=vT(arguments,1);return lr[++_n]=function(){bT(t,void 0,i)},Yt(_n),_n},Hn=function(e){delete lr[e]},IT?Yt=function(r){ET.nextTick(qn(r))}:On&&On.now?Yt=function(r){On.now(qn(r))}:pp&&!TT?(Nn=new pp,Fn=Nn.port2,Nn.port1.onmessage=mp,Yt=gT(Fn.postMessage,Fn)):Le.addEventListener&&lp(Le.postMessage)&&!Le.importScripts&&cr&&cr.protocol!=="file:"&&!bp(fp)?(Yt=fp,Le.addEventListener("message",mp,!1)):hp in dp("script")?Yt=function(r){cp.appendChild(dp("script"))[hp]=function(){cp.removeChild(this),jn(r)}}:Yt=function(r){setTimeout(qn(r),0)});gp.exports={set:Un,clear:Hn}});var yp=b((fA,vp)=>{"use strict";var Sp=se(),kT=_e(),AT=Object.getOwnPropertyDescriptor;vp.exports=function(r){if(!kT)return Sp[r];var e=AT(Sp,r);return e&&e.value}});var Qn=b((bA,Ip)=>{"use strict";var Tp=function(){this.head=null,this.tail=null};Tp.prototype={add:function(r){var e={item:r,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var r=this.head;if(r){var e=this.head=r.next;return e===null&&(this.tail=null),r.item}}};Ip.exports=Tp});var xp=b((gA,Ep)=>{"use strict";var wT=mi();Ep.exports=/ipad|iphone|ipod/i.test(wT)&&typeof Pebble<"u"});var kp=b((SA,Pp)=>{"use strict";var RT=mi();Pp.exports=/web0s(?!.*chrome)/i.test(RT)});var Cp=b((vA,Mp)=>{"use strict";var Ti=se(),$T=yp(),Ap=tr(),Wn=Gn().set,LT=Qn(),MT=Bn(),CT=xp(),DT=kp(),Yn=ja(),wp=Ti.MutationObserver||Ti.WebKitMutationObserver,Rp=Ti.document,$p=Ti.process,Ga=Ti.Promise,Jn=$T("queueMicrotask"),yi,zn,Kn,Qa,Lp;Jn||(dr=new LT,pr=function(){var r,e;for(Yn&&(r=$p.domain)&&r.exit();e=dr.get();)try{e()}catch(t){throw dr.head&&yi(),t}r&&r.enter()},!MT&&!Yn&&!DT&&wp&&Rp?(zn=!0,Kn=Rp.createTextNode(""),new wp(pr).observe(Kn,{characterData:!0}),yi=function(){Kn.data=zn=!zn}):!CT&&Ga&&Ga.resolve?(Qa=Ga.resolve(void 0),Qa.constructor=Ga,Lp=Ap(Qa.then,Qa),yi=function(){Lp(pr)}):Yn?yi=function(){$p.nextTick(pr)}:(Wn=Ap(Wn,Ti),yi=function(){Wn(pr)}),Jn=function(r){dr.head||yi(),dr.add(r)});var dr,pr;Mp.exports=Jn});var Vp=b((yA,Dp)=>{"use strict";Dp.exports=function(r,e){try{arguments.length===1?console.error(r):console.error(r,e)}catch{}}});var Wa=b((TA,Bp)=>{"use strict";Bp.exports=function(r){try{return{error:!1,value:r()}}catch(e){return{error:!0,value:e}}}});var zt=b((IA,Op)=>{"use strict";var VT=se();Op.exports=VT.Promise});var Ii=b((EA,qp)=>{"use strict";var BT=se(),hr=zt(),OT=ae(),_T=ln(),NT=Cn(),FT=be(),_p=Ln(),qT=ze(),Xn=qs(),Np=hr&&hr.prototype,UT=FT("species"),Zn=!1,Fp=OT(BT.PromiseRejectionEvent),HT=_T("Promise",function(){var r=NT(hr),e=r!==String(hr);if(!e&&Xn===66||qT&&!(Np.catch&&Np.finally))return!0;if(!Xn||Xn<51||!/native code/.test(r)){var t=new hr(function(s){s(1)}),i=function(s){s(function(){},function(){})},a=t.constructor={};if(a[UT]=i,Zn=t.then(function(){})instanceof i,!Zn)return!0}return!e&&(_p==="BROWSER"||_p==="DENO")&&!Fp});qp.exports={CONSTRUCTOR:HT,REJECTION_EVENT:Fp,SUBCLASSING:Zn}});var Ei=b((xA,Hp)=>{"use strict";var Up=bt(),jT=TypeError,GT=function(r){var e,t;this.promise=new r(function(i,a){if(e!==void 0||t!==void 0)throw new jT("Bad Promise constructor");e=i,t=a}),this.resolve=Up(e),this.reject=Up(t)};Hp.exports.f=function(r){return new GT(r)}});var uh=b(()=>{"use strict";var QT=Ne(),WT=ze(),Ja=ja(),Lt=se(),Ai=$e(),jp=vi(),Gp=Pn(),YT=ar(),zT=jd(),KT=bt(),Ka=ae(),JT=Oe(),XT=Qd(),ZT=Vn(),Kp=Gn().set,ao=Cp(),eI=Vp(),tI=Wa(),iI=Qn(),Jp=nn(),Xa=zt(),so=Ii(),Xp=Ei(),Za="Promise",Zp=so.CONSTRUCTOR,rI=so.REJECTION_EVENT,aI=so.SUBCLASSING,eo=Jp.getterFor(Za),sI=Jp.set,xi=Xa&&Xa.prototype,Kt=Xa,Ya=xi,eh=Lt.TypeError,to=Lt.document,no=Lt.process,io=Xp.f,nI=io,oI=!!(to&&to.createEvent&&Lt.dispatchEvent),th="unhandledrejection",uI="rejectionhandled",Qp=0,ih=1,lI=2,oo=1,rh=2,za,Wp,cI,Yp,ah=function(r){var e;return JT(r)&&Ka(e=r.then)?e:!1},sh=function(r,e){var t=e.value,i=e.state===ih,a=i?r.ok:r.fail,s=r.resolve,n=r.reject,o=r.domain,u,l,c;try{a?(i||(e.rejection===rh&&pI(e),e.rejection=oo),a===!0?u=t:(o&&o.enter(),u=a(t),o&&(o.exit(),c=!0)),u===r.promise?n(new eh("Promise-chain cycle")):(l=ah(u))?Ai(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},nh=function(r,e){r.notified||(r.notified=!0,ao(function(){for(var t=r.reactions,i;i=t.get();)sh(i,r);r.notified=!1,e&&!r.rejection&&dI(r)}))},oh=function(r,e,t){var i,a;oI?(i=to.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(r,!1,!0),Lt.dispatchEvent(i)):i={promise:e,reason:t},!rI&&(a=Lt["on"+r])?a(i):r===th&&eI("Unhandled promise rejection",t)},dI=function(r){Ai(Kp,Lt,function(){var e=r.facade,t=r.value,i=zp(r),a;if(i&&(a=tI(function(){Ja?no.emit("unhandledRejection",t,e):oh(th,e,t)}),r.rejection=Ja||zp(r)?rh:oo,a.error))throw a.value})},zp=function(r){return r.rejection!==oo&&!r.parent},pI=function(r){Ai(Kp,Lt,function(){var e=r.facade;Ja?no.emit("rejectionHandled",e):oh(uI,e,r.value)})},Pi=function(r,e,t){return function(i){r(e,i,t)}},ki=function(r,e,t){r.done||(r.done=!0,t&&(r=t),r.value=e,r.state=lI,nh(r,!0))},ro=function(r,e,t){if(!r.done){r.done=!0,t&&(r=t);try{if(r.facade===e)throw new eh("Promise can't be resolved itself");var i=ah(e);i?ao(function(){var a={done:!1};try{Ai(i,e,Pi(ro,a,r),Pi(ki,a,r))}catch(s){ki(a,s,r)}}):(r.value=e,r.state=ih,nh(r,!1))}catch(a){ki({done:!1},a,r)}}};if(Zp&&(Kt=function(e){XT(this,Ya),KT(e),Ai(za,this);var t=eo(this);try{e(Pi(ro,t),Pi(ki,t))}catch(i){ki(t,i)}},Ya=Kt.prototype,za=function(e){sI(this,{type:Za,done:!1,notified:!1,parent:!1,reactions:new iI,rejection:!1,state:Qp,value:void 0})},za.prototype=jp(Ya,"then",function(e,t){var i=eo(this),a=io(ZT(this,Kt));return i.parent=!0,a.ok=Ka(e)?e:!0,a.fail=Ka(t)&&t,a.domain=Ja?no.domain:void 0,i.state===Qp?i.reactions.add(a):ao(function(){sh(a,i)}),a.promise}),Wp=function(){var r=new za,e=eo(r);this.promise=r,this.resolve=Pi(ro,e),this.reject=Pi(ki,e)},Xp.f=io=function(r){return r===Kt||r===cI?new Wp(r):nI(r)},!WT&&Ka(Xa)&&xi!==Object.prototype)){Yp=xi.then,aI||jp(xi,"then",function(e,t){var i=this;return new Kt(function(a,s){Ai(Yp,i,a,s)}).then(e,t)},{unsafe:!0});try{delete xi.constructor}catch{}Gp&&Gp(xi,Ya)}QT({global:!0,constructor:!0,wrap:!0,forced:Zp},{Promise:Kt});YT(Kt,Za,!1,!0);zT(Za)});var hh=b((AA,ph)=>{"use strict";var hI=be(),ch=hI("iterator"),dh=!1;try{lh=0,uo={next:function(){return{done:!!lh++}},return:function(){dh=!0}},uo[ch]=function(){return this},Array.from(uo,function(){throw 2})}catch{}var lh,uo;ph.exports=function(r,e){try{if(!e&&!dh)return!1}catch{return!1}var t=!1;try{var i={};i[ch]=function(){return{next:function(){return{done:t=!0}}}},r(i)}catch{}return t}});var lo=b((wA,mh)=>{"use strict";var mI=zt(),fI=hh(),bI=Ii().CONSTRUCTOR;mh.exports=bI||!fI(function(r){mI.all(r).then(void 0,function(){})})});var fh=b(()=>{"use strict";var gI=Ne(),SI=$e(),vI=bt(),yI=Ei(),TI=Wa(),II=qa(),EI=lo();gI({target:"Promise",stat:!0,forced:EI},{all:function(e){var t=this,i=yI.f(t),a=i.resolve,s=i.reject,n=TI(function(){var o=vI(t.resolve),u=[],l=0,c=1;II(e,function(d){var h=l++,m=!1;c++,SI(o,t,d).then(function(f){m||(m=!0,u[h]=f,--c||a(u))},s)}),--c||a(u)});return n.error&&s(n.value),i.promise}})});var gh=b(()=>{"use strict";var xI=Ne(),PI=ze(),kI=Ii().CONSTRUCTOR,po=zt(),AI=ft(),wI=ae(),RI=vi(),bh=po&&po.prototype;xI({target:"Promise",proto:!0,forced:kI,real:!0},{catch:function(r){return this.then(void 0,r)}});!PI&&wI(po)&&(co=AI("Promise").prototype.catch,bh.catch!==co&&RI(bh,"catch",co,{unsafe:!0}));var co});var Sh=b(()=>{"use strict";var $I=Ne(),LI=$e(),MI=bt(),CI=Ei(),DI=Wa(),VI=qa(),BI=lo();$I({target:"Promise",stat:!0,forced:BI},{race:function(e){var t=this,i=CI.f(t),a=i.reject,s=DI(function(){var n=MI(t.resolve);VI(e,function(o){LI(n,t,o).then(i.resolve,a)})});return s.error&&a(s.value),i.promise}})});var vh=b(()=>{"use strict";var OI=Ne(),_I=Ei(),NI=Ii().CONSTRUCTOR;OI({target:"Promise",stat:!0,forced:NI},{reject:function(e){var t=_I.f(this),i=t.reject;return i(e),t.promise}})});var ho=b((OA,yh)=>{"use strict";var FI=at(),qI=Oe(),UI=Ei();yh.exports=function(r,e){if(FI(r),qI(e)&&e.constructor===r)return e;var t=UI.f(r),i=t.resolve;return i(e),t.promise}});var Eh=b(()=>{"use strict";var HI=Ne(),jI=ft(),Th=ze(),GI=zt(),Ih=Ii().CONSTRUCTOR,QI=ho(),WI=jI("Promise"),YI=Th&&!Ih;HI({target:"Promise",stat:!0,forced:Th||Ih},{resolve:function(e){return QI(YI&&this===WI?GI:this,e)}})});var xh=b(()=>{"use strict";uh();fh();gh();Sh();vh();Eh()});var wh=b(()=>{"use strict";var zI=Ne(),KI=ze(),es=zt(),JI=Re(),kh=ft(),Ah=ae(),XI=Vn(),Ph=ho(),ZI=vi(),fo=es&&es.prototype,eE=!!es&&JI(function(){fo.finally.call({then:function(){}},function(){})});zI({target:"Promise",proto:!0,real:!0,forced:eE},{finally:function(r){var e=XI(this,kh("Promise")),t=Ah(r);return this.then(t?function(i){return Ph(e,r()).then(function(){return i})}:r,t?function(i){return Ph(e,r()).then(function(){throw i})}:r)}});!KI&&Ah(es)&&(mo=kh("Promise").prototype.finally,fo.finally!==mo&&ZI(fo,"finally",mo,{unsafe:!0}));var mo});var ts=b((jA,Rh)=>{"use strict";var tE=ft();Rh.exports=tE});var Lh=b((GA,$h)=>{"use strict";Od();xh();wh();var iE=ts();$h.exports=iE("Promise","finally")});var Ch=b((QA,Mh)=>{"use strict";var rE=Lh();Mh.exports=rE});var is=b((WA,Dh)=>{"use strict";var aE=Ch();Dh.exports=aE});var jh=b(()=>{"use strict";var pE=Ne(),hE=Ji(),mE=Ma(),fE=La(),bE=Ms();pE({target:"Array",proto:!0},{at:function(e){var t=hE(this),i=mE(t),a=fE(e),s=a>=0?a:i+a;return s<0||s>=i?void 0:t[s]}});bE("at")});var Qh=b((Gw,Gh)=>{"use strict";jh();var gE=ts();Gh.exports=gE("Array","at")});var Yh=b((Qw,Wh)=>{"use strict";var SE=Qh();Wh.exports=SE});var wi=b((Ww,zh)=>{"use strict";var vE=Yh();zh.exports=vE});var Mm=b(()=>{"use strict"});var Cm=b(()=>{"use strict"});var Vm=b((_M,Dm)=>{"use strict";var tx=Oe(),ix=di(),rx=be(),ax=rx("match");Dm.exports=function(r){var e;return tx(r)&&((e=r[ax])!==void 0?!!e:ix(r)==="RegExp")}});var Om=b((NM,Bm)=>{"use strict";var sx=rr(),nx=String;Bm.exports=function(r){if(sx(r)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return nx(r)}});var Nm=b((FM,_m)=>{"use strict";var ox=at();_m.exports=function(){var r=ox(this),e="";return r.hasIndices&&(e+="d"),r.global&&(e+="g"),r.ignoreCase&&(e+="i"),r.multiline&&(e+="m"),r.dotAll&&(e+="s"),r.unicode&&(e+="u"),r.unicodeSets&&(e+="v"),r.sticky&&(e+="y"),e}});var Um=b((qM,qm)=>{"use strict";var ux=$e(),lx=Ke(),cx=Wi(),dx=Nm(),Fm=RegExp.prototype;qm.exports=function(r){var e=r.flags;return e===void 0&&!("flags"in Fm)&&!lx(r,"flags")&&cx(Fm,r)?ux(dx,r):e}});var jm=b((UM,Hm)=>{"use strict";var _o=ve(),px=Ji(),hx=Math.floor,Bo=_o("".charAt),mx=_o("".replace),Oo=_o("".slice),fx=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,bx=/\$([$&'`]|\d{1,2})/g;Hm.exports=function(r,e,t,i,a,s){var n=t+r.length,o=i.length,u=bx;return a!==void 0&&(a=px(a),u=fx),mx(s,u,function(l,c){var d;switch(Bo(c,0)){case"$":return"$";case"&":return r;case"`":return Oo(e,0,t);case"'":return Oo(e,n);case"<":d=a[Oo(c,1,-1)];break;default:var h=+c;if(h===0)return l;if(h>o){var m=hx(h/10);return m===0?l:m<=o?i[m-1]===void 0?Bo(c,1):i[m-1]+Bo(c,1):l}d=i[h-1]}return d===void 0?"":d})}});var Wm=b(()=>{"use strict";var gx=Ne(),Sx=$e(),Fo=ve(),Gm=Gi(),vx=ae(),yx=pi(),Tx=Vm(),Vi=Om(),Ix=zi(),Ex=Um(),xx=jm(),Px=be(),kx=ze(),Ax=Px("replace"),wx=TypeError,No=Fo("".indexOf),Rx=Fo("".replace),Qm=Fo("".slice),$x=Math.max;gx({target:"String",proto:!0},{replaceAll:function(e,t){var i=Gm(this),a,s,n,o,u,l,c,d,h,m,f=0,g="";if(!yx(e)){if(a=Tx(e),a&&(s=Vi(Gm(Ex(e))),!~No(s,"g")))throw new wx("`.replaceAll` does not allow non-global regexes");if(n=Ix(e,Ax),n)return Sx(n,e,i,t);if(kx&&a)return Rx(Vi(i),e,t)}for(o=Vi(i),u=Vi(e),l=vx(t),l||(t=Vi(t)),c=u.length,d=$x(1,c),h=No(o,u);h!==-1;)m=l?Vi(t(u,h,o)):xx(u,o,h,[],void 0,t),g+=Qm(o,f,h)+m,f=h+c,h=h+d>o.length?-1:No(o,u,h+d);return f<o.length&&(g+=Qm(o,f)),g}})});var zm=b((GM,Ym)=>{"use strict";Mm();Cm();Wm();var Lx=ts();Ym.exports=Lx("String","replaceAll")});var Jm=b((QM,Km)=>{"use strict";var Mx=zm();Km.exports=Mx});var Zm=b((WM,Xm)=>{"use strict";var Cx=Jm();Xm.exports=Cx});var Jx={};Yf(Jx,{ChromecastState:()=>Hi,HttpConnectionType:()=>va,Observable:()=>ct.Observable,PlaybackState:()=>fe,Player:()=>da,SDK_VERSION:()=>Kx,Subject:()=>ct.Subject,Subscription:()=>ct.Subscription,Surface:()=>ya,VERSION:()=>Rs,ValueSubject:()=>ct.ValueSubject,VideoFormat:()=>mt,VideoQuality:()=>ct.VideoQuality});module.exports=zf(Jx);var Rs="2.0.118-dev.d798494f.0";var fe=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(fe||{}),mt=(k=>(k.MPEG="MPEG",k.DASH="DASH",k.DASH_SEP="DASH_SEP",k.DASH_SEP_VK="DASH_SEP",k.DASH_WEBM="DASH_WEBM",k.DASH_WEBM_AV1="DASH_WEBM_AV1",k.DASH_STREAMS="DASH_STREAMS",k.DASH_WEBM_VK="DASH_WEBM",k.DASH_ONDEMAND="DASH_ONDEMAND",k.DASH_ONDEMAND_VK="DASH_ONDEMAND",k.DASH_LIVE="DASH_LIVE",k.DASH_LIVE_CMAF="DASH_LIVE_CMAF",k.DASH_LIVE_WEBM="DASH_LIVE_WEBM",k.HLS="HLS",k.HLS_ONDEMAND="HLS_ONDEMAND",k.HLS_JS="HLS",k.HLS_LIVE="HLS_LIVE",k.HLS_LIVE_CMAF="HLS_LIVE_CMAF",k.WEB_RTC_LIVE="WEB_RTC_LIVE",k))(mt||{});var Hi=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(Hi||{}),va=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(va||{});var ya=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(ya||{});var F=require("@vkontakte/videoplayer-shared");var nu=r=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",r),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});var Ta=class{constructor(e){this.connection$=new F.ValueSubject(void 0);this.castState$=new F.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new F.Subject;this.realCastState$=new F.ValueSubject("NOT_AVAILABLE");this.subscription=new F.Subscription;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=(0,F.isNonNullable)(window.chrome?.cast),a=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},a||nu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:F.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,F.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,F.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,F.isNullable)(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add((0,F.fromEvent)(i,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=i.getCurrentSession()?.getMediaSession()?.media?.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return(0,F.assertNever)(a.sessionState)}})).add((0,F.merge)((0,F.fromEvent)(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,F.tap)(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),(0,F.map)(a=>a.castState)),(0,F.observableFrom)([i.getCastState()])).pipe((0,F.filterChanged)(),(0,F.map)(Kf),(0,F.tap)(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=(0,F.isNonNullable)(this.connection$.getValue());if(s&&!n){let o=i.getCurrentSession();(0,F.assertNonNullable)(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;((0,F.isNullable)(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a==="CONNECTED"?(0,F.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":a)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:F.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},Kf=r=>{switch(r){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return(0,F.assertNever)(r)}};var Af=Be($n(),1);var _h=Be(is(),1);var bo=require("@vkontakte/videoplayer-shared");var he=(r,e=0,t=0)=>{switch(t){case 0:return r.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return r;let i=new URL(r);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(r);return!i.searchParams.get("offset_p")&&e===0?r:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:(0,bo.assertNever)(t)}return r},go=(r,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(r);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(r);return Number(t.searchParams.get("offset_p")??0)}default:(0,bo.assertNever)(e)}};var w=(r,e,t=!1)=>{let i=r.getTransition();(t||!i||i.to===e)&&r.setState(e)};var st=require("@vkontakte/videoplayer-shared"),q=class{constructor(e){this.transitionStarted$=new st.Subject;this.transitionEnded$=new st.Subject;this.transitionUpdated$=new st.Subject;this.forceChanged$=new st.Subject;this.stateChangeStarted$=(0,st.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,st.merge)(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,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:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||(0,st.isNonNullable)(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};var Vh=require("@vkontakte/videoplayer-shared"),Bh=r=>{switch(r){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return(0,Vh.assertNever)(r)}};var $=require("@vkontakte/videoplayer-shared");var sE=5,nE=5,oE=500,Oh=7e3,mr=class{constructor(e){this.subscription=new $.Subscription;this.loadMediaTimeoutSubscription=new $.Subscription;this.videoState=new q("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=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: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="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(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,$.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,$.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,$.assertNever)(e)}break}default:(0,$.assertNever)(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Bh(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 $.Subscription;this.subscription.add(e),this.subscription.add((0,$.merge)(this.videoState.stateChangeStarted$.pipe((0,$.map)(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe((0,$.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 $.Subject;e.add(a.pipe((0,$.debounce)(oE)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,$.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)>sE)&&a.next(o),s=o})),e.add((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,$.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,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,$.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(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<nE&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),w(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,$.assertNever)(n)}}),t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let i=(0,$.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,$.observableFrom)(["init"])).pipe((0,$.debounce)(0));t(i,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"),w(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),w(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?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),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),w(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&w(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,i,a,s;switch(e){case"MPEG":{let l=t[e];(0,$.assertNonNullable)(l);let c=(0,$.getHighestQuality)(Object.keys(l));(0,$.assertNonNullable)(c);let d=l[c];(0,$.assertNonNullable)(d),i=d,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];(0,$.assertNonNullable)(l),i=l.url,a="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=t[e];(0,$.assertNonNullable)(l),i=l.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];(0,$.assertNonNullable)(l),i=l.url,a="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];(0,$.assertNonNullable)(l),i=he(l.url),a="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:$.ErrorCategory.VIDEO_PIPELINE,message:l,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,$.assertNever)(e)}let n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,a);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return(0,$.isNonNullable)(o)&&(n.metadata.title=o),(0,$.isNonNullable)(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((a,s)=>{this.loadMediaTimeoutSubscription.add((0,$.timeout)(Oh).subscribe(()=>s(`timeout(${Oh})`)))});(0,_h.default)(Promise.race([t,i]).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:$.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var To=require("@vkontakte/videoplayer-shared");var Nh=require("@vkontakte/videoplayer-shared"),Fh=r=>{try{r.pause(),r.playbackRate=0,(0,Nh.clearVideoElement)(r),r.remove()}catch(e){console.error(e)}};var rs=require("@vkontakte/videoplayer-shared"),So=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},vo=window.WeakMap?new WeakMap:new So,yo=window.WeakMap?new WeakMap:new Map,uE=(r,e=20)=>{let t=0;return(0,rs.fromEvent)(r,"ratechange").subscribe(i=>{t++,t>=e&&(r.currentTime=r.currentTime,t=0)})},ye=(r,{audioVideoSyncRate:e})=>{let t=r.querySelector("video"),i=!!t;t?(0,To.clearVideoElement)(t):(t=document.createElement("video"),r.appendChild(t)),vo.set(t,i);let a=new rs.Subscription;return a.add(uE(t,e)),yo.set(t,a),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},Te=r=>{yo.get(r)?.unsubscribe(),yo.delete(r);let t=vo.get(r);vo.delete(r),t?(0,To.clearVideoElement)(r):Fh(r)};var L=require("@vkontakte/videoplayer-shared");var Mt=require("@vkontakte/videoplayer-shared"),as=(r,e,t,{equal:i=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=r.getState(),o=e(),u=(0,Mt.isNullable)(a),l=new Mt.Subscription;return a&&l.add(a.subscribe(c=>{let d=r.getState();i(c,d)&&r.setState(c)},s)),i(o,n)||(t(n),u&&r.setState(n)),l.add(r.stateChangeStarted$.subscribe(c=>{t(c.to),u&&r.setState(c.to)},s)),l},nt=(r,e,t)=>as(e,()=>r.loop,i=>{(0,Mt.isNonNullable)(i)&&(r.loop=i)},{onError:t}),Ie=(r,e,t,i)=>as(e,()=>({muted:r.muted,volume:r.volume}),a=>{(0,Mt.isNonNullable)(a)&&(r.muted=a.muted,r.volume=a.volume)},{equal:(a,s)=>a===s||a?.muted===s?.muted&&a?.volume===s?.volume,changed$:t,onError:i}),Fe=(r,e,t,i)=>as(e,()=>r.playbackRate,a=>{(0,Mt.isNonNullable)(a)&&(r.playbackRate=a)},{changed$:t,onError:i}),Ct=as;var lE=r=>["__",r.language,r.label].join("|"),cE=(r,e)=>{if(r.id===e)return!0;let[t,i,a]=e.split("|");return r.language===i&&r.label===a},Io=class r{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,i){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(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Ct(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},u)=>o===n[u].id),changed$:this.available$.pipe((0,L.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(Ct(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},u)=>o===n[u].id),changed$:this.available$.pipe((0,L.map)(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(Ct(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(Ct(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 i=this.current$.getValue();i&&this.select(i)})),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(i=>this.htmlTextTrackToITextTrack(i))),(0,L.filterChanged)((i,a)=>i.length===a.length&&i.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:i})=>i==="showing")),(0,L.map)(i=>i&&this.htmlTextTrackToITextTrack(i).id),(0,L.filterChanged)()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add((0,L.fromEvent)(e,"addtrack").subscribe(i=>{i.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))};i.track?.addEventListener("cuechange",a)})),this.subscription.add((0,L.fromEvent)(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let a=i;(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(r.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,a=e.id?e.id:lE(e),s=this.externalTracks.has(a),n=(s?this.externalTracks.get(a)?.isAuto:this.internalTracks.get(a)?.isAuto)??a.includes("auto");return s?{id:a,type:"external",isAuto:n,language:t,label:i,url:this.externalTracks.get(a)?.url}:{id:a,type:"internal",isAuto:n,language:t,label:i,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(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:a,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===a&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(a=>a.id===i)).forEach(([,i])=>this.detach(i))}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)||!cE(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"),i=>i.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)}},qe=Io;var vt=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 qh=r=>{let e=r;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Eo=r=>{let e=qh(r);return!!(e&&e.fullscreenElement&&e.fullscreenElement===r)},Uh=r=>{let e=qh(r);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===r)};var C=require("@vkontakte/videoplayer-shared");var dE=3,Hh=(r,e,t=dE)=>{let i=0,a=0;for(let s=0;s<r.length;s++){let n=r.start(s),o=r.end(s);if(n<=e&&e<=o){if(i=n,a=o,!t)return{from:i,to:a};for(let u=s-1;u>=0;u--)r.end(u)+t>=i&&(i=r.start(u));for(let u=s+1;u<r.length;u++)r.start(u)-t<=a&&(a=r.end(u))}}return{from:i,to:a}};var Ee=r=>{let e=k=>(0,C.fromEvent)(r,k).pipe((0,C.mapTo)(void 0)),i=(0,C.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(k=>(0,C.fromEvent)(r,k))).pipe((0,C.map)(k=>k.type==="ended"?r.readyState<2:r.readyState<3),(0,C.filterChanged)()),a=(0,C.merge)((0,C.fromEvent)(r,"progress"),(0,C.fromEvent)(r,"timeupdate")).pipe((0,C.map)(()=>Hh(r.buffered,r.currentTime))),s=C.clientChecker.isSafari?(0,C.combine)({play:e("play").pipe((0,C.once)()),playing:e("playing")}).pipe((0,C.mapTo)(void 0)):e("playing"),n=(0,C.fromEvent)(r,"volumechange").pipe((0,C.map)(()=>({muted:r.muted,volume:r.volume}))),o=(0,C.fromEvent)(r,"ratechange").pipe((0,C.map)(()=>r.playbackRate)),u=(0,C.fromEvent)(r,"error").pipe((0,C.filter)(()=>!!(r.error||r.played.length)),(0,C.map)(()=>{let k=r.error;return{id:k?`MediaError#${k.code}`:"HtmlVideoError",category:C.ErrorCategory.VIDEO_PIPELINE,message:k?k.message:"Error event from HTML video element",thrown:r.error??void 0}})),l=(0,C.fromEvent)(r,"timeupdate").pipe((0,C.map)(()=>r.currentTime)),c=new C.Subject,d=.3,h;l.subscribe(k=>{r.loop&&(0,C.isNonNullable)(h)&&(0,C.isNonNullable)(k)&&h>=r.duration-d&&k<=d&&c.next(h),h=k});let m=e("pause").pipe((0,C.filter)(()=>!r.error&&h!==r.duration)),f=(0,C.fromEvent)(r,"enterpictureinpicture"),g=(0,C.fromEvent)(r,"leavepictureinpicture"),y=new C.ValueSubject(Uh(r));f.subscribe(()=>y.next(!0)),g.subscribe(()=>y.next(!1));let I=new C.ValueSubject(Eo(r));return(0,C.fromEvent)(r,"fullscreenchange").pipe((0,C.map)(()=>Eo(r))).subscribe(I),{playing$:s,pause$:m,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:(0,C.fromEvent)(r,"durationchange").pipe((0,C.map)(()=>r.duration)),isBuffering$:i,currentBuffer$:a,volumeState$:n,playbackRateState$:o,inPiP$:y,inFullscreen$:I}};var yt=require("@vkontakte/videoplayer-shared"),Dt=r=>{switch(r){case"mobile":return yt.VideoQuality.Q_144P;case"lowest":return yt.VideoQuality.Q_240P;case"low":return yt.VideoQuality.Q_360P;case"sd":case"medium":return yt.VideoQuality.Q_480P;case"hd":case"high":return yt.VideoQuality.Q_720P;case"fullhd":case"full":return yt.VideoQuality.Q_1080P;case"quadhd":case"quad":return yt.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return yt.VideoQuality.Q_2160P}};var Vt=Be(wi(),1),M=require("@vkontakte/videoplayer-shared");var xo=!1,Tt={},Kh=r=>{xo=r},Jh=()=>{Tt={}},Xh=r=>{r(Tt)},fr=(r,e)=>{xo&&(Tt.meta=Tt.meta??{},Tt.meta[r]=e)},ge=class{constructor(e){this.name=e}next(e){if(!xo)return;Tt.series=Tt.series??{};let t=Tt.series[this.name]??[];t.push([Date.now(),e]),Tt.series[this.name]=t}};var yE=new ge("best_bitrate"),em=(r,e,t)=>(e-t)*Math.pow(2,-10*r)+t;var Po=r=>(e,t)=>r*(Number(e.bitrate)-Number(t.bitrate)),br=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,M.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},tm='Assertion "ABR Tracks is empty array" failed',ss=(r,e,t,i)=>{let a=[...e].sort(Po(1)),s=[...t].sort(Po(1)),n=s.filter(u=>(0,M.isNonNullable)(u.bitrate)&&(0,M.isNonNullable)(r.bitrate)?r.bitrate/u.bitrate>i:!0),o=(0,Vt.default)(s,Math.round(s.length*a.indexOf(r)/(a.length+1)))??(0,Vt.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,Vt.default)(n,-1):(0,Vt.default)(s,0)},Zh=r=>"quality"in r,im=(r,e,t,i)=>{let a=(0,M.isNonNullable)(i?.last?.bitrate)&&(0,M.isNonNullable)(t?.bitrate)&&i.last.bitrate<t.bitrate?r.trackCooldownIncreaseQuality:r.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&(0,M.now)()-i.history[t.id]<=a&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!s&&i.recordSelection(t),s&&i?.last){let n=i.last;i?.recordSwitch(n);let o=Zh(n)?"video":"audio",u=Zh(n)?n.quality:n.bitrate;return e({message:`
|
|
7
7
|
[last ${o} selected] ${u}
|
|
8
|
-
`}),n}return i?.recordSwitch(t),t},
|
|
8
|
+
`}),n}return i?.recordSwitch(t),t},TE=(r,e)=>Math.log(e)/Math.log(r),Bt=(r,{container:e,estimatedThroughput:t,tuning:i,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:h,stallsPredictedThroughput:m,abrLogger:f})=>{(0,M.assertNotEmptyArray)(r,tm);let g=i.containerSizeFactor;if(i.usePixelRatio&&window.devicePixelRatio){let E=window.devicePixelRatio;if(i.pixelRatioMultiplier)g*=i.pixelRatioMultiplier*(E-1)+1;else{let A=i.pixelRatioLogBase,[Z=0,Ae=0,Ge=0]=i.pixelRatioLogCoefficients,R=TE(A,Z*E+Ae)+Ge;Number.isFinite(R)&&(g*=R)}}let y=i.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*g,height:e.height*g}:void 0,I=i.considerPlaybackRate&&(0,M.isNonNullable)(o)?o:1,P=r.filter(E=>!(0,M.isInvariantQuality)(E.quality)).sort((E,A)=>(0,M.isHigher)(E.quality,A.quality)?-1:1),k=(0,Vt.default)(P,-1)?.quality,D=(0,Vt.default)(P,0)?.quality,x=(0,M.isNullable)(a)||(0,M.isNonNullable)(a.min)&&(0,M.isNonNullable)(a.max)&&(0,M.isLower)(a.max,a.min)||(0,M.isNonNullable)(a.min)&&D&&(0,M.isHigher)(a.min,D)||(0,M.isNonNullable)(a.max)&&k&&(0,M.isLower)(a.max,k),N=I*em(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),Y={},z=P.filter(E=>{let A=!0;if(y)if(E.size)A=E.size.width<=y.width&&E.size.height<=y.height;else{let de=y&&(0,M.videoSizeToQuality)(y);A=de?(0,M.isLowerOrEqual)(E.quality,de):!0}if(!A)return Y[E.quality]="FitsContainer",!1;let Z=m||t;if(!((0,M.isNonNullable)(Z)&&isFinite(Z)&&(0,M.isNonNullable)(E.bitrate)?Z-s>=E.bitrate*N:!0))return Y[E.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&(0,M.isNonNullable)(i.minBufferToSwitchUp)&&u&&!(0,M.isInvariantQuality)(u.quality)&&(n??0)<i.minBufferToSwitchUp&&(0,M.isHigher)(E.quality,u.quality))return Y[E.quality]="Buffer",!1;if(!!d&&(0,M.isHigherOrEqual)(E.quality,d))return Y[E.quality]="DroppedFramesLimit",!1;if(!!h&&(0,M.isHigherOrEqual)(E.quality,h))return Y[E.quality]="StallsLimit",!1;let O=x||((0,M.isNullable)(a.max)||(0,M.isLowerOrEqual)(E.quality,a.max))&&((0,M.isNullable)(a.min)||(0,M.isHigherOrEqual)(E.quality,a.min)),oe=(0,M.isNonNullable)(c)&&!c?(0,M.isLowerOrEqual)(E.quality,i.backgroundVideoQualityLimit):!0;return!O||!oe?(Y[E.quality]="FitsQualityLimits",!1):!0})[0];z&&z.bitrate&&yE.next(z.bitrate);let ee=z??(0,Vt.default)(P,-1)??r[0];return ee.quality!==l?.last?.quality&&f({message:`
|
|
9
9
|
[VIDEO TRACKS ABR]
|
|
10
10
|
[available video tracks]
|
|
11
11
|
${r.map(E=>`{ id: ${E.id}, quality: ${E.quality}, bitrate: ${E.bitrate} }`).join(`
|
|
12
12
|
`)}
|
|
13
13
|
|
|
14
14
|
[tuning]
|
|
15
|
-
${Object.entries(i??{}).map(([E,
|
|
15
|
+
${Object.entries(i??{}).map(([E,A])=>`${E}: ${A}`).join(`
|
|
16
16
|
`)}
|
|
17
17
|
|
|
18
18
|
[limit params]
|
|
@@ -26,18 +26,18 @@
|
|
|
26
26
|
bitrateFactor: ${N},
|
|
27
27
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
28
28
|
droppedVideoMaxQualityLimit: ${d},
|
|
29
|
-
stallsVideoMaxQualityLimit: ${
|
|
29
|
+
stallsVideoMaxQualityLimit: ${h},
|
|
30
30
|
limitsAreInvalid: ${x},
|
|
31
31
|
maxQualityLimit: ${a?.max},
|
|
32
32
|
minQualityLimit: ${a?.min},
|
|
33
33
|
|
|
34
34
|
[limited video tracks]
|
|
35
|
-
${Object.entries(Y).map(([E,
|
|
35
|
+
${Object.entries(Y).map(([E,A])=>`${E}: ${A}`).join(`
|
|
36
36
|
`)||"All tracks are available"}
|
|
37
37
|
|
|
38
38
|
[best video track] ${z?.quality}
|
|
39
39
|
[selected video track] ${ee?.quality}
|
|
40
|
-
`}),
|
|
40
|
+
`}),im(i,f,ee,l)},rm=(r,e,t,{estimatedThroughput:i,tuning:a,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{(0,M.assertNotEmptyArray)(t,tm);let c=a.considerPlaybackRate&&(0,M.isNonNullable)(s)?s:1,d=[...t].sort(Po(-1)),h=r.bitrate;(0,M.assertNonNullable)(h);let m=c*em(n??.5,a.bitrateAudioFactorAtEmptyBuffer,a.bitrateAudioFactorAtFullBuffer),f,g=ss(r,e,t,a.minVideoAudioRatio),y=l||i;return(0,M.isNonNullable)(y)&&isFinite(y)&&(f=d.find(I=>(0,M.isNonNullable)(I.bitrate)&&(0,M.isNonNullable)(g?.bitrate)?y-h>=I.bitrate*m&&I.bitrate>=g.bitrate:!1)),f||(f=g),f?.bitrate!==o?.last?.bitrate&&u({message:`
|
|
41
41
|
[AUDIO TRACKS ABR]
|
|
42
42
|
[available audio tracks]
|
|
43
43
|
${t.map(I=>`{ id: ${I.id}, bitrate: ${I.bitrate} }`).join(`
|
|
@@ -50,7 +50,7 @@
|
|
|
50
50
|
[limit params]
|
|
51
51
|
estimatedThroughput: ${i},
|
|
52
52
|
stallsPredictedThroughput: ${l},
|
|
53
|
-
reserve: ${
|
|
53
|
+
reserve: ${h},
|
|
54
54
|
playbackRate: ${s},
|
|
55
55
|
playbackRateFactor: ${c},
|
|
56
56
|
forwardBufferHealth: ${n},
|
|
@@ -58,14 +58,14 @@
|
|
|
58
58
|
minBufferToSwitchUp: ${a.minBufferToSwitchUp},
|
|
59
59
|
|
|
60
60
|
[selected audio track] ${f?.id}
|
|
61
|
-
`}),f&&am(a,u,f,o)};var ue=r=>new URL(r).hostname;var V=require("@vkontakte/videoplayer-shared");var nm=r=>{if(r instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(r.message))throw r;return!(r instanceof DOMException&&(r.code===20||r.name==="AbortError"))},ke=async(r,e)=>{let t=r.muted;try{await r.play()}catch(i){if(!nm(i))return!1;if(e&&e(),t)return console.warn(i),!1;r.muted=!0;try{await r.play()}catch(a){return nm(a)&&(r.muted=!1,console.warn(a)),!1}}return!0};var Ce=require("@vkontakte/videoplayer-shared");var lt=require("@vkontakte/videoplayer-shared");function le(){return(0,lt.now)()}function Ao(r){return le()-r}function Ro(r){let e=r.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,a=n=>i.test(n);return{resolve:(n,o,u=!1)=>{a(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function om(r,e,t){let i=(...a)=>{t.apply(null,a),r.removeEventListener(e,i)};r.addEventListener(e,i)}function $i(r,e,t,i){let a=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,m="arraybuffer",f=7e3,g=2e3,y=()=>{if(u)return;(0,lt.assertNonNullable)(c);let w=Ao(c),Z;if(w<g){Z=g-w,setTimeout(y,Z);return}g*=2,g>f&&(g=f),n&&n.abort(),n=new a,N()},I=w=>(s=w,E),P=w=>(d=w,E),k=()=>(m="json",E),C=()=>{if(!u){if(--l>=0){y(),i&&i();return}u=!0,d&&d(),t&&t()}},x=w=>(p=w,E),N=()=>{c=le(),n=new a,n.open("get",r);let w=0,Z,Re=0,Qe=()=>((0,lt.assertNonNullable)(c),Math.max(c,Math.max(Z||0,Re||0)));if(s&&n.addEventListener("progress",R=>{let j=le();s.updateChunk&&R.loaded>w&&(s.updateChunk(Qe(),R.loaded-w),w=R.loaded,Z=j)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>C())),n.addEventListener("load",()=>{if(u)return;(0,lt.assertNonNullable)(n);let R=n.status;if(R>=200&&R<300){if(n.response.byteLength&&s){let j=n.response.byteLength-w;j&&s.updateChunk&&s.updateChunk(Qe(),j)}n.responseType==="json"&&!Object.values(n.response).length?C():(d&&d(),e(n.response))}else C()}),n.addEventListener("error",()=>{C()}),p){let R=()=>{(0,lt.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Re=le(),n.removeEventListener("readystatechange",R))};n.addEventListener("readystatechange",R)}return n.responseType=m,n.send(),E},E={withBitrateReporting:I,withParallel:x,withJSONResponse:k,withRetryCount:w=>(l=w,E),withRetryInterval:(w,Z)=>((0,lt.isNonNullable)(w)&&(g=w),(0,lt.isNonNullable)(Z)&&(f=Z),E),withTimeout:w=>(o=w,E),withFinally:P,send:N,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return E}var Sr=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,i){return{start:e,end:t,bytes:i}}_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 i=0,a=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=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;i+=n;let u=s.bytes*n/o;a+=u,s.start=t,s.bytes-=u}}}if(a>0&&i>0){let s=a*8/(i/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(i)} 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,i){return this.intervals.push(this._createInterval(e,t,i)),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 vr=class{constructor(e,t,i,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=i,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 i=le(),a=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=le()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=$i(t,s,()=>a("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=le()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=le();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!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,i,a){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,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}`),i(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=i,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 um=require("@vkontakte/videoplayer-shared"),os=1e4,$o=3;var PE=6e4,kE=10,wE=1,AE=500,yr=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.soundProhibitedEvent$=new um.Subject,this.chunkRateEstimator=new Sr(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Ro(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],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=Ro(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,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-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 i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.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,i=t.buffered.length,a;i!==0&&(a=t.buffered.start(i-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){let{videoElement:t}=this.params,i,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):(!i||i.bitrate>s.bitrate)&&(i=s));return a||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,Ce.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:a,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),a.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,a.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{om(a,"progress",()=>{a.buffered.length?(a.currentTime=a.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new vr($o,os,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:a}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let C=s&&(!c||c===this.rep);return C||t("Not running!"),C},p=(C,x,N)=>{u&&u.abort(),u=$i(this.urlResolver.resolve(C,!1),x,N,()=>this._retryCallback()).withTimeout(os).withBitrateReporting(this.bitrateSwitcher).withRetryCount($o).withFinally(()=>{u=null}).send()},m=(C,x,N)=>{(0,Ce.assertNonNullable)(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(C,!1),x,N,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=C=>{let x=i.playbackRate;i.playbackRate!==C&&(t(`Playback rate switch: ${x}=>${C}`),i.playbackRate=C)},g=C=>{this.lowLatency=C,t(`lowLatency changed to ${C}`),y()},y=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let C=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let N=le()-1e4,Y=0;for(let z=0;z<this.bufferStates.length;z++){let ee=this.bufferStates[z];C=Math.min(C,ee.buf),ee.ts<N&&Y++}this.bufferStates.splice(0,Y),t(`update playback rate; minBuffer=${C} drop=${Y} jitter=${this.sourceJitter}`);let J=C-wE;this.sourceJitter>=0?J-=this.sourceJitter/2:this.sourceJitter-=1,J>3?f(1.15):J>1?f(1.1):J>.3?f(1.05):f(1)}},I=C=>{let x,N=()=>x&&x.start?x.start.length:0,Y=R=>x.start[R]/1e3,J=R=>x.dur[R]/1e3,z=R=>x.fragIndex+R,ee=(R,j)=>({chunkIdx:z(R),startTS:Y(R),dur:J(R),discontinuity:j}),E=()=>{let R=0;if(x&&x.dur){let j=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,O=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,oe=j;this.sourceJitter>1&&(oe+=this.sourceJitter-1);let de=x.dur.length-1;for(;de>=0&&(oe-=x.dur[de],!(oe<=0));--de);R=Math.min(de,x.dur.length-1-O),R=Math.max(R,0)}return ee(R,!0)},w=R=>{let j=N();if(!(j<=0)){if((0,Ce.isNonNullable)(R)){for(let O=0;O<j;O++)if(Y(O)>R)return ee(O)}return E()}},Z=R=>{let j=N(),O=R?R.chunkIdx+1:0,oe=O-x.fragIndex;if(!(j<=0)){if(!R||oe<0||oe-j>kE)return t(`Resync: offset=${oe} bChunks=${j} chunk=`+JSON.stringify(R)),E();if(!(oe>=j))return ee(O-x.fragIndex,!1)}},Re=(R,j,O)=>{l&&l.abort(),l=$i(this.urlResolver.resolve(R,!0,this.lowLatency),j,O,()=>this._retryCallback()).withTimeout(os).withRetryCount($o).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(R,j)=>{Re(C,O=>{if(!d())return;x=O;let oe=!!x.lowLatency;oe!==this.lowLatency&&g(oe);let de=0;for(let Rt=0;Rt<x.dur.length;++Rt)de+=x.dur[Rt];de>0&&((0,Ce.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(de/x.dur.length)),a({name:"index",zeroTime:x.zeroTime,shiftDuration:x.shiftDuration}),this.sourceJitter=x.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,x.jitter/1e3)):1,R(w(j))},()=>this._handleNetworkError())},nextChunk:Z}},P=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),(0,Ce.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:C=>{let{videoElement:x,logger:N}=this.params,Y=I(e.jidxUrl),J,z,ee,E,w=0,Z,Re,Qe,R=()=>{Z&&(clearTimeout(Z),Z=void 0);let W=Math.max(AE,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),pe=w+W,ne=le(),ye=Math.min(1e4,pe-ne);w=ne;let $e=()=>{l||d()&&Y.seek(()=>{d()&&(w=le(),j(),R())})};ye>0?Z=window.setTimeout(()=>{this.paused?R():$e()},ye):$e()},j=()=>{let W;for(;W=Y.nextChunk(E);)E=W,si(W);let pe=Y.nextChunk(ee);if(pe){if(ee&&pe.discontinuity){N("Detected discontinuity; restarting playback"),this.paused?R():(P(),this._initPlayerWith(e));return}Rt(pe)}else R()},O=(W,pe)=>{if(!d()||!this.sourceBuffer)return;let ne,ye,$e,ht=it=>{window.setTimeout(()=>{d()&&O(W,pe)},it)};if(this.sourceBuffer.updating)N("Source buffer is updating; delaying appendBuffer"),ht(100);else{let it=le(),mt=x.currentTime;!this.paused&&x.buffered.length>1&&Re===mt&&it-Qe>500&&(N("Stall suspected; trying to fix"),this._fixupStall()),Re!==mt&&(Re=mt,Qe=it);let rt=this._getBufferSizeSec();if(rt>30)N(`Buffered ${rt} seconds; delaying appendBuffer`),ht(2e3);else try{this.sourceBuffer.appendBuffer(W),this.videoPlayStarted?(this.bufferStates.push({ts:it,buf:rt}),y(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),pe&&pe()}catch(ni){if(ni.name==="QuotaExceededError")N("QuotaExceededError; delaying appendBuffer"),$e=this.sourceBuffer.buffered.length,$e!==0&&(ne=this.sourceBuffer.buffered.start(0),ye=mt,ye-ne>4&&this.sourceBuffer.remove(ne,ye-3)),ht(1e3);else throw ni}}},oe=()=>{z&&J&&(N([`Appending chunk, sz=${z.byteLength}:`,JSON.stringify(ee)]),O(z,function(){z=null,j()}))},de=W=>e.fragUrlTemplate.replace("%%id%%",W.chunkIdx),Rt=W=>{d()&&m(de(W),(pe,ne)=>{if(d()){if(ne/=1e3,z=pe,ee=W,n=W.startTS,ne){let ye=Math.min(10,W.dur/ne);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ye:ye}oe()}},()=>this._handleNetworkError())},si=W=>{d()&&((0,Ce.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(de(W),!1)))},Ut=W=>{d()&&(e.cachedHeader=W,O(W,()=>{J=!0,oe()}))};s=!0,Y.seek(W=>{if(d()){if(w=le(),!W){R();return}E=W,!(0,Ce.isNullable)(C)||W.startTS>C?Rt(W):(ee=W,j())}},C),e.cachedHeader?Ut(e.cachedHeader):p(e.headerUrl,Ut,()=>this._handleNetworkError())},stop:P,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),(0,Ce.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,Ce.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,Ce.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=d=>{if(!this.autoQuality)return;let p,m,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(m=this._getBufferSizeSec(),f=d/this.bitrate,m>10&&f>.8||m>15&&f>.5||m>20&&f>.3)){e(`Not switching: buffer=${Math.floor(m)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,m)=>{let f=le();if(this.chunkRateEstimator.addInterval(p,f,m)){let y=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:m,duration:f-p,speed:y}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Ao(n)<3e4)return;i(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let m=s.updateChunk(d,p);return m&&l(),m},notifySwitch:d=>{let p=le();d<o&&(n=p),o=d}}}_fetchManifest(e,t,i){this.manifestRequest=$i(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(os).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;ke(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:a}=this.params,s=n=>{let o=[];return n?.length?(n.forEach((u,l)=>{u.video&&a.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},PE))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var ie=require("@vkontakte/videoplayer-shared"),Lo=class{constructor(){this.onDroopedVideoFramesLimit$=new ie.Subject;this.subscription=new ie.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new ie.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,ie.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,a=t-this.prevDroppedVideoFrames,s=1-(i-a)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&(0,ie.isHigher)(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add((0,ie.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,ie.interval)(this.droppedFramesChecker.checkTime).pipe((0,ie.filter)(()=>this.playing),(0,ie.filter)(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe((0,ie.debounce)(this.droppedFramesChecker.checkTime)),i=(0,ie.merge)(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),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(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[a])=>(0,ie.isLower)(i,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}},us=Lo;var ls=require("@vkontakte/videoplayer-shared"),lm=require("@vkontakte/videoplayer-shared");var Tr=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var RE=(r,e)=>new ls.Observable(t=>{if(!window.IntersectionObserver)return;let i={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Tr()))},{...i,...e});a.observe(r);let s=(0,lm.fromEvent)(document,"visibilitychange").pipe((0,ls.map)(n=>!document.hidden||Tr())).subscribe(n=>t.next(n));return()=>{a.unobserve(r),s.unsubscribe}}),He=RE;var $E=["paused","playing","ready"],LE=["paused","playing","ready"],Ir=class{constructor(e){this.subscription=new V.Subscription;this.videoState=new q("stopped");this.representations$=new V.ValueSubject([]);this.textTracksManager=new Ue;this.droppedFramesManager=new us;this.maxSeekBackTime$=new V.ValueSubject(1/0);this.zeroTime$=new V.ValueSubject(void 0);this.liveOffset=new Tt;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:V.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let a of t){let s=a.name??a.index.toString(10),n=Vt(a.name)??(0,V.videoSizeToQuality)(a.video),o=a.bitrate/1e3,u={...a.video};if(!n)continue;let l={id:s,quality:n,bitrate:o,size:u};i.push({track:l,representation:a})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:a})=>a)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:a})=>a===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),(0,V.isNonNullable)(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);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(),i=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: ${i}; seekState: ${JSON.stringify(s)};`}),i==="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(LE.includes(e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&$E.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(he(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=a?.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="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 u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(he(this.params.source.url,u))}return;default:return(0,V.assertNever)(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:V.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:a})};(0,V.merge)(this.videoState.stateChangeStarted$.pipe((0,V.map)(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,V.map)(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=Ie(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ue(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=Pe(this.video);this.subscription.add(this.representations$.pipe((0,V.map)(a=>a.map(({track:s})=>s)),(0,V.filter)(a=>!!a.length),(0,V.once)()).subscribe(a=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:a}))),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((0,V.filterChanged)(),(0,V.map)(a=>-a/1e3)).subscribe(this.params.output.duration$)).add((0,V.combine)({zeroTime:this.zeroTime$.pipe((0,V.filter)(V.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(ut(this.video,this.params.desiredState.isLooped,t)).add(xe(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(qe(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(He(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&(0,V.videoQualityToHeight)(a);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:a})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return(0,V.assertNever)(a.to)}},t)).add((0,V.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,V.observableFrom)(["init"])).pipe((0,V.debounce)(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Ee(this.video)}createLiveDashPlayer(){let e=new yr({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(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),a=!i&&(0,V.isNonNullable)(t)?t:Ot(e.map(({track:l})=>l),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput: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,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),u&&this.setAutoQuality(i),n||u||s!==o){let l=e.find(({track:c})=>c.id===s)?.representation;(0,V.assertNonNullable)(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;(0,V.assertNonNullable)(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),a=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(he(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var cm=Ir;var ct=(r,e)=>{let t=0;for(let i=0;i<r.length;i++){let a=r.start(i)*1e3,s=r.end(i)*1e3;a<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var B=require("@vkontakte/videoplayer-shared");var cs=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let a=0,s=i.length;a<s;a++)if(i[a].callback===t){i.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let a=0,s=i.length;a<s;a++){let n=i[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}},Li=class extends cs{constructor(){super(),this.listeners||cs.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)}},Er=class{constructor(){Object.defineProperty(this,"signal",{value:new Li,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 i=e;if(i===void 0)if(typeof document>"u")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch{i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(Er.prototype[Symbol.toStringTag]="AbortController",Li.prototype[Symbol.toStringTag]="AbortSignal");function ds(r){return r.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof r.Request=="function"&&!r.Request.prototype.hasOwnProperty("signal")||!r.AbortController}function Mo(r){typeof r=="function"&&(r={fetch:r});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=r;if(!ds({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||a)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch{d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((m,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var xr=ds({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),dm=xr?Mo({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ze=xr?dm.fetch:window.fetch,c$=xr?dm.Request:window.Request,me=xr?Er:window.AbortController,d$=xr?Li:window.AbortSignal;var ms=Oe(Ri(),1);var xt=()=>window.ManagedMediaSource||window.MediaSource,ps=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),pm=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),hm=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var dt=require("@vkontakte/videoplayer-shared"),fs=document.createElement("video"),CE='video/mp4; codecs="avc1.42000a,mp4a.40.2"',VE='video/mp4; codecs="hev1.1.6.L93.B0"',mm='video/webm; codecs="vp09.00.10.08"',fm='video/webm; codecs="av01.0.00M.08"',BE='audio/mp4; codecs="mp4a.40.2"',OE='audio/webm; codecs="opus"',Pr={mms:ps(),mse:pm(),hls:!!(fs.canPlayType?.("application/x-mpegurl")||fs.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},we={mp4:!!fs.canPlayType?.("video/mp4"),webm:!!fs.canPlayType?.("video/webm"),cmaf:!0},Ae={h264:!!xt()?.isTypeSupported?.(CE),h265:!!xt()?.isTypeSupported?.(VE),vp9:!!xt()?.isTypeSupported?.(mm),av1:!!xt()?.isTypeSupported?.(fm),aac:!!xt()?.isTypeSupported?.(BE),opus:!!xt()?.isTypeSupported?.(OE)},Mi=(Ae.h264||Ae.h265)&&Ae.aac,Jt,_E=async()=>{if(!window.navigator.mediaCapabilities)return;let r={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...r,video:{...r.video,contentType:fm}}),window.navigator.mediaCapabilities.decodingInfo({...r,video:{...r.video,contentType:mm}})]);Jt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{_E()}catch(r){console.error(r)}var Di=Pr.hls&&we.mp4,bm=()=>Object.keys(Ae).filter(r=>Ae[r]),gm=(r,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:i})=>{let a=Pr.mse&&(!i||!!window.MediaStreamTrack)||Pr.mms&&t;return r.filter(s=>{switch(s){case"DASH_SEP":return a&&we.mp4&&Mi;case"DASH_WEBM":return a&&we.webm&&Ae.vp9&&Ae.opus;case"DASH_WEBM_AV1":return a&&we.webm&&Ae.av1&&Ae.opus;case"DASH_STREAMS":return a&&(we.mp4&&Mi||we.webm&&(Ae.vp9||Ae.av1)&&(Ae.opus||Ae.aac));case"DASH_LIVE":return a&&we.mp4&&Mi;case"DASH_LIVE_CMAF":return a&&we.mp4&&Mi&&we.cmaf;case"DASH_ONDEMAND":return a&&we.mp4&&Mi;case"HLS":case"HLS_ONDEMAND":return Di||e&&a&&we.mp4&&Mi;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Di;case"MPEG":return we.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Pr.webrtc&&Pr.ws&&Ae.h264&&(we.mp4||we.webm);default:return(0,dt.assertNever)(s)}})},hs=r=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(r){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return Jt?Jt[t].smooth?[t,e]:Jt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Jt?Jt[t].powerEfficient?[t,e]:Jt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:(0,dt.assertNever)(r)}return[e,t]},Sm=({webmCodec:r,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...hs(r),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],a=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(dt.clientChecker.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...a,"MPEG",...hs(r),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...hs(r),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...hs(r),...a,"HLS","HLS_ONDEMAND"];default:(0,dt.assertNever)(e)}return Di?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},vm=({androidPreferredFormat:r,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],a=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...a],n=[...a,...i],o,u=dt.clientChecker.isMac&&dt.clientChecker.isSafari;if(dt.clientChecker.isAndroid)switch(r){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,dt.assertNever)(r)}else Di&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Do=r=>r?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],ym=r=>{if(r.size===0)return;if(r.size===1){let t=r.values().next();return(0,ms.default)(t.value.split("."),0)}for(let t of r){let i=(0,ms.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=r.values().next();return(0,ms.default)(e.value.split("."),0)};var Ci=require("@vkontakte/videoplayer-shared"),Tm=r=>{if(!r)return{id:"EmptyResponse",category:Ci.ErrorCategory.PARSER,message:"Empty response"};if(r.length<=2&&r.match(/^\d+$/))return{id:`UVError#${r}`,category:Ci.ErrorCategory.NETWORK,message:`UV Error ${r}`};let e=r.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Ci.ErrorCategory.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(r,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Ci.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Ci.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var _t=(r,e,t=0)=>{for(let i=0;i<r.length;i++)if(r.start(i)*1e3-t<=e&&r.end(i)*1e3+t>e)return!0;return!1};var S=require("@vkontakte/videoplayer-shared");var _i=Oe(Ri(),1);var NE=(r,e={})=>{let i=e.timeout||1,a=performance.now();return window.setTimeout(()=>{r({get didTimeout(){return e.timeout?!1:performance.now()-a-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-a))}})},1)},FE=r=>window.clearTimeout(r),Im=r=>typeof r=="function"&&r?.toString().endsWith("{ [native code] }"),Em=!Im(window.requestIdleCallback)||!Im(window.cancelIdleCallback),Co=Em?NE:window.requestIdleCallback,E$=Em?FE:window.cancelIdleCallback;var hf=Oe(rs(),1);var je=require("@vkontakte/videoplayer-shared"),qE=18,xm=!1;try{xm=je.clientChecker.isSafari&&!!je.clientChecker.macVersion&&je.clientChecker.macVersion<=qE}catch(r){console.error(r)}var Vo=class{constructor(e){this.bufferFull$=new je.Subject;this.error$=new je.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:je.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(i=>{let a={operation:"append",data:e,signal:t,callback:i};this.queue.push(a),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(a=>{let s={operation:"remove",from:e,to:t,signal:i,callback:a};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i;xm&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(let{callback:a}of this.queue)a(!1);i&&(this.queue=[i]),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:je.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,je.assertNever)(t)}}},Pm=Vo;var Bo=r=>{let e=0;for(let t=0;t<r.length;t++)e+=r.end(t)-r.start(t);return e*1e3};var T=require("@vkontakte/videoplayer-shared");var K=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i: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 Vi=class extends K{};var kr=class extends K{};var wr=class extends K{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let a=this.readString(4);this.compatibleBrands.push(a),i-=4}}};var Ar=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var re=class extends K{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Rr=class extends re{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var $r=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Lr=class extends K{constructor(e,t){super(e,t),this.data=this.content}};var Zt=class extends re{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let a=this.readUint32(),s=a>>>31,n=a<<1>>>1,o=this.readUint32();a=this.readUint32();let u=a>>>28,l=a<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var Mr=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Dr=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Cr=class extends re{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Vr=class extends re{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Br=class extends re{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Or=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var _r=class extends re{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var Nr=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Fr=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var qr=class extends re{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Ur=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Hr=class extends re{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var jr=class extends re{constructor(t,i){super(t,i);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 Gr=class extends re{constructor(t,i){super(t,i);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 HE={ftyp:wr,moov:Ar,mvhd:Rr,moof:$r,mdat:Lr,sidx:Zt,trak:Mr,mdia:Or,mfhd:qr,tkhd:_r,traf:Ur,tfhd:Hr,tfdt:jr,trun:Gr,minf:Nr,sv3d:Dr,st3d:Cr,prhd:Vr,proj:Fr,equi:Br,uuid:kr,unknown:Vi},Nt=class r{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch{break}return t}createBox(e,t){let i=HE[e];return i?new i(t,new r):new Vi(t,new r)}};var ei=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 GE=new TextDecoder("ascii"),QE=r=>GE.decode(new DataView(r.buffer,r.byteOffset+4,4))==="ftyp",WE=r=>{let e=new Zt(r,new Nt),t=e.earliestPresentationTime/e.timescale*1e3,i=r.byteOffset+r.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:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},YE=(r,e)=>{let i=new Nt().parse(r),a=new ei(i),s=a.findAll("moof"),n=e?a.findAll("uuid"):a.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(r.buffer,l,d)},zE=r=>{let t=new Nt().parse(r);return new ei(t).find("sidx")?.timescale},KE=(r,e)=>{let i=new Nt().parse(r),s=new ei(i).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},XE=r=>{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}}},i=new Nt().parse(r),a=new ei(i);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 u=a.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},km={validateData:QE,parseInit:XE,getIndexRange:()=>{},parseSegments:WE,parseFeedableSegmentChunk:YE,getChunkEndTime:KE,getTimescaleFromIndex:zE};var Pt=require("@vkontakte/videoplayer-shared");var Am=require("@vkontakte/videoplayer-shared");var wm={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"}},Rm=r=>{let e=r.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=Qr(r,t),a=i in wm,s=a?wm[i].type:"binary",n=r.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 u=new DataView(r.buffer,r.byteOffset+t+1,o-1),l=n&255>>o,c=Qr(u),d=l*2**((o-1)*8)+c,p=t+o,m;return p+d>r.byteLength?m=new DataView(r.buffer,r.byteOffset+p):m=new DataView(r.buffer,r.byteOffset+p,d),{tag:a?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:m,valueSize:d}},Qr=(r,e=r.byteLength)=>{switch(e){case 1:return r.getUint8(0);case 2:return r.getUint16(0);case 3:return r.getUint8(0)*2**16+r.getUint16(1);case 4:return r.getUint32(0);case 5:return r.getUint8(0)*2**32+r.getUint32(1);case 6:return r.getUint16(0)*2**32+r.getUint32(2);case 7:{let t=r.getUint8(0)*281474976710656+r.getUint16(1)*4294967296+r.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},et=(r,e)=>{switch(e){case"int":return r.getInt8(0);case"uint":return Qr(r);case"float":return r.byteLength===4?r.getFloat32(0):r.getFloat64(0);case"string":return new TextDecoder("ascii").decode(r);case"utf8":return new TextDecoder("utf-8").decode(r);case"date":return new Date(Date.UTC(2001,0)+r.getInt8(0)).getTime();case"master":return r;case"binary":return r;default:(0,Am.assertNever)(e)}},ti=(r,e)=>{let t=0;for(;t<r.byteLength;){let i=new DataView(r.buffer,r.byteOffset+t),a=Rm(i);if(!e(a))return;a.type==="master"&&ti(a.value,e),t=a.value.byteOffset-r.byteOffset+a.valueSize}},$m=r=>{if(r.getUint32(0)!==440786851)return!1;let e,t,i,a=Rm(r);return ti(a.value,({tag:s,type:n,value:o})=>(s===17143?e=et(o,n):s===17026?t=et(o,n):s===17029&&(i=et(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Lm=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],JE=[231,22612,22743,167,171,163,160,175],ZE=r=>{let e,t,i,a,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return ti(r,({tag:p,type:m,value:f,valueSize:g})=>{if(p===21419){let y=et(f,m);l=Qr(y)}else p!==21420&&(l=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+g):p===357149030?s=!0:p===290298740?n=!0:p===2807729?i=et(f,m):p===17545?a=et(f,m):p===21420&&l===475249515?u=et(f,m):p===374648427?ti(f,({tag:y,type:I,value:P})=>y===30321?(c=et(P,I)===1,!1):!0):s&&n&&Lm.includes(p)&&(o=!0),!o}),(0,Pt.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,Pt.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,Pt.assertNonNullable)(a,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(a/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},ex=r=>{if((0,Pt.isNullable)(r.cuesSeekPosition))return;let e=r.segmentStart+r.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},tx=(r,e)=>{let t=!1,i=!1,a=o=>(0,Pt.isNonNullable)(o.time)&&(0,Pt.isNonNullable)(o.position),s=[],n;return ti(r,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&a(n)&&s.push(n),n={};break;case 179:n&&(n.time=et(l,u));break;case 183:break;case 241:n&&(n.position=et(l,u));break;default:t&&Lm.includes(o)&&(i=!0)}return!(t&&i)}),n&&a(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},ix=r=>{let e=0,t=!1;try{ti(r,i=>i.tag===524531317?i.tagSize<=r.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):JE.includes(i.tag)?(e+i.tagSize<=r.byteLength&&(e+=i.tagSize,t||=[163,160,175].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=r.byteLength&&t?new DataView(r.buffer,r.byteOffset,e):null},Mm={validateData:$m,parseInit:ZE,getIndexRange:ex,parseSegments:tx,parseFeedableSegmentChunk:ix};var Wr=r=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(r);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Mm;case"mp4":return km}}throw new ReferenceError(`Unsupported mime type ${r}`)},Dm=r=>"getChunkEndTime"in r;var jo=Oe(tf(),1),nf=Oe(Ri(),1);var Ho=r=>{let e=r.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[a,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[a,s,n]=i;return!!(a&&parseInt(a,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let a=i[0];if(!a||a.length!==6)return!1;let[s,n]=a.toUpperCase(),o=s+n;return["6E","7A","F4"].includes(o)}}return!1};var Oi=require("@vkontakte/videoplayer-shared");var rf=r=>{if(r.includes("/")){let e=r.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(r)};var af=r=>{try{let e=Bx(),t=r.match(e),{groups:i}=t??{};if(i){let a={};if(i.extensions){let o=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(o||[]).forEach(u=>{a[u[0]]=u.slice(2)})}let s=i.variants?.split(/-/).filter(o=>o!==""),n={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:a,variants:s};return Object.keys(n).forEach(o=>{let u=n[o];(typeof u>"u"||u==="")&&delete n[o]}),n}return null}catch{return null}};function Bx(){let r="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
|
|
61
|
+
`}),f&&im(a,u,f,o)};var ue=r=>new URL(r).hostname;var V=require("@vkontakte/videoplayer-shared");var am=r=>{if(r instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(r.message))throw r;return!(r instanceof DOMException&&(r.code===20||r.name==="AbortError"))},xe=async(r,e)=>{let t=r.muted;try{await r.play()}catch(i){if(!am(i))return!1;if(e&&e(),t)return console.warn(i),!1;r.muted=!0;try{await r.play()}catch(a){return am(a)&&(r.muted=!1,console.warn(a)),!1}}return!0};var Me=require("@vkontakte/videoplayer-shared");var ot=require("@vkontakte/videoplayer-shared");function le(){return(0,ot.now)()}function ko(r){return le()-r}function Ao(r){let e=r.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,a=n=>i.test(n);return{resolve:(n,o,u=!1)=>{a(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function sm(r,e,t){let i=(...a)=>{t.apply(null,a),r.removeEventListener(e,i)};r.addEventListener(e,i)}function Ri(r,e,t,i){let a=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,h=!1,m="arraybuffer",f=7e3,g=2e3,y=()=>{if(u)return;(0,ot.assertNonNullable)(c);let A=ko(c),Z;if(A<g){Z=g-A,setTimeout(y,Z);return}g*=2,g>f&&(g=f),n&&n.abort(),n=new a,N()},I=A=>(s=A,E),P=A=>(d=A,E),k=()=>(m="json",E),D=()=>{if(!u){if(--l>=0){y(),i&&i();return}u=!0,d&&d(),t&&t()}},x=A=>(h=A,E),N=()=>{c=le(),n=new a,n.open("get",r);let A=0,Z,Ae=0,Ge=()=>((0,ot.assertNonNullable)(c),Math.max(c,Math.max(Z||0,Ae||0)));if(s&&n.addEventListener("progress",R=>{let j=le();s.updateChunk&&R.loaded>A&&(s.updateChunk(Ge(),R.loaded-A),A=R.loaded,Z=j)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>D())),n.addEventListener("load",()=>{if(u)return;(0,ot.assertNonNullable)(n);let R=n.status;if(R>=200&&R<300){if(n.response.byteLength&&s){let j=n.response.byteLength-A;j&&s.updateChunk&&s.updateChunk(Ge(),j)}n.responseType==="json"&&!Object.values(n.response).length?D():(d&&d(),e(n.response))}else D()}),n.addEventListener("error",()=>{D()}),h){let R=()=>{(0,ot.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Ae=le(),n.removeEventListener("readystatechange",R))};n.addEventListener("readystatechange",R)}return n.responseType=m,n.send(),E},E={withBitrateReporting:I,withParallel:x,withJSONResponse:k,withRetryCount:A=>(l=A,E),withRetryInterval:(A,Z)=>((0,ot.isNonNullable)(A)&&(g=A),(0,ot.isNonNullable)(Z)&&(f=Z),E),withTimeout:A=>(o=A,E),withFinally:P,send:N,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return E}var gr=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,i){return{start:e,end:t,bytes:i}}_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 i=0,a=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=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;i+=n;let u=s.bytes*n/o;a+=u,s.start=t,s.bytes-=u}}}if(a>0&&i>0){let s=a*8/(i/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(i)} 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,i){return this.intervals.push(this._createInterval(e,t,i)),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 Sr=class{constructor(e,t,i,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=i,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 i=le(),a=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=le()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Ri(t,s,()=>a("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=le()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=le();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!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,i,a){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,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}`),i(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=i,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 nm=require("@vkontakte/videoplayer-shared"),ns=1e4,wo=3;var EE=6e4,xE=10,PE=1,kE=500,vr=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.soundProhibitedEvent$=new nm.Subject,this.chunkRateEstimator=new gr(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 i=0;i<this.manifest.length;++i)if(t=this.manifest[i],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,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-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 i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.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,i=t.buffered.length,a;i!==0&&(a=t.buffered.start(i-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){let{videoElement:t}=this.params,i,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):(!i||i.bitrate>s.bitrate)&&(i=s));return a||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,Me.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:a,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("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=()=>{sm(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 Sr(wo,ns,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:a}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let D=s&&(!c||c===this.rep);return D||t("Not running!"),D},h=(D,x,N)=>{u&&u.abort(),u=Ri(this.urlResolver.resolve(D,!1),x,N,()=>this._retryCallback()).withTimeout(ns).withBitrateReporting(this.bitrateSwitcher).withRetryCount(wo).withFinally(()=>{u=null}).send()},m=(D,x,N)=>{(0,Me.assertNonNullable)(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(D,!1),x,N,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=D=>{let x=i.playbackRate;i.playbackRate!==D&&(t(`Playback rate switch: ${x}=>${D}`),i.playbackRate=D)},g=D=>{this.lowLatency=D,t(`lowLatency changed to ${D}`),y()},y=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let D=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let N=le()-1e4,Y=0;for(let z=0;z<this.bufferStates.length;z++){let ee=this.bufferStates[z];D=Math.min(D,ee.buf),ee.ts<N&&Y++}this.bufferStates.splice(0,Y),t(`update playback rate; minBuffer=${D} drop=${Y} jitter=${this.sourceJitter}`);let X=D-PE;this.sourceJitter>=0?X-=this.sourceJitter/2:this.sourceJitter-=1,X>3?f(1.15):X>1?f(1.1):X>.3?f(1.05):f(1)}},I=D=>{let x,N=()=>x&&x.start?x.start.length:0,Y=R=>x.start[R]/1e3,X=R=>x.dur[R]/1e3,z=R=>x.fragIndex+R,ee=(R,j)=>({chunkIdx:z(R),startTS:Y(R),dur:X(R),discontinuity:j}),E=()=>{let R=0;if(x&&x.dur){let j=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,O=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,oe=j;this.sourceJitter>1&&(oe+=this.sourceJitter-1);let de=x.dur.length-1;for(;de>=0&&(oe-=x.dur[de],!(oe<=0));--de);R=Math.min(de,x.dur.length-1-O),R=Math.max(R,0)}return ee(R,!0)},A=R=>{let j=N();if(!(j<=0)){if((0,Me.isNonNullable)(R)){for(let O=0;O<j;O++)if(Y(O)>R)return ee(O)}return E()}},Z=R=>{let j=N(),O=R?R.chunkIdx+1:0,oe=O-x.fragIndex;if(!(j<=0)){if(!R||oe<0||oe-j>xE)return t(`Resync: offset=${oe} bChunks=${j} chunk=`+JSON.stringify(R)),E();if(!(oe>=j))return ee(O-x.fragIndex,!1)}},Ae=(R,j,O)=>{l&&l.abort(),l=Ri(this.urlResolver.resolve(R,!0,this.lowLatency),j,O,()=>this._retryCallback()).withTimeout(ns).withRetryCount(wo).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(R,j)=>{Ae(D,O=>{if(!d())return;x=O;let oe=!!x.lowLatency;oe!==this.lowLatency&&g(oe);let de=0;for(let wt=0;wt<x.dur.length;++wt)de+=x.dur[wt];de>0&&((0,Me.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(de/x.dur.length)),a({name:"index",zeroTime:x.zeroTime,shiftDuration:x.shiftDuration}),this.sourceJitter=x.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,x.jitter/1e3)):1,R(A(j))},()=>this._handleNetworkError())},nextChunk:Z}},P=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),(0,Me.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:D=>{let{videoElement:x,logger:N}=this.params,Y=I(e.jidxUrl),X,z,ee,E,A=0,Z,Ae,Ge,R=()=>{Z&&(clearTimeout(Z),Z=void 0);let W=Math.max(kE,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),pe=A+W,ne=le(),Se=Math.min(1e4,pe-ne);A=ne;let we=()=>{l||d()&&Y.seek(()=>{d()&&(A=le(),j(),R())})};Se>0?Z=window.setTimeout(()=>{this.paused?R():we()},Se):we()},j=()=>{let W;for(;W=Y.nextChunk(E);)E=W,ai(W);let pe=Y.nextChunk(ee);if(pe){if(ee&&pe.discontinuity){N("Detected discontinuity; restarting playback"),this.paused?R():(P(),this._initPlayerWith(e));return}wt(pe)}else R()},O=(W,pe)=>{if(!d()||!this.sourceBuffer)return;let ne,Se,we,dt=et=>{window.setTimeout(()=>{d()&&O(W,pe)},et)};if(this.sourceBuffer.updating)N("Source buffer is updating; delaying appendBuffer"),dt(100);else{let et=le(),pt=x.currentTime;!this.paused&&x.buffered.length>1&&Ae===pt&&et-Ge>500&&(N("Stall suspected; trying to fix"),this._fixupStall()),Ae!==pt&&(Ae=pt,Ge=et);let tt=this._getBufferSizeSec();if(tt>30)N(`Buffered ${tt} seconds; delaying appendBuffer`),dt(2e3);else try{this.sourceBuffer.appendBuffer(W),this.videoPlayStarted?(this.bufferStates.push({ts:et,buf:tt}),y(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),pe&&pe()}catch(si){if(si.name==="QuotaExceededError")N("QuotaExceededError; delaying appendBuffer"),we=this.sourceBuffer.buffered.length,we!==0&&(ne=this.sourceBuffer.buffered.start(0),Se=pt,Se-ne>4&&this.sourceBuffer.remove(ne,Se-3)),dt(1e3);else throw si}}},oe=()=>{z&&X&&(N([`Appending chunk, sz=${z.byteLength}:`,JSON.stringify(ee)]),O(z,function(){z=null,j()}))},de=W=>e.fragUrlTemplate.replace("%%id%%",W.chunkIdx),wt=W=>{d()&&m(de(W),(pe,ne)=>{if(d()){if(ne/=1e3,z=pe,ee=W,n=W.startTS,ne){let Se=Math.min(10,W.dur/ne);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Se:Se}oe()}},()=>this._handleNetworkError())},ai=W=>{d()&&((0,Me.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(de(W),!1)))},qt=W=>{d()&&(e.cachedHeader=W,O(W,()=>{X=!0,oe()}))};s=!0,Y.seek(W=>{if(d()){if(A=le(),!W){R();return}E=W,!(0,Me.isNullable)(D)||W.startTS>D?wt(W):(ee=W,j())}},D),e.cachedHeader?qt(e.cachedHeader):h(e.headerUrl,qt,()=>this._handleNetworkError())},stop:P,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),(0,Me.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,Me.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,Me.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=d=>{if(!this.autoQuality)return;let h,m,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(m=this._getBufferSizeSec(),f=d/this.bitrate,m>10&&f>.8||m>15&&f>.5||m>20&&f>.3)){e(`Not switching: buffer=${Math.floor(m)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}h=this._selectQuality(d),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(h,m)=>{let f=le();if(this.chunkRateEstimator.addInterval(h,f,m)){let y=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:m,duration:f-h,speed:y}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&ko(n)<3e4)return;i(d)}u=this.autoQuality};return{updateChunk:(d,h)=>{let m=s.updateChunk(d,h);return m&&l(),m},notifySwitch:d=>{let h=le();d<o&&(n=h),o=d}}}_fetchManifest(e,t,i){this.manifestRequest=Ri(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(ns).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;xe(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:a}=this.params,s=n=>{let o=[];return n?.length?(n.forEach((u,l)=>{u.video&&a.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({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))},EE))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var ie=require("@vkontakte/videoplayer-shared"),Ro=class{constructor(){this.onDroopedVideoFramesLimit$=new ie.Subject;this.subscription=new ie.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new ie.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,ie.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,a=t-this.prevDroppedVideoFrames,s=1-(i-a)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&(0,ie.isHigher)(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add((0,ie.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,ie.interval)(this.droppedFramesChecker.checkTime).pipe((0,ie.filter)(()=>this.playing),(0,ie.filter)(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe((0,ie.debounce)(this.droppedFramesChecker.checkTime)),i=(0,ie.merge)(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),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(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[a])=>(0,ie.isLower)(i,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}},os=Ro;var us=require("@vkontakte/videoplayer-shared"),om=require("@vkontakte/videoplayer-shared");var yr=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var AE=(r,e)=>new us.Observable(t=>{if(!window.IntersectionObserver)return;let i={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||yr()))},{...i,...e});a.observe(r);let s=(0,om.fromEvent)(document,"visibilitychange").pipe((0,us.map)(n=>!document.hidden||yr())).subscribe(n=>t.next(n));return()=>{a.unobserve(r),s.unsubscribe}}),Ue=AE;var wE=["paused","playing","ready"],RE=["paused","playing","ready"],Tr=class{constructor(e){this.subscription=new V.Subscription;this.videoState=new q("stopped");this.representations$=new V.ValueSubject([]);this.textTracksManager=new qe;this.droppedFramesManager=new os;this.maxSeekBackTime$=new V.ValueSubject(1/0);this.zeroTime$=new V.ValueSubject(void 0);this.liveOffset=new vt;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:V.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let a of t){let s=a.name??a.index.toString(10),n=Dt(a.name)??(0,V.videoSizeToQuality)(a.video),o=a.bitrate/1e3,u={...a.video};if(!n)continue;let l={id:s,quality:n,bitrate:o,size:u};i.push({track:l,representation:a})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:a})=>a)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:a})=>a===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),(0,V.isNonNullable)(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);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(),i=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: ${i}; seekState: ${JSON.stringify(s)};`}),i==="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(RE.includes(e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&wE.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(he(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=a?.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="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 u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(he(this.params.source.url,u))}return;default:return(0,V.assertNever)(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:V.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:a})};(0,V.merge)(this.videoState.stateChangeStarted$.pipe((0,V.map)(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,V.map)(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=ye(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ue(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=Ee(this.video);this.subscription.add(this.representations$.pipe((0,V.map)(a=>a.map(({track:s})=>s)),(0,V.filter)(a=>!!a.length),(0,V.once)()).subscribe(a=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:a}))),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((0,V.filterChanged)(),(0,V.map)(a=>-a/1e3)).subscribe(this.params.output.duration$)).add((0,V.combine)({zeroTime:this.zeroTime$.pipe((0,V.filter)(V.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(nt(this.video,this.params.desiredState.isLooped,t)).add(Ie(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Fe(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ue(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&(0,V.videoQualityToHeight)(a);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:a})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return(0,V.assertNever)(a.to)}},t)).add((0,V.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,V.observableFrom)(["init"])).pipe((0,V.debounce)(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Te(this.video)}createLiveDashPlayer(){let e=new vr({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(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),a=!i&&(0,V.isNonNullable)(t)?t:Bt(e.map(({track:l})=>l),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput: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,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),u&&this.setAutoQuality(i),n||u||s!==o){let l=e.find(({track:c})=>c.id===s)?.representation;(0,V.assertNonNullable)(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;(0,V.assertNonNullable)(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),a=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(he(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var um=Tr;var ut=(r,e)=>{let t=0;for(let i=0;i<r.length;i++){let a=r.start(i)*1e3,s=r.end(i)*1e3;a<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var B=require("@vkontakte/videoplayer-shared");var ls=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let a=0,s=i.length;a<s;a++)if(i[a].callback===t){i.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let a=0,s=i.length;a<s;a++){let n=i[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}},$i=class extends ls{constructor(){super(),this.listeners||ls.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)}},Ir=class{constructor(){Object.defineProperty(this,"signal",{value:new $i,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 i=e;if(i===void 0)if(typeof document>"u")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch{i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(Ir.prototype[Symbol.toStringTag]="AbortController",$i.prototype[Symbol.toStringTag]="AbortSignal");function cs(r){return r.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof r.Request=="function"&&!r.Request.prototype.hasOwnProperty("signal")||!r.AbortController}function $o(r){typeof r=="function"&&(r={fetch:r});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=r;if(!cs({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||a)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let h=new t(l,c);return d&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),h},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.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 h=new Promise((m,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([h,n(u,l)])}return n(u,l)},Request:s}}var Er=cs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),lm=Er?$o({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,It=Er?lm.fetch:window.fetch,u$=Er?lm.Request:window.Request,Ce=Er?Ir:window.AbortController,l$=Er?$i:window.AbortSignal;var hs=Be(wi(),1);var Et=()=>window.ManagedMediaSource||window.MediaSource,ds=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),cm=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),dm=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var lt=require("@vkontakte/videoplayer-shared"),ms=document.createElement("video"),ME='video/mp4; codecs="avc1.42000a,mp4a.40.2"',CE='video/mp4; codecs="hev1.1.6.L93.B0"',pm='video/webm; codecs="vp09.00.10.08"',hm='video/webm; codecs="av01.0.00M.08"',DE='audio/mp4; codecs="mp4a.40.2"',VE='audio/webm; codecs="opus"',xr={mms:ds(),mse:cm(),hls:!!(ms.canPlayType?.("application/x-mpegurl")||ms.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Pe={mp4:!!ms.canPlayType?.("video/mp4"),webm:!!ms.canPlayType?.("video/webm"),cmaf:!0},ke={h264:!!Et()?.isTypeSupported?.(ME),h265:!!Et()?.isTypeSupported?.(CE),vp9:!!Et()?.isTypeSupported?.(pm),av1:!!Et()?.isTypeSupported?.(hm),aac:!!Et()?.isTypeSupported?.(DE),opus:!!Et()?.isTypeSupported?.(VE)},Li=(ke.h264||ke.h265)&&ke.aac,Jt,BE=async()=>{if(!window.navigator.mediaCapabilities)return;let r={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...r,video:{...r.video,contentType:hm}}),window.navigator.mediaCapabilities.decodingInfo({...r,video:{...r.video,contentType:pm}})]);Jt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{BE()}catch(r){console.error(r)}var Mi=xr.hls&&Pe.mp4,mm=()=>Object.keys(ke).filter(r=>ke[r]),fm=(r,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:i})=>{let a=xr.mse&&(!i||!!window.MediaStreamTrack)||xr.mms&&t;return r.filter(s=>{switch(s){case"DASH_SEP":return a&&Pe.mp4&&Li;case"DASH_WEBM":return a&&Pe.webm&&ke.vp9&&ke.opus;case"DASH_WEBM_AV1":return a&&Pe.webm&&ke.av1&&ke.opus;case"DASH_STREAMS":return a&&(Pe.mp4&&Li||Pe.webm&&(ke.vp9||ke.av1)&&(ke.opus||ke.aac));case"DASH_LIVE":return a&&Pe.mp4&&Li;case"DASH_LIVE_CMAF":return a&&Pe.mp4&&Li&&Pe.cmaf;case"DASH_ONDEMAND":return a&&Pe.mp4&&Li;case"HLS":case"HLS_ONDEMAND":return Mi||e&&a&&Pe.mp4&&Li;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Mi;case"MPEG":return Pe.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return xr.webrtc&&xr.ws&&ke.h264&&(Pe.mp4||Pe.webm);default:return(0,lt.assertNever)(s)}})},ps=r=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(r){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return Jt?Jt[t].smooth?[t,e]:Jt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Jt?Jt[t].powerEfficient?[t,e]:Jt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:(0,lt.assertNever)(r)}return[e,t]},bm=({webmCodec:r,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...ps(r),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],a=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(lt.clientChecker.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...a,"MPEG",...ps(r),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...ps(r),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...ps(r),...a,"HLS","HLS_ONDEMAND"];default:(0,lt.assertNever)(e)}return Mi?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},gm=({androidPreferredFormat:r,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],a=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...a],n=[...a,...i],o,u=lt.clientChecker.isMac&<.clientChecker.isSafari;if(lt.clientChecker.isAndroid)switch(r){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,lt.assertNever)(r)}else Mi&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Lo=r=>r?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Sm=r=>{if(r.size===0)return;if(r.size===1){let t=r.values().next();return(0,hs.default)(t.value.split("."),0)}for(let t of r){let i=(0,hs.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=r.values().next();return(0,hs.default)(e.value.split("."),0)};var Ci=require("@vkontakte/videoplayer-shared"),vm=r=>{if(!r)return{id:"EmptyResponse",category:Ci.ErrorCategory.PARSER,message:"Empty response"};if(r.length<=2&&r.match(/^\d+$/))return{id:`UVError#${r}`,category:Ci.ErrorCategory.NETWORK,message:`UV Error ${r}`};let e=r.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Ci.ErrorCategory.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(r,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Ci.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Ci.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var Ot=(r,e,t=0)=>{for(let i=0;i<r.length;i++)if(r.start(i)*1e3-t<=e&&r.end(i)*1e3+t>e)return!0;return!1};var S=require("@vkontakte/videoplayer-shared");var Oi=Be(wi(),1);var OE=(r,e={})=>{let i=e.timeout||1,a=performance.now();return window.setTimeout(()=>{r({get didTimeout(){return e.timeout?!1:performance.now()-a-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-a))}})},1)},_E=r=>window.clearTimeout(r),ym=r=>typeof r=="function"&&r?.toString().endsWith("{ [native code] }"),Tm=!ym(window.requestIdleCallback)||!ym(window.cancelIdleCallback),Mo=Tm?OE:window.requestIdleCallback,T$=Tm?_E:window.cancelIdleCallback;var df=Be(is(),1);var He=require("@vkontakte/videoplayer-shared"),NE=18,Im=!1;try{Im=He.clientChecker.isSafari&&!!He.clientChecker.macVersion&&He.clientChecker.macVersion<=NE}catch(r){console.error(r)}var Co=class{constructor(e){this.bufferFull$=new He.Subject;this.error$=new He.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:He.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(i=>{let a={operation:"append",data:e,signal:t,callback:i};this.queue.push(a),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(a=>{let s={operation:"remove",from:e,to:t,signal:i,callback:a};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i;Im&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(let{callback:a}of this.queue)a(!1);i&&(this.queue=[i]),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:He.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,He.assertNever)(t)}}},Em=Co;var Do=r=>{let e=0;for(let t=0;t<r.length;t++)e+=r.end(t)-r.start(t);return e*1e3};var T=require("@vkontakte/videoplayer-shared");var K=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i: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 Di=class extends K{};var Pr=class extends K{};var kr=class extends K{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let a=this.readString(4);this.compatibleBrands.push(a),i-=4}}};var Ar=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var re=class extends K{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var wr=class extends re{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var Rr=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var $r=class extends K{constructor(e,t){super(e,t),this.data=this.content}};var Xt=class extends re{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let a=this.readUint32(),s=a>>>31,n=a<<1>>>1,o=this.readUint32();a=this.readUint32();let u=a>>>28,l=a<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var Lr=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Mr=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Cr=class extends re{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Dr=class extends re{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Vr=class extends re{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Br=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Or=class extends re{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var _r=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Nr=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Fr=class extends re{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var qr=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ur=class extends re{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Hr=class extends re{constructor(t,i){super(t,i);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 jr=class extends re{constructor(t,i){super(t,i);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 qE={ftyp:kr,moov:Ar,mvhd:wr,moof:Rr,mdat:$r,sidx:Xt,trak:Lr,mdia:Br,mfhd:Fr,tkhd:Or,traf:qr,tfhd:Ur,tfdt:Hr,trun:jr,minf:_r,sv3d:Mr,st3d:Cr,prhd:Dr,proj:Nr,equi:Vr,uuid:Pr,unknown:Di},_t=class r{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch{break}return t}createBox(e,t){let i=qE[e];return i?new i(t,new r):new Di(t,new r)}};var Zt=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 HE=new TextDecoder("ascii"),jE=r=>HE.decode(new DataView(r.buffer,r.byteOffset+4,4))==="ftyp",GE=r=>{let e=new Xt(r,new _t),t=e.earliestPresentationTime/e.timescale*1e3,i=r.byteOffset+r.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:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},QE=(r,e)=>{let i=new _t().parse(r),a=new Zt(i),s=a.findAll("moof"),n=e?a.findAll("uuid"):a.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(r.buffer,l,d)},WE=r=>{let t=new _t().parse(r);return new Zt(t).find("sidx")?.timescale},YE=(r,e)=>{let i=new _t().parse(r),s=new Zt(i).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,h)=>d+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},zE=r=>{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}}},i=new _t().parse(r),a=new Zt(i);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 u=a.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},xm={validateData:jE,parseInit:zE,getIndexRange:()=>{},parseSegments:GE,parseFeedableSegmentChunk:QE,getChunkEndTime:YE,getTimescaleFromIndex:WE};var xt=require("@vkontakte/videoplayer-shared");var km=require("@vkontakte/videoplayer-shared");var Pm={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"}},Am=r=>{let e=r.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=Gr(r,t),a=i in Pm,s=a?Pm[i].type:"binary",n=r.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 u=new DataView(r.buffer,r.byteOffset+t+1,o-1),l=n&255>>o,c=Gr(u),d=l*2**((o-1)*8)+c,h=t+o,m;return h+d>r.byteLength?m=new DataView(r.buffer,r.byteOffset+h):m=new DataView(r.buffer,r.byteOffset+h,d),{tag:a?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:h,tagSize:h+d,value:m,valueSize:d}},Gr=(r,e=r.byteLength)=>{switch(e){case 1:return r.getUint8(0);case 2:return r.getUint16(0);case 3:return r.getUint8(0)*2**16+r.getUint16(1);case 4:return r.getUint32(0);case 5:return r.getUint8(0)*2**32+r.getUint32(1);case 6:return r.getUint16(0)*2**32+r.getUint32(2);case 7:{let t=r.getUint8(0)*281474976710656+r.getUint16(1)*4294967296+r.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Xe=(r,e)=>{switch(e){case"int":return r.getInt8(0);case"uint":return Gr(r);case"float":return r.byteLength===4?r.getFloat32(0):r.getFloat64(0);case"string":return new TextDecoder("ascii").decode(r);case"utf8":return new TextDecoder("utf-8").decode(r);case"date":return new Date(Date.UTC(2001,0)+r.getInt8(0)).getTime();case"master":return r;case"binary":return r;default:(0,km.assertNever)(e)}},ei=(r,e)=>{let t=0;for(;t<r.byteLength;){let i=new DataView(r.buffer,r.byteOffset+t),a=Am(i);if(!e(a))return;a.type==="master"&&ei(a.value,e),t=a.value.byteOffset-r.byteOffset+a.valueSize}},wm=r=>{if(r.getUint32(0)!==440786851)return!1;let e,t,i,a=Am(r);return ei(a.value,({tag:s,type:n,value:o})=>(s===17143?e=Xe(o,n):s===17026?t=Xe(o,n):s===17029&&(i=Xe(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Rm=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],KE=[231,22612,22743,167,171,163,160,175],JE=r=>{let e,t,i,a,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return ei(r,({tag:h,type:m,value:f,valueSize:g})=>{if(h===21419){let y=Xe(f,m);l=Gr(y)}else h!==21420&&(l=void 0);return h===408125543?(e=f.byteOffset,t=f.byteOffset+g):h===357149030?s=!0:h===290298740?n=!0:h===2807729?i=Xe(f,m):h===17545?a=Xe(f,m):h===21420&&l===475249515?u=Xe(f,m):h===374648427?ei(f,({tag:y,type:I,value:P})=>y===30321?(c=Xe(P,I)===1,!1):!0):s&&n&&Rm.includes(h)&&(o=!0),!o}),(0,xt.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,xt.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,xt.assertNonNullable)(a,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(a/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},XE=r=>{if((0,xt.isNullable)(r.cuesSeekPosition))return;let e=r.segmentStart+r.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},ZE=(r,e)=>{let t=!1,i=!1,a=o=>(0,xt.isNonNullable)(o.time)&&(0,xt.isNonNullable)(o.position),s=[],n;return ei(r,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&a(n)&&s.push(n),n={};break;case 179:n&&(n.time=Xe(l,u));break;case 183:break;case 241:n&&(n.position=Xe(l,u));break;default:t&&Rm.includes(o)&&(i=!0)}return!(t&&i)}),n&&a(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},ex=r=>{let e=0,t=!1;try{ei(r,i=>i.tag===524531317?i.tagSize<=r.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):KE.includes(i.tag)?(e+i.tagSize<=r.byteLength&&(e+=i.tagSize,t||=[163,160,175].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=r.byteLength&&t?new DataView(r.buffer,r.byteOffset,e):null},$m={validateData:wm,parseInit:JE,getIndexRange:XE,parseSegments:ZE,parseFeedableSegmentChunk:ex};var Qr=r=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(r);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return $m;case"mp4":return xm}}throw new ReferenceError(`Unsupported mime type ${r}`)},Lm=r=>"getChunkEndTime"in r;var Uo=Be(Zm(),1),af=Be(wi(),1);var qo=r=>{let e=r.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[a,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[a,s,n]=i;return!!(a&&parseInt(a,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let a=i[0];if(!a||a.length!==6)return!1;let[s,n]=a.toUpperCase(),o=s+n;return["6E","7A","F4"].includes(o)}}return!1};var Bi=require("@vkontakte/videoplayer-shared");var ef=r=>{if(r.includes("/")){let e=r.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(r)};var tf=r=>{try{let e=Dx(),t=r.match(e),{groups:i}=t??{};if(i){let a={};if(i.extensions){let o=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(o||[]).forEach(u=>{a[u[0]]=u.slice(2)})}let s=i.variants?.split(/-/).filter(o=>o!==""),n={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:a,variants:s};return Object.keys(n).forEach(o=>{let u=n[o];(typeof u>"u"||u==="")&&delete n[o]}),n}return null}catch{return null}};function Dx(){let r="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
|
|
62
62
|
(?<language>${`(?:[a-z]{2,3}(?:-${r})?|[a-z]{4}|[a-z]{5,8})`})
|
|
63
63
|
(-(?<script>[a-z]{4}))?
|
|
64
64
|
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
65
65
|
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
66
66
|
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
67
67
|
(?:-(?<privateuse>(?:${e})))?
|
|
68
|
-
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var sf=r=>{if(!r.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(r),a=i?.[1]==="-"?-1:1,s={days:e(i?.[5],a),hours:e(i?.[6],a),minutes:e(i?.[7],a),seconds:e(i?.[8],a)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},kt=(r,e)=>{let t=r;t=(0,jo.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[a,s]of Object.entries(i)){let n=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=(0,jo.default)(t,n,(o,u)=>(0,Oi.isNullable)(s)?o:(0,Oi.isNullable)(u)?s:s.padStart(parseInt(u,10),"0"))}return t},of=(r,e)=>{let i=new DOMParser().parseFromString(r,"application/xml"),a={video:[],audio:[],text:[]},s=i.children[0],n=s.getElementsByTagName("Period")[0],o=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(x=>x.textContent?.trim()??""),u=(0,nf.default)(o,0)??"",l=n.children,c=s.getAttribute("type")==="dynamic",d=s.getAttribute("availabilityStartTime"),p=d?new Date(d).getTime():void 0,m,f=s.getAttribute("mediaPresentationDuration"),g=n.getAttribute("duration"),I=s.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)m=sf(f);else if(g){let x=sf(g);(0,Oi.isNonNullable)(x)&&(m=x)}else I&&(m=parseInt(I,10));let P=0,k=s.getAttribute("profiles")?.split(",")??[];for(let x of l){let N=x.getAttribute("id")??"id"+(P++).toString(10),Y=x.getAttribute("mimeType")??"",J=x.getAttribute("codecs")??"",z=x.getAttribute("contentType")??Y?.split("/")[0],ee=x.getAttribute("profiles")?.split(",")??[],E=af(x.getAttribute("lang")??"")??{},w=x.querySelector("Label")?.textContent?.trim()??void 0,Z=x.querySelectorAll("Representation"),Re=x.querySelector("SegmentTemplate"),Qe=x.querySelector("Role")?.getAttribute("value")??void 0,R=z,j={id:N,language:E.language,isDefault:Qe==="main",label:w,codecs:J,hdr:R==="video"&&Ho(J),mime:Y,representations:[]};for(let O of Z){let oe=O.getAttribute("lang")??void 0,de=O.getAttribute("label")??void 0,Rt=O.querySelector("BaseURL")?.textContent?.trim()??"",si=new URL(Rt||u,e).toString(),Ut=O.getAttribute("mimeType")??Y,W=O.getAttribute("codecs")??J??"",pe;if(z==="text"){let ne=O.getAttribute("id")||"",ye=E.privateuse?.includes("x-auto")||ne.includes("_auto"),$e=O.querySelector("SegmentTemplate");if($e){let ht={representationId:O.getAttribute("id")??void 0,bandwidth:O.getAttribute("bandwidth")??void 0},it=parseInt(O.getAttribute("bandwidth")??"",10)/1e3,mt=parseInt($e.getAttribute("startNumber")??"",10)??1,rt=parseInt($e.getAttribute("timescale")??"",10),ni=$e.querySelectorAll("SegmentTimeline S")??[],oi=$e.getAttribute("media");if(!oi)continue;let ha=[],ma=0,fa="",ui=0,qi=mt,fe=0;for(let We of ni){let Ht=parseInt(We.getAttribute("d")??"",10),Be=parseInt(We.getAttribute("r")??"",10)||0,$t=parseInt(We.getAttribute("t")??"",10);fe=Number.isFinite($t)?$t:fe;let jt=Ht/rt*1e3,li=fe/rt*1e3;for(let at=0;at<Be+1;at++){let Lt=kt(oi,{...ht,segmentNumber:qi.toString(10),segmentTime:(fe+at*Ht).toString(10)}),ci=(li??0)+at*jt,Hi=ci+jt;qi++,ha.push({time:{from:ci,to:Hi},url:Lt})}fe+=(Be+1)*Ht,ma+=(Be+1)*jt}ui=fe/rt*1e3,fa=kt(oi,{...ht,segmentNumber:qi.toString(10),segmentTime:fe.toString(10)});let Ui={time:{from:ui,to:1/0},url:fa},ft={type:"template",baseUrl:si,segmentTemplateUrl:oi,initUrl:"",totalSegmentsDurationMs:ma,segments:ha,nextSegmentBeyondManifest:Ui,timescale:rt};pe={id:ne,kind:"text",segmentReference:ft,profiles:[],duration:m,bitrate:it,mime:"",codecs:"",width:0,height:0,isAuto:ye}}else pe={id:ne,isAuto:ye,kind:"text",url:si}}else{let ne=O.getAttribute("contentType")??Ut?.split("/")[0]??z,ye=x.getAttribute("profiles")?.split(",")??[],$e=parseInt(O.getAttribute("width")??"",10),ht=parseInt(O.getAttribute("height")??"",10),it=parseInt(O.getAttribute("bandwidth")??"",10)/1e3,mt=O.getAttribute("frameRate")??"",rt=O.getAttribute("quality")??void 0,ni=mt?rf(mt):void 0,oi=O.getAttribute("id")??"id"+(P++).toString(10),ha=ne==="video"?`${ht}p`:ne==="audio"?`${it}Kbps`:W,ma=`${oi}@${ha}`,fa=[...k,...ee,...ye],ui,qi=O.querySelector("SegmentBase"),fe=O.querySelector("SegmentTemplate")??Re;if(qi){let ft=O.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[We,Ht]=ft.split("-").map(Lt=>parseInt(Lt,10)),Be={from:We,to:Ht},$t=O.querySelector("SegmentBase")?.getAttribute("indexRange"),[jt,li]=$t?$t.split("-").map(Lt=>parseInt(Lt,10)):[],at=$t?{from:jt,to:li}:void 0;ui={type:"byteRange",url:si,initRange:Be,indexRange:at}}else if(fe){let ft={representationId:O.getAttribute("id")??void 0,bandwidth:O.getAttribute("bandwidth")??void 0},We=parseInt(fe.getAttribute("timescale")??"",10),Ht=fe.getAttribute("initialization")??"",Be=fe.getAttribute("media"),$t=parseInt(fe.getAttribute("startNumber")??"",10)??1,jt=kt(Ht,ft);if(!Be)throw new ReferenceError("No media attribute in SegmentTemplate");let li=fe.querySelectorAll("SegmentTimeline S")??[],at=[],Lt=0,ci="",Hi=0;if(li.length){let ba=$t,Ye=0;for(let di of li){let st=parseInt(di.getAttribute("d")??"",10),Gt=parseInt(di.getAttribute("r")??"",10)||0,ga=parseInt(di.getAttribute("t")??"",10);Ye=Number.isFinite(ga)?ga:Ye;let $s=st/We*1e3,Uf=Ye/We*1e3;for(let Sa=0;Sa<Gt+1;Sa++){let Hf=kt(Be,{...ft,segmentNumber:ba.toString(10),segmentTime:(Ye+Sa*st).toString(10)}),nu=(Uf??0)+Sa*$s,jf=nu+$s;ba++,at.push({time:{from:nu,to:jf},url:Hf})}Ye+=(Gt+1)*st,Lt+=(Gt+1)*$s}Hi=Ye/We*1e3,ci=kt(Be,{...ft,segmentNumber:ba.toString(10),segmentTime:Ye.toString(10)})}else if((0,Oi.isNonNullable)(m)){let Ye=parseInt(fe.getAttribute("duration")??"",10)/We*1e3,di=Math.ceil(m/Ye),st=0;for(let Gt=1;Gt<di;Gt++){let ga=kt(Be,{...ft,segmentNumber:Gt.toString(10),segmentTime:st.toString(10)});at.push({time:{from:st,to:st+Ye},url:ga}),st+=Ye}Hi=st,ci=kt(Be,{...ft,segmentNumber:di.toString(10),segmentTime:st.toString(10)})}let qf={time:{from:Hi,to:1/0},url:ci};ui={type:"template",baseUrl:si,segmentTemplateUrl:Be,initUrl:jt,totalSegmentsDurationMs:Lt,segments:at,nextSegmentBeyondManifest:qf,timescale:We}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ne||!Ut)continue;let Ui={video:"video",audio:"audio",text:"text"}[ne];if(!Ui)continue;R||=Ui,pe={id:ma,kind:Ui,segmentReference:ui,profiles:fa,duration:m,bitrate:it,mime:Ut,codecs:W,width:$e,height:ht,fps:ni,quality:rt}}j.language||=oe,j.label||=de,j.mime||=Ut,j.codecs||=W,j.hdr||=R==="video"&&Ho(W),j.representations.push(pe)}R&&a[R].push(j)}return{dynamic:c,liveAvailabilityStartTime:p,duration:m,streams:a,baseUrls:o}};var Wo=Oe(Ri(),1);var uf=require("@vkontakte/videoplayer-shared"),lf=({id:r,width:e,height:t,bitrate:i,fps:a,quality:s})=>{let n=(s?Vt(s):void 0)??(0,uf.videoSizeToQuality)({width:e,height:t});return n&&{id:r,quality:n,bitrate:i,size:{width:e,height:t},fps:a}},cf=({id:r,bitrate:e})=>({id:r,bitrate:e}),df=({language:r,label:e},{id:t,url:i,isAuto:a})=>({id:t,url:i,isAuto:a,type:"internal",language:r,label:e}),pf=({language:r,label:e,id:t,url:i,isAuto:a})=>({id:t,url:i,isAuto:a,type:"internal",language:r,label:e}),Yo=({id:r,language:e,label:t,codecs:i,isDefault:a})=>({id:r,language:e,label:t,codec:(0,Wo.default)(i.split("."),0),isDefault:a}),zo=({id:r,language:e,label:t,hdr:i,codecs:a})=>({id:r,language:e,hdr:i,label:t,codec:(0,Wo.default)(a.split("."),0)}),Ko=r=>"url"in r,Ve=r=>r.type==="template",Yr=r=>r instanceof DOMException&&(r.name==="AbortError"||r.code===20);var zr=class{constructor(e,t,i,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentSegmentLength$=new T.ValueSubject(0);this.onLastSegment$=new T.ValueSubject(!1);this.fullyBuffered$=new T.ValueSubject(!1);this.playingRepresentation$=new T.ValueSubject(void 0);this.playingRepresentationInit$=new T.ValueSubject(void 0);this.error$=new T.Subject;this.gaps=[];this.subscription=new T.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new me;this.switchAbortController=new me;this.destroyAbortController=new me;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,T.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,T.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.resetAccumulateBufferAfterStall(),this.startAccumulateBuffer(),this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Pm(this.sourceBuffer),this.subscription.add((0,T.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:T.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add((0,T.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:T.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,Bo(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=ct(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),a=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,T.assertNonNullable)(i,"No init buffer for starting representation"),(0,T.assertNonNullable)(a,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(a,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchToOld=(0,T.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,T.assertNonNullable)(i,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if((0,T.isNullable)(s)||(0,T.isNullable)(a)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),(0,T.assertNonNullable)(a,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,T.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=(0,T.abortable)(this.destroyAbortController.signal,async function*(e){let t=e?.flatMap(u=>u.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let u of this.representations.keys()){let l=t.find(p=>p.id===u);l&&this.representations.set(u,l);let c=this.representations.get(u);if(!c||!Ve(c.segmentReference))return;let d=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,d)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,a=this.representations.get(i);(0,T.assertNonNullable)(a);let s=this.segments.get(i);(0,T.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(i);if((0,T.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,a),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=a,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!l?.dynamic,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new me,(0,T.abortable)(this.switchAbortController.signal,async function*(i,a=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);(0,T.assertNonNullable)(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if((0,T.isNullable)(o)||(0,T.isNullable)(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),(0,T.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer)){if(this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),a)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();(0,T.isNonNullable)(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new me,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,T.isNullable)(e)||(0,T.isNullable)(this.downloadingRepresentationId)||(0,T.isNullable)(this.playingRepresentationId)||(0,T.isNullable)(this.sourceBuffer)||(0,T.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if((0,T.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let a=i.find(l=>e>=l.time.from&&e<l.time.to);this.currentSegmentLength$.next((a?.time.to??0)-(a?.time.from??0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=ct(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)&&Bo(this.sourceBuffer.buffered)>=this.bufferLimit){let l=ct(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<c);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,s),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(o.includes(a))l="high";else{let c=(0,_i.default)(o,0);c&&c.time.from-a.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l)}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!o.length&&ct(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,_i.default)(i,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,a=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+a}),i=s.time.to;(0,T.isNonNullable)(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=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<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[a[0]]:a}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind].flatMap(a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=e?.streams[this.kind].flatMap(i=>i.representations)??[];for(let i of t){if(!i||!Ve(i.segmentReference))return;let a=i.segmentReference.segments.map(u=>({...u,status:"none",size:void 0})),s=this.segments.get(i.id)??[],n=(0,_i.default)(s,-1)?.time.to??0,o=a?.findIndex(u=>Math.floor(n)>=Math.floor(u.time.from)&&Math.floor(n)<=Math.floor(u.time.to));if(o===-1){this.liveUpdateSegmentIndex=0;let u=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,u)}else{let u=a.slice(o+1);this.segments.set(i.id,[...s,...u])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,T.assertNonNullable)(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}startAccumulateBuffer(){this.bufferAccumulation.enabled=!0}resetAccumulateBufferAfterStall(){(0,T.assertNonNullable)(this.playingRepresentationId);let e=this.representations.get(this.playingRepresentationId)?.duration;(0,T.assertNonNullable)(e);let{shortVideoDuration:t,shortVideoBufferStallSize:i,longVideoBufferStallSize:a}=this.tuning.dash.accumulationBufferStallSize;this.bufferAccumulation={enabled:!1,targetBufferSizeMs:e<=t?i:a,accumulatedBufferSizeMs:0,accumulated:[]}}updateLowLatencyLiveIfNeeded(e){for(let t of this.representations.values()){let i=t.segmentReference;if(!Ve(i))return;let a=this.segments.get(t.id)??[],s=a.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(s&&!isFinite(s.time.to)&&(s.time.to=e.time.to),!!!a.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*i.timescale/1e3).toString(10),u=kt(i.segmentTemplateUrl,{segmentTime:o});a.push({status:"none",time:{from:e.time.to,to:1/0},url:u})}}}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.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.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(a=>t>=a.time.from&&t<a.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let a=e.findIndex(({status:d,time:{from:p,to:m}},f)=>{let g=p<=i&&m>=i,y=p>i||g||f===0&&i===0,I=Math.min(this.forwardBufferTarget,this.bufferLimit),P=this.preloadOnly&&p<=i+I||m<=i+I;return(d==="none"||d==="partially_ejected"&&y&&P&&this.sourceBuffer&&!(_t(this.sourceBuffer.buffered,p)&&_t(this.sourceBuffer.buffered,m)))&&y&&P});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<s.length&&(n<=l||o<=c);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,i="auto"){Ve(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="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:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await(0,T.abortable)(o,async function*(){let c=(0,T.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:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=(0,T.now)(),!c)return;let d=new DataView(c);if(!isFinite(a.segment.time.to)){let p=t.segmentReference.timescale,m=Wr(t.mime);a.segment.time.to=m.getChunkEndTime(d,p)}u&&a.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Yr(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Ve(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,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,T.abortable)(n,async function*(){let u=(0,T.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,T.fromEvent)(window,"online").pipe((0,T.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:a,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=(0,T.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Yr(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Ve(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,a={from:(0,_i.default)(e,0).byte.from,to:(0,_i.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:a,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,T.now)(),this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:a?a.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ve(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let a=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,T.now)();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:a,signal:s,onProgress:u,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:i,onSegmentAppendFailed:a,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){a();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=Wr(n.mime).parseFeedableSegmentChunk(l,this.isLive);c?.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:a,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){n();continue}let c=l.byte.from-i,d=l.byte.to-i,p=d-c+1,m=c<a,f=d<=a;if(!m)continue;let g=Wr(o.mime),y=this.tuning.dash.enableSubSegmentBufferFeeding&&(Dm(g)||this.bufferAccumulation.targetBufferSizeMs===0);if(l.status==="downloading"&&f){l.status="downloaded";let I=new DataView(e.buffer,e.byteOffset+c,p),P=this.getCurrentPosition();(0,T.isNonNullable)(P)&&(this.bufferAccumulation.accumulatedBufferSizeMs=l.time.to-P,this.bufferAccumulation.accumulated.push({dataView:I,segmentProgress:u}),this.activeSegments.delete(u));let k=async({dataView:C,segmentProgress:x})=>{await this.sourceBufferTaskQueue.append(C,s)&&!s.aborted?this.onSegmentFullyAppended(x,t):n()};this.bufferAccumulation.enabled&&this.bufferAccumulation.accumulatedBufferSizeMs>this.bufferAccumulation.targetBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(k),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||(0,T.isNullable)(P))&&(k({dataView:I,segmentProgress:u}),this.resetAccumulateBufferAfterStall())}else if(y&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,a-c),u.loadedBytes>u.feedingBytes)){let I=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),P=u.loadedBytes===p?I:g.parseFeedableSegmentChunk(I);P?.byteLength&&(l.status="partially_fed",u.feedingBytes+=P.byteLength,await this.sourceBufferTaskQueue.append(P,s)&&!s.aborted?(u.fedBytes+=P.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):n())}}}onSegmentFullyAppended(e,t){this.tuning.useSafariEndlessRequestBugfix&&((0,T.assertNonNullable)(this.sourceBuffer),_t(this.sourceBuffer.buffered,e.segment.time.from,100)&&_t(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"SafariEmptyAppendBuffer",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Safari stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Ko(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let a of this.segments.get(i.id)??[])a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none");(0,T.assertNonNullable)(this.sourceBuffer),this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment]),this.tuning.useNewPruneBufferStrategy&&this.pruneBuffer(this.getCurrentPosition(),1/0,!1)}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);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 i=this.representations.get(e);i&&(this.initLoadIdleCallback=Co(()=>(0,hf.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let a=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?(0,T.abortable)(this.destroyAbortController.signal,async function*(){let o=(0,T.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Wr(e.mime),a)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&Ve(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:T.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||(0,T.isNullable)(e)||this.sourceBuffer.updating)return!1;let a=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:p}=u[c],m=l[l.length-1];m.to>=d?m.to=Math.max(m.to,p):l.push(u[c])}return l},o=u=>{if(s>=t)return a;a.push({...u.time}),a=n(a);let l=Ko(u)?u.size??0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let m of p)["none","partially_ejected"].includes(m.status)&&Math.round(m.time.from)<=Math.round(l)&&Math.round(m.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(a.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return a.length?(await Promise.all(a.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!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)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!this.sourceBuffer.buffered.length||(0,T.isNullable)(e)?0:ct(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(this.sourceBuffer)for(let i of t){let a={representation:e,from:i.time.from,to:i.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<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){a=void 0;break}o>i.time.from&&o<i.time.to&&(a.from=o),n<i.time.to&&n>i.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){if(!this.gapDetectionIdleCallback){(0,T.assertNonNullable)(this.sourceBuffer);for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(a=>this.sourceBuffer&&(Math.round(a.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(a.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Co(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:T.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,T.isNullable)(this.sourceBuffer)||(0,T.isNullable)(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let a=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:a,to:s})}let t=100;for(let i of this.segments.values())for(let a of i){let{status:s}=a;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(a.time.from),o=Math.ceil(a.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.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 Kr=r=>{let e=new URL(r);return e.searchParams.set("quic","1"),e.toString()};var mf=r=>{let e=r.get("X-Delivery-Type"),t=r.get("X-Reused"),i=e===null?"http1":e??void 0,a=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:a}};var G=require("@vkontakte/videoplayer-shared");var ff=r=>{let e=new URL(r);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var bs=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:a=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new G.ValueSubject(void 0);this.lastConnectionReused$=new G.ValueSubject(void 0);this.lastRequestFirstBytes$=new G.ValueSubject(void 0);this.abortAllController=new me;this.subscription=new G.Subscription;this.fetchManifest=(0,G.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Kr(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=ff(i));let a=yield Ze(i,{signal:this.abortAllController.signal}).catch(Xr);return a?(t.log("success",(0,G.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(a.headers),a.text()):(t.error("error",(0,G.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,G.abortable)(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:a,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){let l=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let E=new URL(l,location.href);E.searchParams.append("bytes",`${i.from}-${i.to}`),l=E.toString();break}default:(0,G.assertNever)(t)}this.requestQuic&&(l=Kr(l));let p=this.abortAllController.signal,m;if(n){let E=new me;if(m=(0,G.merge)((0,G.fromEvent)(this.abortAllController.signal,"abort"),(0,G.fromEvent)(n,"abort")).subscribe(()=>{try{E.abort()}catch(w){Xr(w)}}),this.abortAllController.signal.aborted||n.aborted)try{E.abort()}catch(w){Xr(w)}p=E.signal}let f=(0,G.now)();d.log("startRequest",(0,G.flattenObject)({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:f}));let g=yield Ze(l,{priority:s,headers:c,signal:p}).catch(Xr),y=(0,G.now)();if(!g)return d.error("error",{message:"No response in request"}),d.end(),m?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(y-f),!g.ok||!g.body){m?.unsubscribe();let E=`Fetch error ${g.status}: ${g.statusText}`;return d.error("error",{message:E}),d.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!a&&!o){m?.unsubscribe();let E=(0,G.now)(),w={requestStartedAt:f,requestEndedAt:E,duration:E-f};return d.log("endRequest",(0,G.flattenObject)(w)),d.end(),g.arrayBuffer()}let[I,P]=g.body.tee(),k=I.getReader();o&&this.throughputEstimator?.trackStream(P,u);let C=0,x=new Uint8Array(0),N=!1,Y=E=>{m?.unsubscribe(),N=!0,Xr(E)},J=(0,G.abortable)(p,async function*({done:E,value:w}){if(C===0&&this.lastRequestFirstBytes$.next((0,G.now)()-f),p.aborted){m?.unsubscribe();return}if(!E&&w){let Z=new Uint8Array(x.length+w.length);Z.set(x),Z.set(w,x.length),x=Z,C+=w.byteLength,a?.(new DataView(x.buffer),C),yield k?.read().then(J,Y)}}.bind(this));yield k?.read().then(J,Y),m?.unsubscribe();let z=(0,G.now)(),ee={failed:N,requestStartedAt:f,requestEndedAt:z,duration:z-f};return N?(d.error("endRequest",(0,G.flattenObject)(ee)),d.end(),null):(d.log("endRequest",(0,G.flattenObject)(ee)),d.end(),x.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,G.abortable)(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:a,to:s}=e.initRange,n=a,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,a),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let p=new DataView(d,a-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let m=t.parseInit(p),f=e.indexRange??t.getIndexRange(m);if(!f)throw new ReferenceError("No way to load representation index");let g;if(u)g=new DataView(d,f.from-n,f.to-f.from+1);else{let I=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!I)return null;g=new DataView(I)}let y=t.parseSegments(g,m,f);return{init:m,dataView:new DataView(d),segments:y}}.bind(this));this.fetchTemplateRepresentation=(0,G.abortable)(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),a=yield this.fetch(i,{priority:t,measureThroughput:!1});return a?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(a)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=a,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=mf(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:a}=e;switch(a){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:(0,G.assertNever)(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Xr=r=>{if(!Yr(r))throw r};var ii=(r,e,t)=>t*e+(1-t)*r,Xo=(r,e)=>r.reduce((t,i)=>t+i,0)/e,bf=(r,e,t,i)=>{let a=0,s=t,n=Xo(r,e),o=e<i?e:i;for(let u=0;u<o;u++)r[s]>n?a++:a--,s=(r.length+s-1)%r.length;return Math.abs(a)===o};var Jr=require("@vkontakte/videoplayer-shared"),Ft=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 Jr.ValueSubject(e.initial),this.debounced$=new Jr.ValueSubject(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Se(`raw_${t}`),this.smoothedSeries$=new Se(`smoothed_${t}`),this.reportedSeries$=new Se(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;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,Jr.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 gs=class extends Ft{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ii(this.slow,e,this.params.emaAlphaSlow),this.fast=ii(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Ss=class extends Ft{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Xo(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ii(this.emaSmoothed,e,this.params.emaAlpha);let i=bf(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var vs=class extends Ft{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?ii(this.smoothed,t,this.params.emaAlpha):t}};var ri=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new gs({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Ss({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new vs({initial:e,label:"liveEdgeDelay",...t})}};var Jo=(r,e)=>{r&&r.playbackRate!==e&&(r.playbackRate=e)};var ys=require("@vkontakte/videoplayer-shared");var Zr=class r{constructor(e,t){this.currentRepresentation$=new ys.ValueSubject(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!(0,ys.isNullable)(e))for(let t of this.representations)for(let i of t){let a=i.segmentReference,s=a.segments.length,n=a.segments[0].time.from,o=a.segments[s-1].time.to;if(e<n||e>o)continue;let u=a.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,a.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=r.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>r.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&Ve(t.segmentReference))}};var Nx=["timeupdate","progress","play","seeked","stalled","waiting"],Fx=["timeupdate","progress","loadeddata","playing","seeked"];var Ts=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new S.Subscription;this.representationSubscription=new S.Subscription;this.state$=new q("none");this.currentVideoRepresentation$=new S.ValueSubject(void 0);this.currentVideoRepresentationInit$=new S.ValueSubject(void 0);this.currentAudioRepresentation$=new S.ValueSubject(void 0);this.currentVideoSegmentLength$=new S.ValueSubject(0);this.currentAudioSegmentLength$=new S.ValueSubject(0);this.error$=new S.Subject;this.lastConnectionType$=new S.ValueSubject(void 0);this.lastConnectionReused$=new S.ValueSubject(void 0);this.lastRequestFirstBytes$=new S.ValueSubject(void 0);this.currentLiveTextRepresentation$=new S.ValueSubject(null);this.isLive$=new S.ValueSubject(!1);this.liveDuration$=new S.ValueSubject(0);this.liveAvailabilityStartTime$=new S.ValueSubject(void 0);this.bufferLength$=new S.ValueSubject(0);this.liveLoadBufferLength$=new S.ValueSubject(0);this.livePositionFromPlayer$=new S.ValueSubject(0);this.isLowLatency$=new S.ValueSubject(!1);this.isActiveLowLatency$=new S.ValueSubject(!1);this.currentStallDuration$=new S.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new S.ValueSubject(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new S.Subject;this.gapWatchdogActive=!1;this.destroyController=new me;this.initManifest=(0,S.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=he(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:S.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,S.abortable)(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:S.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=of(e??"",this.manifestUrlString)}catch(n){let o=Tm(e)??{id:"ManifestParsing",category:S.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(o)}if(!t)return null;let i=(n,o,u)=>!!(this.element?.canPlayType?.(o)&&xt()?.isTypeSupported?.(`${o}; codecs="${u}"`)||n==="text");t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let a={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let u=t.streams[n].filter(({mime:d,codecs:p})=>i(n,d,p)),l=new Set(u.map(({codecs:d})=>d)),c=ym(l);if(c&&(a[n]=u.filter(({codecs:d})=>d.startsWith(c))),n==="video"){let d=this.tuning.preferHDR,p=a.video.some(f=>f.hdr),m=a.video.some(f=>!f.hdr);S.clientChecker.isHDR&&d&&p?a.video=a.video.filter(f=>f.hdr):m&&(a.video=a.video.filter(f=>!f.hdr))}}let s={...t,streams:a};return this.tracer.log("updateManifestEnd",(0,S.flattenObject)(s)),s}.bind(this));this.initRepresentations=(0,S.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",(0,S.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,S.assertNonNullable)(this.manifest),(0,S.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=p=>{this.representationSubscription.add((0,S.fromEvent)(p,"error").pipe((0,S.filter)(m=>!!this.element?.played.length)).subscribe(m=>{this.error$.next({id:"VideoSource",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:m})}))};this.source=this.tuning.useManagedMediaSource?hm():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&ps())if(i){let p=document.createElement("source");a(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.isLowLatency$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,m)=>[...p,...m.representations],[]);if(this.videoBufferManager=new zr("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,S.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((m,f)=>[...m,...f.representations],[]);this.audioBufferManager=new zr("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Zr.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Zr(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,S.interval)(1e3).subscribe(p=>{if(this.element?.paused){let m=vo(this.manifestUrlString,2);this.manifestUrlString=he(this.manifestUrlString,m+1e3,2)}}));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,S.merge)(...Fx.map(p=>(0,S.fromEvent)(this.element,p))).pipe((0,S.map)(p=>this.element?ct(this.element.buffered,this.element.currentTime*1e3):0),(0,S.filterChanged)(),(0,S.tap)(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,S.merge)((0,S.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe((0,S.filterChanged)()).subscribe(m=>Jo(this.element,1))),this.representationSubscription.add((0,S.combine)({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe((0,S.filter)(({bufferLength:m,isActiveLowLatency:f})=>f&&!!m)).subscribe(({bufferLength:m})=>this.liveEstimatedDelay.next(m))),this.representationSubscription.add((0,S.combine)({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:m,isActiveLowLatency:f})=>{if(!f)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,y=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,I=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,P=m-g,k=1;Math.abs(P)>y&&(k=1+Math.sign(P)*I),Jo(this.element,k)})),this.representationSubscription.add(this.bufferLength$.subscribe(m=>{let f=0;if(m){let g=(this.element?.currentTime??0)*1e3;f=Math.min(...this.bufferManagers.map(I=>I.getLiveSegmentsToLoadState(this.manifest)?.to??g))-g}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add((0,S.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,S.throttle)(1e3)).subscribe(async({liveLoadBufferLength:m,bufferLength:f})=>{if((0,S.assertNonNullable)(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,y=vo(this.manifestUrlString,2),I=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,P=Math.min(I,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),k=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,C=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,x=isFinite(m)?m:f,N=this.isActiveLowLatency$.getValue(),Y=I<=this.tuning.live.activeLiveDelay&&y===0;this.isActiveLowLatency$.next(N&&Y);let J="none";if(N?J="active_low_latency":this.isLowLatency$.getValue()&&Y?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(z=>z.proceedLowLatencyLive()),J="active_low_latency"):y!==0&&x<P?J="live_forward_buffering":x<P+C&&(J="live_with_target_offset"),isFinite(m)&&(p=m>p?m:p),J==="live_forward_buffering"||J==="live_with_target_offset"){let z=p-(P+k),ee=this.normolizeLiveOffset(Math.trunc(y+z/g)),E=Math.abs(ee-y),w;!m||E<=this.tuning.dashCmafLive.offsetCalculationError?w=y:ee>0&&E>this.tuning.dashCmafLive.offsetCalculationError?w=ee:w=0,this.manifestUrlString=he(this.manifestUrlString,w,2)}J!=="none"&&J!=="active_low_latency"&&(p=0,this.updateLive())}))}let l=(0,S.merge)(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe((0,S.map)(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=(0,S.merge)(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe((0,S.map)(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add((0,S.merge)(this.forceEnded$,(0,S.combine)({allBuffersFull:l,someBufferEnded:c}).pipe((0,S.filter)(({allBuffersFull:p,someBufferEnded:m})=>p&&m))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(p=>!p.updating))try{this.source?.endOfStream()}catch(p){this.error$.next({id:"EndOfStream",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:p})}})),this.representationSubscription.add((0,S.merge)(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>this.source?.addEventListener("sourceopen",p)));let d=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{let m=[];return p.duration&&m.push(p.duration),Ve(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&m.push(p.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...d)/1e3,this.audioBufferManager&&(0,S.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,S.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:S.ErrorCategory.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new bs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveEstimatedDelay=ri.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator}),this.initTracerSubscription()}async seekLive(e){(0,S.assertNonNullable)(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=he(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){(0,S.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,S.merge)(...Nx.map(e=>(0,S.fromEvent)(this.element,e)),(0,S.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:S.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,S.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,S.fromEvent)(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&_t(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element)return;let t=this.currentStallDuration$.getValue();t+=50,this.currentStallDuration$.next(t);let i={timeInWaiting:t},a=(0,S.now)(),s=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardBufferDuration()??0,l=this.audioBufferManager?.getForwardBufferDuration()??0,c=u<s&&a-n>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&l<s&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||d)&&t>this.tuning.dash.crashOnStallTWithoutDataTimeout||t>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${t} ms`);if(this.isLive$.getValue()&&t%5e3===0)this.seekLive(this.liveLastSeekOffset),i.liveLastSeekOffset=this.liveLastSeekOffset;else{let p=this.element.currentTime*1e3;this.videoBufferManager?.maintain(p),this.audioBufferManager?.maintain(p),i.position=p}this.tracer.log("stallIntervalCallback",(0,S.flattenObject)(i))};this.videoBufferManager?.startAccumulateBuffer(),this.audioBufferManager?.startAccumulateBuffer(),this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=(0,S.interval)(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:S.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,i)}seek(e,t){(0,S.assertNonNullable)(this.element),(0,S.assertNonNullable)(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),_t(this.element.buffered,i)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.startAccumulateBuffer(),this.videoBufferManager.maintain(i),this.audioBufferManager?.startAccumulateBuffer(),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,S.flattenObject)({requestedPosition:e,forcePrecise:t,position:i}))}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>e.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,S.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let i=this.element.currentTime*1e3,a=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=i&&o.to+s>i&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?a.push(1/0):a.push(o.to));if(a.length){let n=Math.max(...a)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t={...t,gapEnds:a,jumpTo:n,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",(0,S.flattenObject)(t)))}}};var Is=class{constructor(e,t){this.fov=e,this.orientation=t}};var Es=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,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let a=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:a,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??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,i){this.setRotationSpeed(e,t,i),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,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);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*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Sf=`attribute vec2 a_vertex;
|
|
68
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var rf=r=>{if(!r.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(r),a=i?.[1]==="-"?-1:1,s={days:e(i?.[5],a),hours:e(i?.[6],a),minutes:e(i?.[7],a),seconds:e(i?.[8],a)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},Pt=(r,e)=>{let t=r;t=(0,Uo.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[a,s]of Object.entries(i)){let n=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=(0,Uo.default)(t,n,(o,u)=>(0,Bi.isNullable)(s)?o:(0,Bi.isNullable)(u)?s:s.padStart(parseInt(u,10),"0"))}return t},sf=(r,e)=>{let i=new DOMParser().parseFromString(r,"application/xml"),a={video:[],audio:[],text:[]},s=i.children[0],n=s.getElementsByTagName("Period")[0],o=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(x=>x.textContent?.trim()??""),u=(0,af.default)(o,0)??"",l=n.children,c=s.getAttribute("type")==="dynamic",d=s.getAttribute("availabilityStartTime"),h=d?new Date(d).getTime():void 0,m,f=s.getAttribute("mediaPresentationDuration"),g=n.getAttribute("duration"),I=s.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)m=rf(f);else if(g){let x=rf(g);(0,Bi.isNonNullable)(x)&&(m=x)}else I&&(m=parseInt(I,10));let P=0,k=s.getAttribute("profiles")?.split(",")??[];for(let x of l){let N=x.getAttribute("id")??"id"+(P++).toString(10),Y=x.getAttribute("mimeType")??"",X=x.getAttribute("codecs")??"",z=x.getAttribute("contentType")??Y?.split("/")[0],ee=x.getAttribute("profiles")?.split(",")??[],E=tf(x.getAttribute("lang")??"")??{},A=x.querySelector("Label")?.textContent?.trim()??void 0,Z=x.querySelectorAll("Representation"),Ae=x.querySelector("SegmentTemplate"),Ge=x.querySelector("Role")?.getAttribute("value")??void 0,R=z,j={id:N,language:E.language,isDefault:Ge==="main",label:A,codecs:X,hdr:R==="video"&&qo(X),mime:Y,representations:[]};for(let O of Z){let oe=O.getAttribute("lang")??void 0,de=O.getAttribute("label")??void 0,wt=O.querySelector("BaseURL")?.textContent?.trim()??"",ai=new URL(wt||u,e).toString(),qt=O.getAttribute("mimeType")??Y,W=O.getAttribute("codecs")??X??"",pe;if(z==="text"){let ne=O.getAttribute("id")||"",Se=E.privateuse?.includes("x-auto")||ne.includes("_auto"),we=O.querySelector("SegmentTemplate");if(we){let dt={representationId:O.getAttribute("id")??void 0,bandwidth:O.getAttribute("bandwidth")??void 0},et=parseInt(O.getAttribute("bandwidth")??"",10)/1e3,pt=parseInt(we.getAttribute("startNumber")??"",10)??1,tt=parseInt(we.getAttribute("timescale")??"",10),si=we.querySelectorAll("SegmentTimeline S")??[],ni=we.getAttribute("media");if(!ni)continue;let pa=[],ha=0,ma="",oi=0,Fi=pt,me=0;for(let Qe of si){let Ut=parseInt(Qe.getAttribute("d")??"",10),Ve=parseInt(Qe.getAttribute("r")??"",10)||0,Rt=parseInt(Qe.getAttribute("t")??"",10);me=Number.isFinite(Rt)?Rt:me;let Ht=Ut/tt*1e3,ui=me/tt*1e3;for(let it=0;it<Ve+1;it++){let $t=Pt(ni,{...dt,segmentNumber:Fi.toString(10),segmentTime:(me+it*Ut).toString(10)}),li=(ui??0)+it*Ht,Ui=li+Ht;Fi++,pa.push({time:{from:li,to:Ui},url:$t})}me+=(Ve+1)*Ut,ha+=(Ve+1)*Ht}oi=me/tt*1e3,ma=Pt(ni,{...dt,segmentNumber:Fi.toString(10),segmentTime:me.toString(10)});let qi={time:{from:oi,to:1/0},url:ma},ht={type:"template",baseUrl:ai,segmentTemplateUrl:ni,initUrl:"",totalSegmentsDurationMs:ha,segments:pa,nextSegmentBeyondManifest:qi,timescale:tt};pe={id:ne,kind:"text",segmentReference:ht,profiles:[],duration:m,bitrate:et,mime:"",codecs:"",width:0,height:0,isAuto:Se}}else pe={id:ne,isAuto:Se,kind:"text",url:ai}}else{let ne=O.getAttribute("contentType")??qt?.split("/")[0]??z,Se=x.getAttribute("profiles")?.split(",")??[],we=parseInt(O.getAttribute("width")??"",10),dt=parseInt(O.getAttribute("height")??"",10),et=parseInt(O.getAttribute("bandwidth")??"",10)/1e3,pt=O.getAttribute("frameRate")??"",tt=O.getAttribute("quality")??void 0,si=pt?ef(pt):void 0,ni=O.getAttribute("id")??"id"+(P++).toString(10),pa=ne==="video"?`${dt}p`:ne==="audio"?`${et}Kbps`:W,ha=`${ni}@${pa}`,ma=[...k,...ee,...Se],oi,Fi=O.querySelector("SegmentBase"),me=O.querySelector("SegmentTemplate")??Ae;if(Fi){let ht=O.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Qe,Ut]=ht.split("-").map($t=>parseInt($t,10)),Ve={from:Qe,to:Ut},Rt=O.querySelector("SegmentBase")?.getAttribute("indexRange"),[Ht,ui]=Rt?Rt.split("-").map($t=>parseInt($t,10)):[],it=Rt?{from:Ht,to:ui}:void 0;oi={type:"byteRange",url:ai,initRange:Ve,indexRange:it}}else if(me){let ht={representationId:O.getAttribute("id")??void 0,bandwidth:O.getAttribute("bandwidth")??void 0},Qe=parseInt(me.getAttribute("timescale")??"",10),Ut=me.getAttribute("initialization")??"",Ve=me.getAttribute("media"),Rt=parseInt(me.getAttribute("startNumber")??"",10)??1,Ht=Pt(Ut,ht);if(!Ve)throw new ReferenceError("No media attribute in SegmentTemplate");let ui=me.querySelectorAll("SegmentTimeline S")??[],it=[],$t=0,li="",Ui=0;if(ui.length){let fa=Rt,We=0;for(let ci of ui){let rt=parseInt(ci.getAttribute("d")??"",10),jt=parseInt(ci.getAttribute("r")??"",10)||0,ba=parseInt(ci.getAttribute("t")??"",10);We=Number.isFinite(ba)?ba:We;let ws=rt/Qe*1e3,Ff=We/Qe*1e3;for(let ga=0;ga<jt+1;ga++){let qf=Pt(Ve,{...ht,segmentNumber:fa.toString(10),segmentTime:(We+ga*rt).toString(10)}),au=(Ff??0)+ga*ws,Uf=au+ws;fa++,it.push({time:{from:au,to:Uf},url:qf})}We+=(jt+1)*rt,$t+=(jt+1)*ws}Ui=We/Qe*1e3,li=Pt(Ve,{...ht,segmentNumber:fa.toString(10),segmentTime:We.toString(10)})}else if((0,Bi.isNonNullable)(m)){let We=parseInt(me.getAttribute("duration")??"",10)/Qe*1e3,ci=Math.ceil(m/We),rt=0;for(let jt=1;jt<ci;jt++){let ba=Pt(Ve,{...ht,segmentNumber:jt.toString(10),segmentTime:rt.toString(10)});it.push({time:{from:rt,to:rt+We},url:ba}),rt+=We}Ui=rt,li=Pt(Ve,{...ht,segmentNumber:ci.toString(10),segmentTime:rt.toString(10)})}let Nf={time:{from:Ui,to:1/0},url:li};oi={type:"template",baseUrl:ai,segmentTemplateUrl:Ve,initUrl:Ht,totalSegmentsDurationMs:$t,segments:it,nextSegmentBeyondManifest:Nf,timescale:Qe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ne||!qt)continue;let qi={video:"video",audio:"audio",text:"text"}[ne];if(!qi)continue;R||=qi,pe={id:ha,kind:qi,segmentReference:oi,profiles:ma,duration:m,bitrate:et,mime:qt,codecs:W,width:we,height:dt,fps:si,quality:tt}}j.language||=oe,j.label||=de,j.mime||=qt,j.codecs||=W,j.hdr||=R==="video"&&qo(W),j.representations.push(pe)}R&&a[R].push(j)}return{dynamic:c,liveAvailabilityStartTime:h,duration:m,streams:a,baseUrls:o}};var Go=Be(wi(),1);var nf=require("@vkontakte/videoplayer-shared"),of=({id:r,width:e,height:t,bitrate:i,fps:a,quality:s,streamId:n})=>{let o=(s?Dt(s):void 0)??(0,nf.videoSizeToQuality)({width:e,height:t});return o&&{id:r,quality:o,bitrate:i,size:{width:e,height:t},fps:a,streamId:n}},uf=({id:r,bitrate:e})=>({id:r,bitrate:e}),lf=({language:r,label:e},{id:t,url:i,isAuto:a})=>({id:t,url:i,isAuto:a,type:"internal",language:r,label:e}),cf=({language:r,label:e,id:t,url:i,isAuto:a})=>({id:t,url:i,isAuto:a,type:"internal",language:r,label:e}),Qo=({id:r,language:e,label:t,codecs:i,isDefault:a})=>({id:r,language:e,label:t,codec:(0,Go.default)(i.split("."),0),isDefault:a}),Wo=({id:r,language:e,label:t,hdr:i,codecs:a})=>({id:r,language:e,hdr:i,label:t,codec:(0,Go.default)(a.split("."),0)}),Yo=r=>"url"in r,De=r=>r.type==="template",Wr=r=>r instanceof DOMException&&(r.name==="AbortError"||r.code===20);var Yr=class{constructor(e,t,i,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentSegmentLength$=new T.ValueSubject(0);this.onLastSegment$=new T.ValueSubject(!1);this.fullyBuffered$=new T.ValueSubject(!1);this.playingRepresentation$=new T.ValueSubject(void 0);this.playingRepresentationInit$=new T.ValueSubject(void 0);this.error$=new T.Subject;this.gaps=[];this.subscription=new T.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Ce;this.switchAbortController=new Ce;this.destroyAbortController=new Ce;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,T.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,T.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.resetAccumulateBufferAfterStall(),this.startAccumulateBuffer(),this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Em(this.sourceBuffer),this.subscription.add((0,T.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:T.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add((0,T.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:T.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,Do(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=ut(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),a=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,T.assertNonNullable)(i,"No init buffer for starting representation"),(0,T.assertNonNullable)(a,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(a,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchToOld=(0,T.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,T.assertNonNullable)(i,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if((0,T.isNullable)(s)||(0,T.isNullable)(a)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),(0,T.assertNonNullable)(a,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,T.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=(0,T.abortable)(this.destroyAbortController.signal,async function*(e){let t=e?.flatMap(u=>u.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let u of this.representations.keys()){let l=t.find(h=>h.id===u);l&&this.representations.set(u,l);let c=this.representations.get(u);if(!c||!De(c.segmentReference))return;let d=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,d)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,a=this.representations.get(i);(0,T.assertNonNullable)(a);let s=this.segments.get(i);(0,T.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(i);if((0,T.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,a),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=a,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!l?.dynamic,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Ce,(0,T.abortable)(this.switchAbortController.signal,async function*(i,a=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);(0,T.assertNonNullable)(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if((0,T.isNullable)(o)||(0,T.isNullable)(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),(0,T.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer)){if(this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),a)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();(0,T.isNonNullable)(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Ce,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,T.isNullable)(e)||(0,T.isNullable)(this.downloadingRepresentationId)||(0,T.isNullable)(this.playingRepresentationId)||(0,T.isNullable)(this.sourceBuffer)||(0,T.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if((0,T.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let a=i.find(l=>e>=l.time.from&&e<l.time.to);this.currentSegmentLength$.next((a?.time.to??0)-(a?.time.from??0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=ut(this.sourceBuffer.buffered,e),d=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=a.time.to-e+100&&(s=d)}if(isFinite(this.bufferLimit)&&Do(this.sourceBuffer.buffered)>=this.bufferLimit){let l=ut(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<c);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,s),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(o.includes(a))l="high";else{let c=(0,Oi.default)(o,0);c&&c.time.from-a.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l)}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!o.length&&ut(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Oi.default)(i,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,a=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+a}),i=s.time.to;(0,T.isNonNullable)(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=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<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[a[0]]:a}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind].flatMap(a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=e?.streams[this.kind].flatMap(i=>i.representations)??[];for(let i of t){if(!i||!De(i.segmentReference))return;let a=i.segmentReference.segments.map(u=>({...u,status:"none",size:void 0})),s=this.segments.get(i.id)??[],n=(0,Oi.default)(s,-1)?.time.to??0,o=a?.findIndex(u=>Math.floor(n)>=Math.floor(u.time.from)&&Math.floor(n)<=Math.floor(u.time.to));if(o===-1){this.liveUpdateSegmentIndex=0;let u=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,u)}else{let u=a.slice(o+1);this.segments.set(i.id,[...s,...u])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,T.assertNonNullable)(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}startAccumulateBuffer(){this.bufferAccumulation.enabled=!0}resetAccumulateBufferAfterStall(){(0,T.assertNonNullable)(this.playingRepresentationId);let e=this.representations.get(this.playingRepresentationId)?.duration;(0,T.assertNonNullable)(e);let{shortVideoDuration:t,shortVideoBufferStallSize:i,longVideoBufferStallSize:a}=this.tuning.dash.accumulationBufferStallSize;this.bufferAccumulation={enabled:!1,targetBufferSizeMs:e<=t?i:a,accumulatedBufferSizeMs:0,accumulated:[]}}updateLowLatencyLiveIfNeeded(e){for(let t of this.representations.values()){let i=t.segmentReference;if(!De(i))return;let a=this.segments.get(t.id)??[],s=a.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(s&&!isFinite(s.time.to)&&(s.time.to=e.time.to),!!!a.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*i.timescale/1e3).toString(10),u=Pt(i.segmentTemplateUrl,{segmentTime:o});a.push({status:"none",time:{from:e.time.to,to:1/0},url:u})}}}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.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.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(a=>t>=a.time.from&&t<a.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let a=e.findIndex(({status:d,time:{from:h,to:m}},f)=>{let g=h<=i&&m>=i,y=h>i||g||f===0&&i===0,I=Math.min(this.forwardBufferTarget,this.bufferLimit),P=this.preloadOnly&&h<=i+I||m<=i+I;return(d==="none"||d==="partially_ejected"&&y&&P&&this.sourceBuffer&&!(Ot(this.sourceBuffer.buffered,h)&&Ot(this.sourceBuffer.buffered,m)))&&y&&P});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<s.length&&(n<=l||o<=c);d++){let h=s[d];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}async loadSegments(e,t,i="auto"){De(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="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:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await(0,T.abortable)(o,async function*(){let c=(0,T.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:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=(0,T.now)(),!c)return;let d=new DataView(c);if(!isFinite(a.segment.time.to)){let h=t.segmentReference.timescale,m=Qr(t.mime);a.segment.time.to=m.getChunkEndTime(d,h)}u&&a.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Wr(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())De(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,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,T.abortable)(n,async function*(){let u=(0,T.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,T.fromEvent)(window,"online").pipe((0,T.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:a,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=(0,T.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Wr(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(De(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,a={from:(0,Oi.default)(e,0).byte.from,to:(0,Oi.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:a,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,T.now)(),this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:a?a.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!De(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let a=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,T.now)();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:a,signal:s,onProgress:u,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:i,onSegmentAppendFailed:a,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){a();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=Qr(n.mime).parseFeedableSegmentChunk(l,this.isLive);c?.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:a,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){n();continue}let c=l.byte.from-i,d=l.byte.to-i,h=d-c+1,m=c<a,f=d<=a;if(!m)continue;let g=Qr(o.mime),y=this.tuning.dash.enableSubSegmentBufferFeeding&&(Lm(g)||this.bufferAccumulation.targetBufferSizeMs===0);if(l.status==="downloading"&&f){l.status="downloaded";let I=new DataView(e.buffer,e.byteOffset+c,h),P=this.getCurrentPosition();(0,T.isNonNullable)(P)&&(this.bufferAccumulation.accumulatedBufferSizeMs=l.time.to-P,this.bufferAccumulation.accumulated.push({dataView:I,segmentProgress:u}),this.activeSegments.delete(u));let k=async({dataView:D,segmentProgress:x})=>{await this.sourceBufferTaskQueue.append(D,s)&&!s.aborted?this.onSegmentFullyAppended(x,t):n()};this.bufferAccumulation.enabled&&this.bufferAccumulation.accumulatedBufferSizeMs>this.bufferAccumulation.targetBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(k),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||(0,T.isNullable)(P))&&(k({dataView:I,segmentProgress:u}),this.resetAccumulateBufferAfterStall())}else if(y&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(h,a-c),u.loadedBytes>u.feedingBytes)){let I=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),P=u.loadedBytes===h?I:g.parseFeedableSegmentChunk(I);P?.byteLength&&(l.status="partially_fed",u.feedingBytes+=P.byteLength,await this.sourceBufferTaskQueue.append(P,s)&&!s.aborted?(u.fedBytes+=P.byteLength,u.fedBytes===h&&this.onSegmentFullyAppended(u,t)):n())}}}onSegmentFullyAppended(e,t){this.tuning.useSafariEndlessRequestBugfix&&!this.isLive&&((0,T.assertNonNullable)(this.sourceBuffer),Ot(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ot(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"SafariEmptyAppendBuffer",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Safari stuck on empty result of adding segment to source buffer"})),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 i of this.representations.values())if(i.id!==t)for(let a of this.segments.get(i.id)??[])a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none");(0,T.assertNonNullable)(this.sourceBuffer),this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);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 i=this.representations.get(e);i&&(this.initLoadIdleCallback=Mo(()=>(0,df.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let a=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?(0,T.abortable)(this.destroyAbortController.signal,async function*(){let o=(0,T.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Qr(e.mime),a)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let h=c;this.isLive&&De(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:T.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||(0,T.isNullable)(e)||this.sourceBuffer.updating)return!1;let a=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:h}=u[c],m=l[l.length-1];m.to>=d?m.to=Math.max(m.to,h):l.push(u[c])}return l},o=u=>{if(s>=t)return a;a.push({...u.time}),a=n(a);let l=Yo(u)?u.size??0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let h of this.segments.values())for(let m of h)["none","partially_ejected"].includes(m.status)&&Math.round(m.time.from)<=Math.round(l)&&Math.round(m.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let h={time:{from:l,to:c},url:"",status:"none"};o(h)}}if(a.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return a.length?(await Promise.all(a.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!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)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!this.sourceBuffer.buffered.length||(0,T.isNullable)(e)?0:ut(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(this.sourceBuffer)for(let i of t){let a={representation:e,from:i.time.from,to:i.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<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){a=void 0;break}o>i.time.from&&o<i.time.to&&(a.from=o),n<i.time.to&&n>i.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){if(!this.gapDetectionIdleCallback){(0,T.assertNonNullable)(this.sourceBuffer);for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(a=>this.sourceBuffer&&(Math.round(a.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(a.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Mo(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:T.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,T.isNullable)(this.sourceBuffer)||(0,T.isNullable)(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let a=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:a,to:s})}let t=100;for(let i of this.segments.values())for(let a of i){let{status:s}=a;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(a.time.from),o=Math.ceil(a.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.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 zr=r=>{let e=new URL(r);return e.searchParams.set("quic","1"),e.toString()};var pf=r=>{let e=r.get("X-Delivery-Type"),t=r.get("X-Reused"),i=e===null?"http1":e??void 0,a=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:a}};var G=require("@vkontakte/videoplayer-shared");var hf=r=>{let e=new URL(r);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var fs=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:a=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new G.ValueSubject(void 0);this.lastConnectionReused$=new G.ValueSubject(void 0);this.lastRequestFirstBytes$=new G.ValueSubject(void 0);this.abortAllController=new Ce;this.subscription=new G.Subscription;this.fetchManifest=(0,G.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=zr(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=hf(i));let a=yield It(i,{signal:this.abortAllController.signal}).catch(Kr);return a?(t.log("success",(0,G.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(a.headers),a.text()):(t.error("error",(0,G.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,G.abortable)(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:a,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){let l=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let E=new URL(l,location.href);E.searchParams.append("bytes",`${i.from}-${i.to}`),l=E.toString();break}default:(0,G.assertNever)(t)}this.requestQuic&&(l=zr(l));let h=this.abortAllController.signal,m;if(n){let E=new Ce;if(m=(0,G.merge)((0,G.fromEvent)(this.abortAllController.signal,"abort"),(0,G.fromEvent)(n,"abort")).subscribe(()=>{try{E.abort()}catch(A){Kr(A)}}),this.abortAllController.signal.aborted||n.aborted)try{E.abort()}catch(A){Kr(A)}h=E.signal}let f=(0,G.now)();d.log("startRequest",(0,G.flattenObject)({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:f}));let g=yield It(l,{priority:s,headers:c,signal:h}).catch(Kr),y=(0,G.now)();if(!g)return d.error("error",{message:"No response in request"}),d.end(),m?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(y-f),!g.ok||!g.body){m?.unsubscribe();let E=`Fetch error ${g.status}: ${g.statusText}`;return d.error("error",{message:E}),d.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!a&&!o){m?.unsubscribe();let E=(0,G.now)(),A={requestStartedAt:f,requestEndedAt:E,duration:E-f};return d.log("endRequest",(0,G.flattenObject)(A)),d.end(),g.arrayBuffer()}let[I,P]=g.body.tee(),k=I.getReader();o&&this.throughputEstimator?.trackStream(P,u);let D=0,x=new Uint8Array(0),N=!1,Y=E=>{m?.unsubscribe(),N=!0,Kr(E)},X=(0,G.abortable)(h,async function*({done:E,value:A}){if(D===0&&this.lastRequestFirstBytes$.next((0,G.now)()-f),h.aborted){m?.unsubscribe();return}if(!E&&A){let Z=new Uint8Array(x.length+A.length);Z.set(x),Z.set(A,x.length),x=Z,D+=A.byteLength,a?.(new DataView(x.buffer),D),yield k?.read().then(X,Y)}}.bind(this));yield k?.read().then(X,Y),m?.unsubscribe();let z=(0,G.now)(),ee={failed:N,requestStartedAt:f,requestEndedAt:z,duration:z-f};return N?(d.error("endRequest",(0,G.flattenObject)(ee)),d.end(),null):(d.log("endRequest",(0,G.flattenObject)(ee)),d.end(),x.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,G.abortable)(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:a,to:s}=e.initRange,n=a,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,a),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let h=new DataView(d,a-n,s-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let m=t.parseInit(h),f=e.indexRange??t.getIndexRange(m);if(!f)throw new ReferenceError("No way to load representation index");let g;if(u)g=new DataView(d,f.from-n,f.to-f.from+1);else{let I=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!I)return null;g=new DataView(I)}let y=t.parseSegments(g,m,f);return{init:m,dataView:new DataView(d),segments:y}}.bind(this));this.fetchTemplateRepresentation=(0,G.abortable)(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),a=yield this.fetch(i,{priority:t,measureThroughput:!1});return a?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(a)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=a,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=pf(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:a}=e;switch(a){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:(0,G.assertNever)(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Kr=r=>{if(!Wr(r))throw r};var ti=(r,e,t)=>t*e+(1-t)*r,zo=(r,e)=>r.reduce((t,i)=>t+i,0)/e,mf=(r,e,t,i)=>{let a=0,s=t,n=zo(r,e),o=e<i?e:i;for(let u=0;u<o;u++)r[s]>n?a++:a--,s=(r.length+s-1)%r.length;return Math.abs(a)===o};var Jr=require("@vkontakte/videoplayer-shared"),Nt=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 Jr.ValueSubject(e.initial),this.debounced$=new Jr.ValueSubject(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ge(`raw_${t}`),this.smoothedSeries$=new ge(`smoothed_${t}`),this.reportedSeries$=new ge(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;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,Jr.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 bs=class extends Nt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ti(this.slow,e,this.params.emaAlphaSlow),this.fast=ti(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var gs=class extends Nt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=zo(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ti(this.emaSmoothed,e,this.params.emaAlpha);let i=mf(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Ss=class extends Nt{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?ti(this.smoothed,t,this.params.emaAlpha):t}};var ii=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new bs({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new gs({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new Ss({initial:e,label:"liveEdgeDelay",...t})}};var Ko=(r,e)=>{r&&r.playbackRate!==e&&(r.playbackRate=e)};var vs=require("@vkontakte/videoplayer-shared");var Xr=class r{constructor(e,t){this.currentRepresentation$=new vs.ValueSubject(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!(0,vs.isNullable)(e))for(let t of this.representations)for(let i of t){let a=i.segmentReference,s=a.segments.length,n=a.segments[0].time.from,o=a.segments[s-1].time.to;if(e<n||e>o)continue;let u=a.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,a.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=r.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>r.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&De(t.segmentReference))}};var Ox=["timeupdate","progress","play","seeked","stalled","waiting"],_x=["timeupdate","progress","loadeddata","playing","seeked"];var ys=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new S.Subscription;this.representationSubscription=new S.Subscription;this.state$=new q("none");this.currentVideoRepresentation$=new S.ValueSubject(void 0);this.currentVideoRepresentationInit$=new S.ValueSubject(void 0);this.currentAudioRepresentation$=new S.ValueSubject(void 0);this.currentVideoSegmentLength$=new S.ValueSubject(0);this.currentAudioSegmentLength$=new S.ValueSubject(0);this.error$=new S.Subject;this.lastConnectionType$=new S.ValueSubject(void 0);this.lastConnectionReused$=new S.ValueSubject(void 0);this.lastRequestFirstBytes$=new S.ValueSubject(void 0);this.currentLiveTextRepresentation$=new S.ValueSubject(null);this.isLive$=new S.ValueSubject(!1);this.liveDuration$=new S.ValueSubject(0);this.liveAvailabilityStartTime$=new S.ValueSubject(void 0);this.bufferLength$=new S.ValueSubject(0);this.liveLoadBufferLength$=new S.ValueSubject(0);this.livePositionFromPlayer$=new S.ValueSubject(0);this.isLowLatency$=new S.ValueSubject(!1);this.isActiveLowLatency$=new S.ValueSubject(!1);this.currentStallDuration$=new S.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new S.ValueSubject(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new S.Subject;this.gapWatchdogActive=!1;this.destroyController=new Ce;this.initManifest=(0,S.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=he(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:S.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,S.abortable)(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:S.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=sf(e??"",this.manifestUrlString)}catch(n){let o=vm(e)??{id:"ManifestParsing",category:S.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(o)}if(!t)return null;let i=(n,o,u)=>!!(this.element?.canPlayType?.(o)&&Et()?.isTypeSupported?.(`${o}; codecs="${u}"`)||n==="text");t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let a={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let u=t.streams[n].filter(({mime:d,codecs:h})=>i(n,d,h)),l=new Set(u.map(({codecs:d})=>d)),c=Sm(l);if(c&&(a[n]=u.filter(({codecs:d})=>d.startsWith(c))),n==="video"){let d=this.tuning.preferHDR,h=a.video.some(f=>f.hdr),m=a.video.some(f=>!f.hdr);S.clientChecker.isHDR&&d&&h?a.video=a.video.filter(f=>f.hdr):m&&(a.video=a.video.filter(f=>!f.hdr))}}let s={...t,streams:a};return this.tracer.log("updateManifestEnd",(0,S.flattenObject)(s)),s}.bind(this));this.initRepresentations=(0,S.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",(0,S.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,S.assertNonNullable)(this.manifest),(0,S.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=h=>{this.representationSubscription.add((0,S.fromEvent)(h,"error").pipe((0,S.filter)(m=>!!this.element?.played.length)).subscribe(m=>{this.error$.next({id:"VideoSource",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:m})}))};this.source=this.tuning.useManagedMediaSource?dm():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&ds())if(i){let h=document.createElement("source");a(h),h.type="application/x-mpegurl",h.src=i.url,this.element.appendChild(h)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.isLowLatency$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((h,m)=>[...h,...m.representations],[]);if(this.videoBufferManager=new Yr("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,S.isNonNullable)(t)){let h=this.manifest.streams.audio.reduce((m,f)=>[...m,...f.representations],[]);this.audioBufferManager=new Yr("audio",this.source,h,n),this.bufferManagers.push(this.audioBufferManager)}Xr.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Xr(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,S.interval)(1e3).subscribe(h=>{if(this.element?.paused){let m=go(this.manifestUrlString,2);this.manifestUrlString=he(this.manifestUrlString,m+1e3,2)}}));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,S.merge)(..._x.map(h=>(0,S.fromEvent)(this.element,h))).pipe((0,S.map)(h=>this.element?ut(this.element.buffered,this.element.currentTime*1e3):0),(0,S.filterChanged)(),(0,S.tap)(h=>{h>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,S.merge)((0,S.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe((0,S.filterChanged)()).subscribe(m=>Ko(this.element,1))),this.representationSubscription.add((0,S.combine)({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe((0,S.filter)(({bufferLength:m,isActiveLowLatency:f})=>f&&!!m)).subscribe(({bufferLength:m})=>this.liveEstimatedDelay.next(m))),this.representationSubscription.add((0,S.combine)({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:m,isActiveLowLatency:f})=>{if(!f)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,y=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,I=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,P=m-g,k=1;Math.abs(P)>y&&(k=1+Math.sign(P)*I),Ko(this.element,k)})),this.representationSubscription.add(this.bufferLength$.subscribe(m=>{let f=0;if(m){let g=(this.element?.currentTime??0)*1e3;f=Math.min(...this.bufferManagers.map(I=>I.getLiveSegmentsToLoadState(this.manifest)?.to??g))-g}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let h=0;this.representationSubscription.add((0,S.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,S.throttle)(1e3)).subscribe(async({liveLoadBufferLength:m,bufferLength:f})=>{if((0,S.assertNonNullable)(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,y=go(this.manifestUrlString,2),I=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,P=Math.min(I,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),k=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,D=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,x=isFinite(m)?m:f,N=this.isActiveLowLatency$.getValue(),Y=I<=this.tuning.live.activeLiveDelay&&y===0;this.isActiveLowLatency$.next(N&&Y);let X="none";if(N?X="active_low_latency":this.isLowLatency$.getValue()&&Y?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(z=>z.proceedLowLatencyLive()),X="active_low_latency"):y!==0&&x<P?X="live_forward_buffering":x<P+D&&(X="live_with_target_offset"),isFinite(m)&&(h=m>h?m:h),X==="live_forward_buffering"||X==="live_with_target_offset"){let z=h-(P+k),ee=this.normolizeLiveOffset(Math.trunc(y+z/g)),E=Math.abs(ee-y),A;!m||E<=this.tuning.dashCmafLive.offsetCalculationError?A=y:ee>0&&E>this.tuning.dashCmafLive.offsetCalculationError?A=ee:A=0,this.manifestUrlString=he(this.manifestUrlString,A,2)}X!=="none"&&X!=="active_low_latency"&&(h=0,this.updateLive())}))}let l=(0,S.merge)(...this.bufferManagers.map(h=>h.fullyBuffered$)).pipe((0,S.map)(()=>this.bufferManagers.every(h=>h.fullyBuffered$.getValue()))),c=(0,S.merge)(...this.bufferManagers.map(h=>h.onLastSegment$)).pipe((0,S.map)(()=>this.bufferManagers.some(h=>h.onLastSegment$.getValue())));this.representationSubscription.add((0,S.merge)(this.forceEnded$,(0,S.combine)({allBuffersFull:l,someBufferEnded:c}).pipe((0,S.filter)(({allBuffersFull:h,someBufferEnded:m})=>h&&m))).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:S.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add((0,S.merge)(...this.bufferManagers.map(h=>h.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(h=>this.source?.addEventListener("sourceopen",h)));let d=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(h=>h.representations).flatMap(h=>{let m=[];return h.duration&&m.push(h.duration),De(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...d)/1e3,this.audioBufferManager&&(0,S.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,S.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:S.ErrorCategory.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new fs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveEstimatedDelay=ii.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator}),this.initTracerSubscription()}async seekLive(e){(0,S.assertNonNullable)(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=he(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){(0,S.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,S.merge)(...Ox.map(e=>(0,S.fromEvent)(this.element,e)),(0,S.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:S.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,S.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,S.fromEvent)(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Ot(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element)return;let t=this.currentStallDuration$.getValue();t+=50,this.currentStallDuration$.next(t);let i={timeInWaiting:t},a=(0,S.now)(),s=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardBufferDuration()??0,l=this.audioBufferManager?.getForwardBufferDuration()??0,c=u<s&&a-n>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&l<s&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||d)&&t>this.tuning.dash.crashOnStallTWithoutDataTimeout||t>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${t} ms`);if(this.isLive$.getValue()&&t%5e3===0)this.seekLive(this.liveLastSeekOffset),i.liveLastSeekOffset=this.liveLastSeekOffset;else{let h=this.element.currentTime*1e3;this.videoBufferManager?.maintain(h),this.audioBufferManager?.maintain(h),i.position=h}this.tracer.log("stallIntervalCallback",(0,S.flattenObject)(i))};this.videoBufferManager?.startAccumulateBuffer(),this.audioBufferManager?.startAccumulateBuffer(),this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=(0,S.interval)(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:S.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,i)}seek(e,t){(0,S.assertNonNullable)(this.element),(0,S.assertNonNullable)(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),Ot(this.element.buffered,i)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.startAccumulateBuffer(),this.videoBufferManager.maintain(i),this.audioBufferManager?.startAccumulateBuffer(),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,S.flattenObject)({requestedPosition:e,forcePrecise:t,position:i}))}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>e.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,S.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let i=this.element.currentTime*1e3,a=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=i&&o.to+s>i&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?a.push(1/0):a.push(o.to));if(a.length){let n=Math.max(...a)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t={...t,gapEnds:a,jumpTo:n,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",(0,S.flattenObject)(t)))}}};var Ts=class{constructor(e,t){this.fov=e,this.orientation=t}};var Is=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,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let a=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:a,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??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,i){this.setRotationSpeed(e,t,i),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,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);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*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var bf=`attribute vec2 a_vertex;
|
|
69
69
|
attribute vec2 a_texel;
|
|
70
70
|
|
|
71
71
|
varying vec2 v_texel;
|
|
@@ -76,7 +76,7 @@ void main(void) {
|
|
|
76
76
|
// save texel vector to pass to fragment shader
|
|
77
77
|
v_texel = a_texel;
|
|
78
78
|
}
|
|
79
|
-
`;var
|
|
79
|
+
`;var gf=`#ifdef GL_ES
|
|
80
80
|
precision highp float;
|
|
81
81
|
precision highp int;
|
|
82
82
|
#else
|
|
@@ -119,6 +119,5 @@ void main(void) {
|
|
|
119
119
|
// sample using new coordinates
|
|
120
120
|
gl_FragColor = texture2D(u_texture, tc);
|
|
121
121
|
}
|
|
122
|
-
`;var xs=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,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 Is(this.params.fov,this.params.orientation),this.cameraRotationManager=new Es(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"),i=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(i),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(i,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(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Sf,this.gl.VERTEX_SHADER),i=this.createShader(vf,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),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,i=1,a=this.frameHeight/(this.frameWidth/this.viewportWidth);return a>this.viewportHeight?t=this.viewportHeight/a:i=a/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),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,i=this.camera.fov.x/360/2,a=this.camera.fov.y/180/2,s=e-i,n=t-a,o=e+i,u=t-a,l=e+i,c=t+a,d=e-i,p=t+a;return[s,n,o,u,l,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var ce=require("@vkontakte/videoplayer-shared"),Zo=class{constructor(){this.isSeeked$=new ce.ValueSubject(!1);this.isBuffering$=new ce.ValueSubject(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new ce.Subscription}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add((0,ce.combine)({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe((0,ce.filter)(({isBuffering:t,isSeeked:i})=>t&&!i)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add((0,ce.combine)({currentStallDuration:this.currentStallDuration$,isSeeked:this.isSeeked$}).subscribe(({currentStallDuration:t,isSeeked:i})=>{if((0,ce.isNullable)(this.lastUniqueVideoTrackSelected))return;let{stallDurationBeforeQualityDecrease:a,stallDurationNoDataBeforeQualityDecrease:s,stallCountBeforeQualityDecrease:n,resetQualityRestrictionTimeout:o}=this.qualityLimitsOnStall,u=this.rtt$.getValue(),l=this.throughput$.getValue(),c=this.videoLastDataObtainedTimestamp$.getValue(),d=(0,ce.now)(),p=n&&this.currentStallsCount>=n,m=a&&!i&&d-this.lastUniqueVideoTrackSelectedTimestamp>=a+u&&t>=a,f=s&&d-this.lastUniqueVideoTrackSelectedTimestamp>=s+u&&d-c>=s+u&&t>=s;(p||m||f)&&(window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,(0,ce.isNonNullable)(this.lastUniqueVideoTrackSelected.bitrate)&&l>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},o))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=(0,ce.now)(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},yf=Zo;var ai=class{constructor(e){this.subscription=new B.Subscription;this.videoState=new q("stopped");this.elementSize$=new B.ValueSubject(void 0);this.textTracksManager=new Ue;this.droppedFramesManager=new us;this.stallsManager=new yf;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new gr;this.audioTrackSwitchHistory=new gr;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"){let n=this.liveOffset?.getTotalPausedTime()??0;this.seek(a.position-n,a.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&A(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset?.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):i?.to==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return(0,B.assertNever)(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new xs(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=Ie(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ue(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Ts({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=Pe(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:B.ErrorCategory.WTF,message:`${a} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,B.filter)(c=>!!c.length),(0,B.once)()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,B.map)(c=>c.to.state!=="none"),(0,B.filterChanged)());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe((0,B.filterChanged)()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:i.isBuffering$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe((0,B.filter)(B.isNonNullable),(0,B.once)()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe((0,B.map)(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(ut(this.video,t.isLooped,a)),this.subscription.add(xe(this.video,t.volume,i.volumeState$,a)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(qe(this.video,t.playbackRate,i.playbackRateState$,a)),s((0,B.observeElementSize)(this.video),this.elementSize$),s(He(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},a)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if((0,B.assertNonNullable)(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let f of d.audio){m.push(Yo(f));let g=[];for(let y of f.representations){let I=cf(y);g.push(I),this.audioTracksMap.set(I,{stream:f,representation:y})}this.audioStreamsMap.set(f,g)}this.params.output.availableAudioStreams$.next(m)}let p=[];for(let m of d.video){p.push(zo(m));let f=[];for(let g of m.representations){let y=lf(g);y&&(f.push(y),this.videoTracksMap.set(y,{stream:m,representation:g}))}this.videoStreamsMap.set(m,f)}if(this.params.output.availableVideoStreams$.next(p),this.textTracksManager)for(let m of d.text)for(let f of m.representations){let g=df(m,f);this.textTracksMap.set(g,{stream:m,representation:f})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a));let o=c=>e.error$.next({id:"RepresentationSwitch",category:B.ErrorCategory.WTF,message:"Switching representations threw",thrown:c});this.subscription.add((0,B.merge)(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,B.fromEvent)(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[m,f]=p,g=[...this.videoTracksMap.keys()].find(I=>this.videoTracksMap.get(I)?.representation.id===m.id);(0,B.isNonNullable)(g)&&(this.stallsManager.lastVideoTrackSelected=g);let y=this.params.desiredState.autoVideoTrackLimits.getTransition();if(y&&this.params.output.autoVideoTrackLimits$.next(y.to),c==="manifest_ready")this.player.initRepresentations(m.id,f?.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",m.id).catch(o),f){let I=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",f.id,I).catch(o)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSize$.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,B.filterChanged)()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:m}]=d,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(zo(m))},a)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,B.filterChanged)()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[p,{stream:m}]=d,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(Yo(m))},a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},a)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,a)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,a)),this.textTracksManager?.connect(this.video,t,e);let u=t.playbackState.stateChangeStarted$.pipe((0,B.map)(({to:c})=>c==="ready"),(0,B.filterChanged)());this.subscription.add((0,B.merge)(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add((0,B.merge)(u,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=(0,B.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,B.observableFrom)(["init"])).pipe((0,B.debounce)(0));this.subscription.add(l.subscribe(this.syncPlayback,a))}selectVideoAudioRepresentations(){let{desiredState:e,output:t}=this.params,i=e.autoVideoTrackSwitching.getState(),a=e.videoTrack.getState()?.id,n=[...this.videoTracksMap.keys()].find(({id:N})=>N===a),o=t.currentVideoTrack$.getValue(),u=e.videoStream.getState()??(n&&this.videoTracksMap.get(n)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:N})=>N===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=ct(this.video.buffered,this.video.currentTime*1e3),p=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,m=Math.min(d/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),f=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),g=[...this.audioStreamsMap.keys()].find(({id:N})=>N===f?.id)??this.audioStreamsMap.keys().next().value,y=0;if(g){if(n&&!i){let N=ns(n,c,this.audioStreamsMap.get(g)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,N?.bitrate??-1/0)}if(o){let N=ns(o,c,this.audioStreamsMap.get(g)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,N?.bitrate??-1/0)}}let I=Ot(c,{container:this.elementSize$.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:y,forwardBufferHealth:m,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),P=i?I??n:n??I,k=g&&sm(P,c,this.audioStreamsMap.get(g)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:m,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),C=this.videoTracksMap.get(P)?.representation,x=k&&this.audioTracksMap.get(k)?.representation;if(C&&x)return[C,x];if(C&&!x&&this.audioTracksMap.size===0)return[C,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:B.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.destroy3DScene(),this.textTracksManager?.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Ee(this.video),this.tracer.end()}};var ta=class extends ai{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var qt=require("@vkontakte/videoplayer-shared");var ia=class extends ai{constructor(e){super(e),this.liveOffset=new Tt,this.textTracksManager=null}subscribe(){super.subscribe();let{output:e,observableVideo:t,desiredState:i,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),a(t.timeUpdate$,e.liveBufferTime$),a(this.player.liveDuration$,e.duration$),this.subscription.add(i.isLowLatency.stateChangeEnded$.pipe((0,qt.map)(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add((0,qt.combine)({interval:(0,qt.interval)(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{if(this.videoState.getState()==="playing"){let n=e.position$.getValue()+(s-1);n<=0&&e.position$.next(n),this.liveOffset?.resetTo(-n*1e3)}})).add((0,qt.combine)({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,qt.map)(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=pf(s);this.params.output.availableTextTracks$.next([n])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),a=t==="paused"&&i==="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 Tf=Oe(rs(),1);var H=require("@vkontakte/videoplayer-shared"),tt={};var Ni=(r,e)=>new H.Observable(t=>{let i=(a,s)=>t.next(s);return r.on(e,i),()=>r.off(e,i)}),ra=class{constructor(e){this.subscription=new H.Subscription;this.videoState=new q("initializing");this.textTracksManager=new Ue;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(e!=="initializing")switch(i?.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,H.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,H.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,H.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,H.assertNever)(e)}break;default:(0,H.assertNever)(t)}};this.video=Ie(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ue(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),Ee(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:H.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Tf.default)(import("hls.js").then(a=>{e||(tt.Hls=a.default,tt.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){(0,H.assertNonNullable)(tt.Hls,"hls.js not loaded"),this.hls=new tt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,H.assertNonNullable)(tt.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:H.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:l})},a=Pe(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,i));s(a.timeUpdate$,t.position$),s(a.durationChange$,t.duration$),s(a.ended$,t.endedEvent$),s(a.looped$,t.loopedEvent$),s(a.error$,t.error$),s(a.isBuffering$,t.isBuffering$),s(a.currentBuffer$,t.currentBuffer$),s(a.loadStart$,t.firstBytesEvent$),s(a.loadedMetadata$,t.loadedMetadataEvent$),s(a.playing$,t.firstFrameEvent$),s(a.canplay$,t.canplay$),s(a.seeked$,t.seekedEvent$),s(a.inPiP$,t.inPiP$),s(a.inFullscreen$,t.inFullscreen$),this.subscription.add(ut(this.video,e.isLooped,i)),this.subscription.add(xe(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(qe(this.video,e.playbackRate,a.playbackRateState$,i)),s(He(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe((0,H.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Ni(this.hls,tt.Events.ERROR).subscribe(l=>{l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:H.ErrorCategory.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${l.err?.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),A(e.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),A(e.playbackState,"paused")},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),s(Ni(this.hls,tt.Events.MANIFEST_PARSED).pipe((0,H.map)(({levels:l})=>l.reduce((c,d)=>{let p=d.name||d.height.toString(10),{width:m,height:f}=d,g=Vt(d.attrs.QUALITY??"")??(0,H.videoSizeToQuality)({width:m,height:f});if(!g)return c;let y=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,I={id:p.toString(),quality:g,bitrate:d.bitrate/1e3,size:{width:m,height:f},fps:y};return this.trackLevels.set(p,{track:I,level:d}),c.push(I),c},[]))),t.availableVideoTracks$),s(Ni(this.hls,tt.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,m=d.attrs.URI||"",f=d.lang;c.push({id:p,url:m,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(Ni(this.hls,tt.Events.LEVEL_LOADING).pipe((0,H.map)(({url:l})=>ue(l))),t.hostname$),s(Ni(this.hls,tt.Events.FRAG_CHANGED),l=>{let{video:c,audio:d}=l.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(Ct(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:i}));let n=l=>Array.from(this.trackLevels.values()).find(({level:c})=>c===l)?.track,o=Ni(this.hls,tt.Events.LEVEL_SWITCHED).pipe((0,H.map)(({level:l})=>n(this.hls.levels[l])));o.pipe((0,H.filter)(H.isNonNullable)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Ct(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{if((0,H.isNullable)(l))return;let c=this.trackLevels.get(l.id)?.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,m=this.hls.levels[p];!m||c.bitrate>m.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:i})),s(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=(0,H.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,H.observableFrom)(["init"])).pipe((0,H.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:H.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),A(this.params.desiredState.playbackState,"stopped",!0)}};var If="X-Playback-Duration",eu=async r=>{let e=await Ze(r),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(If)?parseInt(e.headers.get(If),10):void 0};var U=require("@vkontakte/videoplayer-shared");var iu=Oe(Mn(),1);var Ps=require("@vkontakte/videoplayer-shared");var Gx=r=>{let e=null;if(r.QUALITY&&(e=Vt(r.QUALITY)),!e&&r.RESOLUTION){let[t,i]=r.RESOLUTION.split("x").map(a=>parseInt(a,10));e=(0,Ps.videoSizeToQuality)({width:t,height:i})}return e??null},Qx=(r,e)=>{let t=r.split(`
|
|
123
|
-
`),i=[],a=[];for(let s=0;s<t.length;s++){let n=t[s],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),u=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!u)){if(o){let l=(0,iu.default)(o[1].split(",").map(y=>y.split("="))),c=l.QUALITY??`stream-${l.BANDWIDTH}`,d=Gx(l),p;l.BANDWIDTH&&(p=parseInt(l.BANDWIDTH,10)/1e3||void 0),!p&&l["AVERAGE-BANDWIDTH"]&&(p=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let m=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,f;if(l.RESOLUTION){let[y,I]=l.RESOLUTION.split("x").map(P=>parseInt(P,10));y&&I&&(f={width:y,height:I})}let g=new URL(t[++s],e).toString();d&&i.push({id:c,quality:d,url:g,bandwidth:p,size:f,fps:m})}if(u){let l=(0,iu.default)(u[1].split(",").map(m=>{let f=m.indexOf("=");return[m.substring(0,f),m.substring(f+1)]}).map(([m,f])=>[m,f.replace(/^"|"$/g,"")])),c=l.URI?.replace(/playlist$/,"subtitles.vtt"),d=l.LANGUAGE,p=l.NAME;c&&d&&a.push({type:"internal",id:d,label:p,language:d,url:c,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:a}},Wx=r=>new Promise(e=>{setTimeout(()=>{e()},r)}),tu=0,Ef=async(r,e=r,t,i)=>{let s=await(await Ze(r,i)).text();tu+=1;try{let{qualityManifests:n,textTracks:o}=Qx(s,e);return{qualityManifests:n,textTracks:o}}catch{if(tu<=t.manifestRetryMaxCount)return await Wx((0,Ps.getExponentialDelay)(tu-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Ef(r,e,t)}return{qualityManifests:[],textTracks:[]}},ks=Ef;var ve=require("@vkontakte/videoplayer-shared");var ws=class{constructor(e,t,i,a){this.subscription=new ve.Subscription;this.abortControllers={destroy:new me,nextManifest:null};this.numberFormat=new Intl.NumberFormat("ru-RU",{maximumFractionDigits:2,minimumFractionDigits:2,useGrouping:!0});this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new ve.ValueSubject(null);this.getCurrentTime$=new ve.ValueSubject(null);this.error$=new ve.Subject;this.logger=new ve.Logger,this.log=this.logger.createComponentLog("LiveTextManager"),this.params={fetchManifestData:i,sourceUrl:a},this.subscription.add(e.pipe((0,ve.throttle)(1e3)).subscribe(s=>{this.processLiveTime(s)})).add(this.logger.log$.subscribe(s=>{console.debug(`%c${s.component}`,"background:#258b6d;",s.message)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}async prepare(e){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=await this.fetchManifestData();await this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let i=await this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}}async parseTextTracks(e,t){for(let i of e){let a=new URL(i.url,t).toString();this.log({message:"[parseTextTracks]"}),this.log({message:a});let n=await(await Ze(a,{signal:this.abortControllers.destroy.signal})).text();this.log({message:n});let o=this.parsePlaylist(n,a);return this.log({message:JSON.stringify(o,void 0,2)}),{textTrack:i,playlist:o}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},a=e.split(`
|
|
124
|
-
`),s=0;for(let n=0;n<a.length;++n){let o=a[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=a[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!i.segmentStartTime){let d=new Date(i.vkStartTime).valueOf(),p=new Date(i.programDateTime).valueOf();i.segmentStartTime=p-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if((0,ve.isNonNullable)(e)&&this.currentTextTrackData){this.log({message:`[processLiveTime] ${e.toFixed(2)}, ${new Date(e).toISOString()}`});let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:a}=t[t.length-1].time;if(e<i){this.log({message:`[processLiveTime] out of bounds (before) ! ${i-e}`});return}if(e>a){this.log({message:`[processLiveTime] out of bounds (after) !' ${e-a}`});return}let s=a-e;this.log({message:`Current segments time left: ${this.numberFormat.format(s)} ms`}),s<4e3&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new me;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){let e=this.prepareUrl??this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:ve.ErrorCategory.WTF,thrown:t,message:e})}};var aa=class{constructor(e){this.subscription=new U.Subscription;this.videoState=new q("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new U.ValueSubject([]);this.liveOffset=new Tt;this.manifestStartTime$=new U.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=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(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=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),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(a?.to!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?A(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),A(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):a?.to==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="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"&&(A(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,U.assertNever)(t)}};this.params=e,this.video=Ie(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:U.VideoQuality.INVARIANT,url:this.params.source.url};let t=(i,a)=>ks(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},a);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new ws(this.params.output.liveTime$,this.video,t,this.params.source.url):this.textTracksManager=new Ue,t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:a})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:U.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(a,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:U.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ue(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new U.ValueSubject(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!a&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:U.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=Pe(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(a.ended$,e.endedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(xe(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(qe(this.video,t.playbackRate,a.playbackRateState$,i)),s(He(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe((0,U.filterChanged)(),(0,U.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,U.isNonNullable)(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(m=>m.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(ue(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(a.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add((0,U.combine)({startTime:this.manifestStartTime$.pipe((0,U.filter)(U.isNonNullable)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe((0,U.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let n=(0,U.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,U.observableFrom)(["init"])).pipe((0,U.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),Ee(this.video)}prepare(){let e=this.selectManifest();if((0,U.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=t?.to??i??{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&a.searchParams.set(c,d)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=he(a.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(n),this.video.setAttribute("src",n),this.video.load(),eu(n).then(o=>{if(!(0,U.isNullable)(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();((0,U.isNullable)(u)||!isFinite(u))&&Ze(n).then(l=>l.text()).then(l=>{let c=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(c){let d=new URL(c,n).toString();eu(d).then(p=>{(0,U.isNullable)(p)||this.maxSeekBackTime$.next(p)})}}).catch(()=>{})}})}playIfAllowed(){ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:U.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=he(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};var Q=require("@vkontakte/videoplayer-shared");var sa=class{constructor(e){this.subscription=new Q.Subscription;this.videoState=new q("stopped");this.textTracksManager=new Ue;this.manifests$=new Q.ValueSubject([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=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(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=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),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch(a?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?A(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):a?.to==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):a?.to==="paused"&&A(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,Q.assertNever)(t)}};this.params=e,this.video=Ie(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Q.VideoQuality.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ue(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),ks(he(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:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Q.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!a&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:Q.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},a=Pe(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,Q.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ut(this.video,t.isLooped,i)),this.subscription.add(xe(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(qe(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,Q.isNonNullable)(l.to)){let m=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(g=>g.id===m);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ue(f.url)))}let d=this.params.desiredState.playbackRate.getState(),p=this.params.output.element$.getValue()?.playbackRate;if(d!==p){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(d),m.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe((0,Q.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!Q.clientChecker.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,Q.merge)((0,Q.fromEvent)(o,"addtrack"),(0,Q.fromEvent)(o,"removetrack"),(0,Q.fromEvent)(o,"change"),(0,Q.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=(0,Q.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,Q.observableFrom)(["init"])).pipe((0,Q.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ee(this.video)}prepare(){let e=this.selectManifest();if((0,Q.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:s,min:n}=t?.to??i??{};for(let[o,u]of[[s,"mq"],[n,"lq"]]){let l=String(parseFloat(o||""));u&&o&&a.searchParams.set(u,l)}}this.video.setAttribute("src",a.toString()),this.video.load()}playIfAllowed(){ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Q.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var X=require("@vkontakte/videoplayer-shared");var na=class{constructor(e){this.subscription=new X.Subscription;this.videoState=new q("stopped");this.trackUrls={};this.textTracksManager=new Ue;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*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(i?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?A(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return(0,X.assertNever)(e)}};this.params=e,this.video=Ie(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],a)=>{let s=a.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),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,i=o=>{e.error$.next({id:"MpegProvider",category:X.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},a=Pe(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,X.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ut(this.video,t.isLooped,i)),this.subscription.add(xe(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(qe(this.video,t.playbackRate,a.playbackRateState$,i)),s(He(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&(0,X.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let u=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(u!==l){let c=this.params.output.element$.getValue();c&&(this.params.desiredState.playbackRate.setState(u),c.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=(0,X.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,X.observableFrom)(["init"])).pipe((0,X.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Ee(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;(0,X.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,X.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Kr(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ue(t))}playIfAllowed(){ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:X.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){let t,i=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){let a=Object.values(this.trackUrls).find(o=>!(0,X.isInvariantQuality)(o.track.quality)&&(0,X.isLowerOrEqual)(o.track.quality,e))?.track,s=this.params.desiredState.videoTrack.getState()?.id,n=this.trackUrls[s??"0"]?.track;if(a&&n&&(0,X.isHigherOrEqual)(n.quality,a.quality)&&(t=a),!t){let o=Object.values(this.trackUrls).filter(l=>!(0,X.isInvariantQuality)(l.track.quality)&&(0,X.isHigher)(l.track.quality,e)),u=o.length;u&&(t=o[u-1].track)}t&&(i=t.quality)}else if(!e){let a=Object.values(this.trackUrls).map(s=>s.track);t=Ot(a,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput: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:i})}};var te=require("@vkontakte/videoplayer-shared");var Pf=require("@vkontakte/videoplayer-shared"),xf=["stun:videostun.mycdn.me:80"],Yx=1e3,zx=3,ru=()=>null,As=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=ru;this.externalStopCallback=ru;this.externalErrorCallback=ru;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.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:xf}]};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:Pf.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),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))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),Yx)}normalizeOptions(e={}){let t={stunServerList:xf,maxRetryNumber:zx,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var oa=class{constructor(e){this.videoState=new q("stopped");this.maxSeekBackTime$=new te.ValueSubject(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return(0,te.assertNever)(e)}};this.subscription=new te.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ie(e.container,e.tuning),this.liveStreamClient=new As(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.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Ee(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:te.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};(0,te.merge)(this.videoState.stateChangeStarted$.pipe((0,te.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,te.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=Pe(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,i));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(He(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")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(a.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(xe(this.video,t.volume,a.volumeState$,i)).add(a.volumeState$.subscribe(e.volume$,i)).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,te.assertNever)(n.to)}},i)).add((0,te.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,te.observableFrom)(["init"])).pipe((0,te.debounce)(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ue(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:te.VideoQuality.INVARIANT}),this.video.srcObject=e,A(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:te.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:te.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var ua=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};var v=require("@vkontakte/videoplayer-shared");var wt=require("@vkontakte/videoplayer-shared"),kf=r=>new wt.Observable(e=>{let t=new wt.Subscription,i=r.desiredPlaybackState$.stateChangeStarted$.pipe((0,wt.map)(({from:l,to:c})=>`${l}-${c}`)),a=r.desiredPlaybackState$.stateChangeEnded$,s=r.providerChanged$.pipe((0,wt.map)(({type:l})=>l!==void 0)),n=new wt.Subject,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),r.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),r.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var Ge=require("@vkontakte/videoplayer-shared");function wf(){return new(window.AudioContext||window.webkitAudioContext)}var Af=require("@vkontakte/videoplayer-shared");var Fi=class r{constructor(e,t,i,a){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=a;this.destroyController=new me;this.subscriptions=new Ge.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,Ge.filter)(s=>!!s.type),(0,Ge.once)()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){Af.clientChecker.isSafari&&e!=="MPEG"||this.subscriptions.add((0,Ge.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,Ge.filter)(({playbackState:t,video:i,volume:{muted:a,volume:s}})=>t==="playing"&&!!i&&!a&&!!s),(0,Ge.once)()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,i=wf();this.audioContext=i;let a=i.createGain();if(this.gainNode=a,a.gain.value=t,a.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(a),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){this.volumeMultiplierError$.next({id:r.errorId,category:Ge.ErrorCategory.VIDEO_PIPELINE,message:e?.message??`${r.errorId} exception`,thrown:e})}};var Kx={chunkDuration:5e3,maxParallelRequests:5},la=class{constructor(e){this.current$=new v.ValueSubject({type:void 0});this.providerError$=new v.Subject;this.noAvailableProvidersError$=new v.Subject;this.volumeMultiplierError$=new v.Subject;this.providerOutput={position$:new v.ValueSubject(0),duration$:new v.ValueSubject(1/0),volume$:new v.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new v.ValueSubject([]),currentVideoStream$:new v.ValueSubject(void 0),availableVideoTracks$:new v.ValueSubject([]),currentVideoTrack$:new v.ValueSubject(void 0),availableAudioStreams$:new v.ValueSubject([]),currentAudioStream$:new v.ValueSubject(void 0),availableAudioTracks$:new v.ValueSubject([]),currentVideoSegmentLength$:new v.ValueSubject(0),currentAudioSegmentLength$:new v.ValueSubject(0),isAudioAvailable$:new v.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new v.ValueSubject(!1),autoVideoTrackLimits$:new v.ValueSubject(void 0),currentBuffer$:new v.ValueSubject(void 0),isBuffering$:new v.ValueSubject(!0),error$:new v.Subject,warning$:new v.Subject,willSeekEvent$:new v.Subject,soundProhibitedEvent$:new v.Subject,seekedEvent$:new v.Subject,loopedEvent$:new v.Subject,endedEvent$:new v.Subject,firstBytesEvent$:new v.Subject,loadedMetadataEvent$:new v.Subject,firstFrameEvent$:new v.Subject,canplay$:new v.Subject,isLive$:new v.ValueSubject(void 0),isLowLatency$:new v.ValueSubject(!1),canChangePlaybackSpeed$:new v.ValueSubject(!0),liveTime$:new v.ValueSubject(void 0),liveBufferTime$:new v.ValueSubject(void 0),availableTextTracks$:new v.ValueSubject([]),currentTextTrack$:new v.ValueSubject(void 0),hostname$:new v.ValueSubject(void 0),httpConnectionType$:new v.ValueSubject(void 0),httpConnectionReused$:new v.ValueSubject(void 0),inPiP$:new v.ValueSubject(!1),inFullscreen$:new v.ValueSubject(!1),element$:new v.ValueSubject(void 0),elementVisible$:new v.ValueSubject(!0),availableSources$:new v.ValueSubject(void 0),is3DVideo$:new v.ValueSubject(!1),playbackState$:new v.ValueSubject(""),getCurrentTime$:new v.ValueSubject(null)};this.subscription=new v.Subscription;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=gm([...vm(this.params.tuning),...Sm(this.params.tuning)],this.params.tuning).filter(l=>(0,v.isNonNullable)(e.sources[l])),{forceFormat:i,formatsToAvoid:a}=this.params.tuning,s=[];i?s=[i]:a.length?s=[...t.filter(l=>!a.includes(l)),...t.filter(l=>a.includes(l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,v.flattenObject)(s)),this.screenFormatsIterator=new ua(s);let n=[...Do(!0),...Do(!1)];this.chromecastFormatsIterator=new ua(n.filter(l=>(0,v.isNonNullable)(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Fi.isSupported()&&(this.volumeMultiplierManager=new Fi(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,v.isNullable)(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:v.ErrorCategory.WTF,message:"Failed to create provider",thrown:a})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),a=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:a?i.position:t,forcePrecise:a?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return(0,v.assertNever)(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:a}=this.params,s=this.providerOutput,n={container:i,source:null,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,v.assertNonNullable)(o),new ta({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new ia({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),Di||!this.params.tuning.useHlsJs?new sa({...n,source:o}):new ra({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new aa({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new na({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new cm({...n,source:o,config:{...Kx,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new oa({container:i,source:o,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,v.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:a,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,v.assertNonNullable)(o),new fr({connection:o,meta:s,container:i,source:t,format:e,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return(0,v.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,v.assertNever)(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return(0,v.assertNever)(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=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:i(e.url)}}return(0,Rf.default)(Object.entries(e).map(([a,s])=>[a,i(s)]))}initProviderErrorHandling(){let e=new v.Subscription,t=!1,i=0;return e.add((0,v.merge)(this.providerOutput.error$.pipe((0,v.filter)(a=>!this.params.tuning.ignoreAudioRendererError||!a.message||!/AUDIO_RENDERER_ERROR/ig.test(a.message))),kf({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,v.map)(a=>({id:`ProviderHangup:${a}`,category:v.ErrorCategory.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let a=this.params.desiredState.playbackState.transitionEnded$.pipe((0,v.filter)(({to:s})=>s==="playing"),(0,v.once)()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{let s=this.current$.getValue().destination,n={error:a,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=a.category===v.ErrorCategory.NETWORK,u=a.category===v.ErrorCategory.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c},c?(i++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s??"SCREEN")}this.tracer.error("providerError",(0,v.flattenObject)(n))})),e}};var _=require("@vkontakte/videoplayer-shared");var Xx=5e3,$f="one_video_throughput",Lf="one_video_rtt",ca=window.navigator.connection,Mf=()=>{let r=ca?.downlink;if((0,_.isNonNullable)(r)&&r!==10)return r*1e3},Df=()=>{let r=ca?.rtt;if((0,_.isNonNullable)(r)&&r!==3e3)return r},Cf=(r,e,t)=>{let i=t*8,a=i/r;return i/(a+e)},au=class r{constructor(e){this.subscription=new _.Subscription;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=r.load($f)||(e.useBrowserEstimation?Mf():void 0)||Xx,i=r.load(Lf)??(e.useBrowserEstimation?Df():void 0)??0;if(this.throughput$=new _.ValueSubject(t),this.rtt$=new _.ValueSubject(i),this.rttAdjustedThroughput$=new _.ValueSubject(Cf(t,i,e.rttPenaltyRequestSize)),this.throughput=ri.getSmoothedValue(t,-1,e),this.rtt=ri.getSmoothedValue(i,1,e),e.useBrowserEstimation){let a=()=>{let n=Mf();n&&this.throughput.next(n);let o=Df();(0,_.isNonNullable)(o)&&this.rtt.next(o)};ca&&"onchange"in ca&&this.subscription.add((0,_.fromEvent)(ca,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{_.safeStorage.set($f,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{_.safeStorage.set(Lf,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,_.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,_.map)(({throughput:a,rtt:s})=>Cf(a,s,e.rttPenaltyRequestSize)),(0,_.filter)(a=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(a-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=(0,_.now)(),a=new _.Subscription;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add((0,_.fromEvent)(e,"progress").pipe((0,_.once)()).subscribe(s=>{t=s.loaded,i=(0,_.now)()}));break;case 1:case 0:a.add((0,_.fromEvent)(e,"loadstart").subscribe(()=>{t=0,i=(0,_.now)()}));break}a.add((0,_.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,_.now)(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let a=0,s=(0,_.now)(),n=0,o=(0,_.now)(),u=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(a,(0,_.now)()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=(0,_.now)();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=d.byteLength,s=(0,_.now)()}else n+=d.byteLength;o=(0,_.now)()}else a+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,_.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,_.now)()-o,this.concurrentDownloads.size),n=0,o=(0,_.now)());await i?.read().then(l,u)}};this.concurrentDownloads.add(e),i?.read().then(l,u)}addRawSpeed(e,t,i=1,a=!1){if(r.sanityCheck(e,t,a)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let a=e*8/t;return!(!a||!isFinite(a)||a>1e6||a<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=_.safeStorage.get(e);if((0,_.isNonNullable)(t))return parseInt(t,10)??void 0}},Vf=au;var da=require("@vkontakte/videoplayer-shared"),Bf={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:1.2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:3e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:da.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:da.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,accumulationBufferStallSize:{shortVideoDuration:2*6e4,shortVideoBufferStallSize:0,longVideoBufferStallSize:0},qualityLimitsOnStall:{stallDurationBeforeQualityDecrease:0,stallDurationNoDataBeforeQualityDecrease:0,stallCountBeforeQualityDecrease:0,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1},Of=r=>({...(0,da.fillWithDefault)(r,Bf),configName:[...r.configName??[],...Bf.configName]});var h=require("@vkontakte/videoplayer-shared");var At=require("@vkontakte/videoplayer-shared"),su=({seekState:r,position$:e})=>(0,At.merge)(r.stateChangeEnded$.pipe((0,At.map)(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),(0,At.filter)(At.isNonNullable)),e.pipe((0,At.filter)(()=>r.getState().state==="none")));var _f=require("@vkontakte/videoplayer-shared"),Nf=r=>{let e=typeof r.container=="string"?document.getElementById(r.container):r.container;return(0,_f.assertNonNullable)(e,`Wrong container or containerId {${r.container}}`),e};var Rs=require("@vkontakte/videoplayer-shared"),Ff=(r,e,t,i)=>{r!==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(i)&&e.startTransitionTo(r)}):(r===void 0||t?.getValue().find(i))&&e.startTransitionTo(r)};var pa=class{constructor(e={configName:[]},t=h.Tracer.createRootTracer(!1)){this.subscription=new h.Subscription;this.logger=new h.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new h.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new q("stopped"),seekState:new q({state:"none"}),volume:new q({volume:1,muted:!1}),videoTrack:new q(void 0),videoStream:new q(void 0),audioStream:new q(void 0),autoVideoTrackSwitching:new q(!0),autoVideoTrackLimits:new q({}),isLooped:new q(!1),isLowLatency:new q(!1),playbackRate:new q(1),externalTextTracks:new q([]),internalTextTracks:new q([]),currentTextTrack:new q(void 0),textTrackCuesSettings:new q({}),cameraOrientation:new q({x:0,y:0})};this.info={playbackState$:new h.ValueSubject("stopped"),position$:new h.ValueSubject(0),duration$:new h.ValueSubject(1/0),muted$:new h.ValueSubject(!1),volume$:new h.ValueSubject(1),availableVideoStreams$:new h.ValueSubject([]),currentVideoStream$:new h.ValueSubject(void 0),availableQualities$:new h.ValueSubject([]),availableQualitiesFps$:new h.ValueSubject({}),currentQuality$:new h.ValueSubject(void 0),isAutoQualityEnabled$:new h.ValueSubject(!0),autoQualityLimitingAvailable$:new h.ValueSubject(!1),autoQualityLimits$:new h.ValueSubject({}),availableAudioStreams$:new h.ValueSubject([]),currentAudioStream$:new h.ValueSubject(void 0),availableAudioTracks$:new h.ValueSubject([]),isAudioAvailable$:new h.ValueSubject(!0),currentPlaybackRate$:new h.ValueSubject(1),currentBuffer$:new h.ValueSubject({start:0,end:0}),isBuffering$:new h.ValueSubject(!0),isStalled$:new h.ValueSubject(!1),isEnded$:new h.ValueSubject(!1),isLooped$:new h.ValueSubject(!1),isLive$:new h.ValueSubject(void 0),canChangePlaybackSpeed$:new h.ValueSubject(void 0),atLiveEdge$:new h.ValueSubject(void 0),atLiveDurationEdge$:new h.ValueSubject(void 0),liveTime$:new h.ValueSubject(void 0),liveBufferTime$:new h.ValueSubject(void 0),currentFormat$:new h.ValueSubject(void 0),availableTextTracks$:new h.ValueSubject([]),currentTextTrack$:new h.ValueSubject(void 0),throughputEstimation$:new h.ValueSubject(void 0),rttEstimation$:new h.ValueSubject(void 0),videoBitrate$:new h.ValueSubject(void 0),hostname$:new h.ValueSubject(void 0),httpConnectionType$:new h.ValueSubject(void 0),httpConnectionReused$:new h.ValueSubject(void 0),surface$:new h.ValueSubject("none"),chromecastState$:new h.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new h.ValueSubject(void 0),intrinsicVideoSize$:new h.ValueSubject(void 0),availableSources$:new h.ValueSubject(void 0),is3DVideo$:new h.ValueSubject(!1),currentVideoSegmentLength$:new h.ValueSubject(0),currentAudioSegmentLength$:new h.ValueSubject(0)};this.events={inited$:new h.Subject,ready$:new h.Subject,started$:new h.Subject,playing$:new h.Subject,paused$:new h.Subject,stopped$:new h.Subject,willStart$:new h.Subject,willResume$:new h.Subject,willPause$:new h.Subject,willStop$:new h.Subject,willDestruct$:new h.Subject,watchCoverageRecord$:new h.Subject,watchCoverageLive$:new h.Subject,managedError$:new h.Subject,fatalError$:new h.Subject,ended$:new h.Subject,looped$:new h.Subject,seeked$:new h.Subject,willSeek$:new h.Subject,autoplaySoundProhibited$:new h.Subject,firstBytes$:new h.Subject,loadedMetadata$:new h.Subject,firstFrame$:new h.Subject,canplay$:new h.Subject,log$:new h.Subject};this.experimental={element$:new h.ValueSubject(void 0),tuningConfigName$:new h.ValueSubject([]),enableDebugTelemetry$:new h.ValueSubject(!1),dumpTelemetry:em,getCurrentTime$:new h.ValueSubject(null)};if(this.initLogs(),this.tuning=Of(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ia({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Vf(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,a,s)=>{let n=Reflect.get(i,a,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(m,f)=>{let g=typeof f;return["number","string","boolean"].includes(g)?f:f===null?null:`<${g}>`})),c=`Player.${String(a)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:h.ErrorCategory.WTF,message:d,thrown:u}),u}}}})}initVideo(e){this.config=e;let{container:t,...i}=e;return this.tracer.log("initVideo",(0,h.flattenObject)(i)),this.domContainer=Nf(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new la({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Tr()?(this.tracer.log("request play from hidden tab"),(0,h.fromEvent)(document,"visibilitychange").pipe((0,h.once)()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let i=this.info.duration$.getValue(),a=this.info.isLive$.getValue(),s=e;return e>=i&&!a&&(s=i-.1),this.tracer.log("seekTime",{duration:i,isLive:a,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){(0,h.assertNonNullable)(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe((0,h.filter)(i=>i.length>0),(0,h.once)()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",(0,h.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){(0,h.assertNonNullable)(this.providerContainer);let t=this.providerContainer?.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",(0,h.flattenObject)(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return Ff(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let i=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let a=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:a.x+s.x,y:a.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if((0,h.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return(0,h.isNonNullable)(i)?i/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((i,{width:a})=>i||a||0,0),height:e.reduce((i,{height:a})=>i||a||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add((0,h.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,h.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,h.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,h.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,h.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,h.map)(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,h.filter)(({from:e})=>e==="stopped"),(0,h.once)()).subscribe(()=>{this.initedAt=(0,h.now)(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",(0,h.flattenObject)(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:h.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe((0,h.once)()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",(0,h.flattenObject)(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,h.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,h.map)(n=>n.destination),(0,h.filterChanged)()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe((0,h.map)(n=>n.map(({quality:o})=>o).sort((o,u)=>(0,h.isInvariantQuality)(o)?1:(0,h.isInvariantQuality)(u)?-1:(0,h.isHigher)(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe((0,h.filterChanged)()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe((0,h.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe((0,h.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,h.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,h.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,h.filterChanged)()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n??{})})).add(e.providerOutput.currentBuffer$.pipe((0,h.map)(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add((0,h.combine)({hasLiveOffsetByPaused:(0,h.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,h.map)(n=>n.to),(0,h.filterChanged)(),(0,h.map)(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add((0,h.combine)({atLiveEdge:(0,h.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:su({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,h.map)(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),(0,h.filterChanged)(),(0,h.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,h.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,h.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,h.map)(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,h.filterChanged)(),(0,h.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,h.map)(n=>n.muted),(0,h.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,h.map)(n=>n.volume),(0,h.filterChanged)()).subscribe(this.info.volume$)).add(su({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,h.merge)(e.providerOutput.endedEvent$.pipe((0,h.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,h.mapTo)(!1))).pipe((0,h.filterChanged)()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe((0,h.map)(n=>({id:n?`No${n}`:"NoProviders",category:h.ErrorCategory.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe((0,h.once)(),(0,h.map)(n=>n??(0,h.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,h.once)(),(0,h.map)(()=>(0,h.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,h.once)(),(0,h.map)(()=>(0,h.now)()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new h.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new h.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,h.filter)(({to:n})=>n==="playing"),(0,h.once)()).subscribe(()=>i.next(!1)));let a=0,s=(0,h.merge)(e.providerOutput.isBuffering$,t,i).pipe((0,h.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),(0,h.filterChanged)());this.subscription.add(s.subscribe(n=>{n?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})),this.subscription.add((0,h.merge)(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add((0,h.merge)(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,h.map)(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new h.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,h.filterChanged)((i,a)=>i.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,h.filter)(i=>i.length>0),(0,h.once)()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let i=this.explicitInitialQuality??this.desiredState.videoTrack.getState()?.quality;i&&(t=e.find(({quality:a})=>a===i),t||this.setAutoQuality(!0)),t||(t=Ot(e,{container:this.domContainer.getBoundingClientRect(),estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add((0,h.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,h.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,h.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,h.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,h.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,h.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,h.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,h.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,h.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,h.map)(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;(0,h.assertNonNullable)(this.providerContainer),(0,h.assertNonNullable)(e),Zh(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Jh(t)),this.providerContainer.current$.subscribe(({type:t})=>br("provider",t)),e.duration$.subscribe(t=>br("duration",t)),e.availableVideoTracks$.pipe((0,h.filter)(t=>!!t.length),(0,h.once)()).subscribe(t=>br("tracks",t)),this.events.fatalError$.subscribe(new Se("fatalError")),this.events.managedError$.subscribe(new Se("managedError")),e.position$.subscribe(new Se("position")),e.currentVideoTrack$.pipe((0,h.map)(t=>t?.quality)).subscribe(new Se("quality")),this.info.currentBuffer$.subscribe(new Se("buffer")),e.isBuffering$.subscribe(new Se("isBuffering"))].forEach(t=>this.subscription.add(t)),br("codecs",bm())}initTracerSubscription(){let e=(0,h.getTraceSubscriptionMethod)(this.tracer.log.bind(this.tracer)),t=(0,h.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe((0,h.filterChanged)()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add((0,h.combine)({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe((0,h.filter)(({currentQuality:i,videoBitrate:a})=>!!i&&!!a),(0,h.filterChanged)((i,a)=>i.currentQuality===a.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,h.filter)(i=>i>0),(0,h.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,h.filter)(i=>i>0),(0,h.filterChanged)()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add((0,h.combine)({currentBuffer:this.info.currentBuffer$.pipe((0,h.filter)(i=>i.end>0),(0,h.filterChanged)((i,a)=>i.end===a.end&&i.start===a.start)),position:this.info.position$.pipe((0,h.filterChanged)())}).pipe((0,h.throttle)(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe((0,h.filterChanged)()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe((0,h.filterChanged)()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe((0,h.filterChanged)()).subscribe(e("canChangePlaybackSpeed"))).add((0,h.combine)({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe((0,h.filter)(({liveTime:i,liveBufferTime:a})=>!!i&&!!a),(0,h.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,h.filterChanged)(),(0,h.filter)(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,h.filterChanged)(),(0,h.filter)(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe((0,h.filterChanged)()).subscribe(e("muted"))).add(this.info.volume$.pipe((0,h.filterChanged)()).subscribe(e("volume"))).add(this.info.isEnded$.pipe((0,h.filterChanged)(),(0,h.filter)(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add((0,h.combine)({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe((0,h.filter)(({throughputEstimation:i,rtt:a})=>!!i&&!!a),(0,h.throttle)(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe((0,h.filterChanged)(),(0,h.filter)(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:h.ErrorCategory.DOM,message:String(a)})})};this.subscription.add((0,h.merge)((0,h.fromEvent)(document,"visibilitychange"),(0,h.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let a=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!e?.released;a&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(a=>a.quality===t);this.tracer.log("setVideoTrackIdByQuality",(0,h.flattenObject)({quality:t,availableTracks:(0,h.flattenObject)(e),track:(0,h.flattenObject)(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};var pt=require("@vkontakte/videoplayer-shared"),Jx=`@vkontakte/videoplayer-core@${Ls}`;
|
|
122
|
+
`;var Es=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,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 Ts(this.params.fov,this.params.orientation),this.cameraRotationManager=new Is(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"),i=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(i),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(i,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(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(bf,this.gl.VERTEX_SHADER),i=this.createShader(gf,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),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,i=1,a=this.frameHeight/(this.frameWidth/this.viewportWidth);return a>this.viewportHeight?t=this.viewportHeight/a:i=a/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),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,i=this.camera.fov.x/360/2,a=this.camera.fov.y/180/2,s=e-i,n=t-a,o=e+i,u=t-a,l=e+i,c=t+a,d=e-i,h=t+a;return[s,n,o,u,l,c,d,h]}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 ce=require("@vkontakte/videoplayer-shared"),Jo=class{constructor(){this.isSeeked$=new ce.ValueSubject(!1);this.isBuffering$=new ce.ValueSubject(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new ce.Subscription}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add((0,ce.combine)({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe((0,ce.filter)(({isBuffering:t,isSeeked:i})=>t&&!i)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add((0,ce.combine)({currentStallDuration:this.currentStallDuration$,isSeeked:this.isSeeked$}).subscribe(({currentStallDuration:t,isSeeked:i})=>{if((0,ce.isNullable)(this.lastUniqueVideoTrackSelected))return;let{stallDurationBeforeQualityDecrease:a,stallDurationNoDataBeforeQualityDecrease:s,stallCountBeforeQualityDecrease:n,resetQualityRestrictionTimeout:o}=this.qualityLimitsOnStall,u=this.rtt$.getValue(),l=this.throughput$.getValue(),c=this.videoLastDataObtainedTimestamp$.getValue(),d=(0,ce.now)(),h=n&&this.currentStallsCount>=n,m=a&&!i&&d-this.lastUniqueVideoTrackSelectedTimestamp>=a+u&&t>=a,f=s&&d-this.lastUniqueVideoTrackSelectedTimestamp>=s+u&&d-c>=s+u&&t>=s;(h||m||f)&&(window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,(0,ce.isNonNullable)(this.lastUniqueVideoTrackSelected.bitrate)&&l>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},o))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=(0,ce.now)(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},Sf=Jo;var ri=class{constructor(e){this.subscription=new B.Subscription;this.videoState=new q("stopped");this.elementSize$=new B.ValueSubject(void 0);this.textTracksManager=new qe;this.droppedFramesManager=new os;this.stallsManager=new Sf;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new br;this.audioTrackSwitchHistory=new br;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state==="requested"&&i?.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"),w(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"),w(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&w(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset?.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&w(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()):i?.to==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return(0,B.assertNever)(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Es(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=ye(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ue(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new ys({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=Ee(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:B.ErrorCategory.WTF,message:`${a} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,B.filter)(c=>!!c.length),(0,B.once)()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,B.map)(c=>c.to.state!=="none"),(0,B.filterChanged)());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe((0,B.filterChanged)()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:i.isBuffering$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe((0,B.filter)(B.isNonNullable),(0,B.once)()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe((0,B.map)(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(nt(this.video,t.isLooped,a)),this.subscription.add(Ie(this.video,t.volume,i.volumeState$,a)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Fe(this.video,t.playbackRate,i.playbackRateState$,a)),s((0,B.observeElementSize)(this.video),this.elementSize$),s(Ue(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},a)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if((0,B.assertNonNullable)(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let f of d.audio){m.push(Qo(f));let g=[];for(let y of f.representations){let I=uf(y);g.push(I),this.audioTracksMap.set(I,{stream:f,representation:y})}this.audioStreamsMap.set(f,g)}this.params.output.availableAudioStreams$.next(m)}let h=[];for(let m of d.video){h.push(Wo(m));let f=[];for(let g of m.representations){let y=of({...g,streamId:m.id});y&&(f.push(y),this.videoTracksMap.set(y,{stream:m,representation:g}))}this.videoStreamsMap.set(m,f)}if(this.params.output.availableVideoStreams$.next(h),this.textTracksManager)for(let m of d.text)for(let f of m.representations){let g=lf(m,f);this.textTracksMap.set(g,{stream:m,representation:f})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a));let o=c=>e.error$.next({id:"RepresentationSwitch",category:B.ErrorCategory.WTF,message:"Switching representations threw",thrown:c});this.subscription.add((0,B.merge)(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,B.fromEvent)(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[m,f]=h,g=[...this.videoTracksMap.keys()].find(I=>this.videoTracksMap.get(I)?.representation.id===m.id);(0,B.isNonNullable)(g)&&(this.stallsManager.lastVideoTrackSelected=g);let y=this.params.desiredState.autoVideoTrackLimits.getTransition();if(y&&this.params.output.autoVideoTrackLimits$.next(y.to),c==="manifest_ready")this.player.initRepresentations(m.id,f?.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",m.id).catch(o),f){let I=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",f.id,I).catch(o)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSize$.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,B.filterChanged)()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:m}]=d,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Wo(m))},a)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,B.filterChanged)()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=d,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(Qo(m))},a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},a)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,a)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,a)),this.textTracksManager?.connect(this.video,t,e);let u=t.playbackState.stateChangeStarted$.pipe((0,B.map)(({to:c})=>c==="ready"),(0,B.filterChanged)());this.subscription.add((0,B.merge)(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add((0,B.merge)(u,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=(0,B.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,B.observableFrom)(["init"])).pipe((0,B.debounce)(0));this.subscription.add(l.subscribe(this.syncPlayback,a))}selectVideoAudioRepresentations(){let{desiredState:e,output:t}=this.params,i=e.autoVideoTrackSwitching.getState(),a=e.videoTrack.getState()?.id,n=[...this.videoTracksMap.keys()].find(({id:N})=>N===a),o=t.currentVideoTrack$.getValue(),u=e.videoStream.getState()??(n&&this.videoTracksMap.get(n)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:N})=>N===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=ut(this.video.buffered,this.video.currentTime*1e3),h=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,m=Math.min(d/Math.min(h,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),f=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),g=[...this.audioStreamsMap.keys()].find(({id:N})=>N===f?.id)??this.audioStreamsMap.keys().next().value,y=0;if(g){if(n&&!i){let N=ss(n,c,this.audioStreamsMap.get(g)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,N?.bitrate??-1/0)}if(o){let N=ss(o,c,this.audioStreamsMap.get(g)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,N?.bitrate??-1/0)}}let I=Bt(c,{container:this.elementSize$.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:y,forwardBufferHealth:m,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),P=i?I??n:n??I,k=g&&rm(P,c,this.audioStreamsMap.get(g)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:m,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),D=this.videoTracksMap.get(P)?.representation,x=k&&this.audioTracksMap.get(k)?.representation;if(D&&x)return[D,x];if(D&&!x&&this.audioTracksMap.size===0)return[D,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:B.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.destroy3DScene(),this.textTracksManager?.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Te(this.video),this.tracer.end()}};var ea=class extends ri{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var Ft=require("@vkontakte/videoplayer-shared");var ta=class extends ri{constructor(e){super(e),this.liveOffset=new vt,this.textTracksManager=null}subscribe(){super.subscribe();let{output:e,observableVideo:t,desiredState:i,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),a(t.timeUpdate$,e.liveBufferTime$),a(this.player.liveDuration$,e.duration$),this.subscription.add(i.isLowLatency.stateChangeEnded$.pipe((0,Ft.map)(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add((0,Ft.combine)({interval:(0,Ft.interval)(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{if(this.videoState.getState()==="playing"){let n=e.position$.getValue()+(s-1);n<=0&&e.position$.next(n),this.liveOffset?.resetTo(-n*1e3)}})).add((0,Ft.combine)({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,Ft.map)(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=cf(s);this.params.output.availableTextTracks$.next([n])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),a=t==="paused"&&i==="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 vf=Be(is(),1);var H=require("@vkontakte/videoplayer-shared"),Ze={};var _i=(r,e)=>new H.Observable(t=>{let i=(a,s)=>t.next(s);return r.on(e,i),()=>r.off(e,i)}),ia=class{constructor(e){this.subscription=new H.Subscription;this.videoState=new q("initializing");this.textTracksManager=new qe;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(e!=="initializing")switch(i?.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,H.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,H.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,H.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,H.assertNever)(e)}break;default:(0,H.assertNever)(t)}};this.video=ye(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ue(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),Te(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:H.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,vf.default)(import("hls.js").then(a=>{e||(Ze.Hls=a.default,Ze.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){(0,H.assertNonNullable)(Ze.Hls,"hls.js not loaded"),this.hls=new Ze.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,H.assertNonNullable)(Ze.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:H.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:l})},a=Ee(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,i));s(a.timeUpdate$,t.position$),s(a.durationChange$,t.duration$),s(a.ended$,t.endedEvent$),s(a.looped$,t.loopedEvent$),s(a.error$,t.error$),s(a.isBuffering$,t.isBuffering$),s(a.currentBuffer$,t.currentBuffer$),s(a.loadStart$,t.firstBytesEvent$),s(a.loadedMetadata$,t.loadedMetadataEvent$),s(a.playing$,t.firstFrameEvent$),s(a.canplay$,t.canplay$),s(a.seeked$,t.seekedEvent$),s(a.inPiP$,t.inPiP$),s(a.inFullscreen$,t.inFullscreen$),this.subscription.add(nt(this.video,e.isLooped,i)),this.subscription.add(Ie(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Fe(this.video,e.playbackRate,a.playbackRateState$,i)),s(Ue(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe((0,H.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(_i(this.hls,Ze.Events.ERROR).subscribe(l=>{l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:H.ErrorCategory.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${l.err?.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),w(e.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),w(e.playbackState,"paused")},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),s(_i(this.hls,Ze.Events.MANIFEST_PARSED).pipe((0,H.map)(({levels:l})=>l.reduce((c,d)=>{let h=d.name||d.height.toString(10),{width:m,height:f}=d,g=Dt(d.attrs.QUALITY??"")??(0,H.videoSizeToQuality)({width:m,height:f});if(!g)return c;let y=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,I={id:h.toString(),quality:g,bitrate:d.bitrate/1e3,size:{width:m,height:f},fps:y};return this.trackLevels.set(h,{track:I,level:d}),c.push(I),c},[]))),t.availableVideoTracks$),s(_i(this.hls,Ze.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let h=d.name,m=d.attrs.URI||"",f=d.lang;c.push({id:h,url:m,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(_i(this.hls,Ze.Events.LEVEL_LOADING).pipe((0,H.map)(({url:l})=>ue(l))),t.hostname$),s(_i(this.hls,Ze.Events.FRAG_CHANGED),l=>{let{video:c,audio:d}=l.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(Ct(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:i}));let n=l=>Array.from(this.trackLevels.values()).find(({level:c})=>c===l)?.track,o=_i(this.hls,Ze.Events.LEVEL_SWITCHED).pipe((0,H.map)(({level:l})=>n(this.hls.levels[l])));o.pipe((0,H.filter)(H.isNonNullable)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Ct(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{if((0,H.isNullable)(l))return;let c=this.trackLevels.get(l.id)?.level;if(!c)return;let d=this.hls.levels.indexOf(c),h=this.hls.currentLevel,m=this.hls.levels[h];!m||c.bitrate>m.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:i})),s(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=(0,H.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,H.observableFrom)(["init"])).pipe((0,H.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:H.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),w(this.params.desiredState.playbackState,"stopped",!0)}};var yf="X-Playback-Duration",Xo=async r=>{let e=await It(r),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(yf)?parseInt(e.headers.get(yf),10):void 0};var U=require("@vkontakte/videoplayer-shared");var eu=Be($n(),1);var xs=require("@vkontakte/videoplayer-shared");var Hx=r=>{let e=null;if(r.QUALITY&&(e=Dt(r.QUALITY)),!e&&r.RESOLUTION){let[t,i]=r.RESOLUTION.split("x").map(a=>parseInt(a,10));e=(0,xs.videoSizeToQuality)({width:t,height:i})}return e??null},jx=(r,e)=>{let t=r.split(`
|
|
123
|
+
`),i=[],a=[];for(let s=0;s<t.length;s++){let n=t[s],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),u=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!u)){if(o){let l=(0,eu.default)(o[1].split(",").map(y=>y.split("="))),c=l.QUALITY??`stream-${l.BANDWIDTH}`,d=Hx(l),h;l.BANDWIDTH&&(h=parseInt(l.BANDWIDTH,10)/1e3||void 0),!h&&l["AVERAGE-BANDWIDTH"]&&(h=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let m=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,f;if(l.RESOLUTION){let[y,I]=l.RESOLUTION.split("x").map(P=>parseInt(P,10));y&&I&&(f={width:y,height:I})}let g=new URL(t[++s],e).toString();d&&i.push({id:c,quality:d,url:g,bandwidth:h,size:f,fps:m})}if(u){let l=(0,eu.default)(u[1].split(",").map(m=>m.split("=")).map(([m,f])=>[m,f.replace(/^"|"$/g,"")])),c=l.URI?.replace(/playlist$/,"subtitles.vtt"),d=l.LANGUAGE,h=l.NAME;c&&d&&a.push({type:"internal",id:d,label:h,language:d,url:c,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:a}},Gx=r=>new Promise(e=>{setTimeout(()=>{e()},r)}),Zo=0,Tf=async(r,e=r,t)=>{let a=await(await It(r)).text();Zo+=1;try{let{qualityManifests:s,textTracks:n}=jx(a,e);return{qualityManifests:s,textTracks:n}}catch{if(Zo<=t.manifestRetryMaxCount)return await Gx((0,xs.getExponentialDelay)(Zo-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Tf(r,e,t)}return{qualityManifests:[],textTracks:[]}},Ps=Tf;var ra=class{constructor(e){this.subscription=new U.Subscription;this.videoState=new q("stopped");this.textTracksManager=new qe;this.manifests$=new U.ValueSubject([]);this.liveOffset=new vt;this.manifestStartTime$=new U.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=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(i==="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"),w(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=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),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(a?.to!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?w(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),w(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):a?.to==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="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"&&(w(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,U.assertNever)(t)}};this.params=e,this.video=ye(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:U.VideoQuality.INVARIANT,url:this.params.source.url},Ps(he(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t})=>{t.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:U.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:U.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ue(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new U.ValueSubject(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!a&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:U.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=Ee(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(a.ended$,e.endedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Ie(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Fe(this.video,t.playbackRate,a.playbackRateState$,i)),s(Ue(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe((0,U.filterChanged)(),(0,U.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,U.isNonNullable)(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(m=>m.id===d);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(ue(h.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(a.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add((0,U.combine)({startTime:this.manifestStartTime$.pipe((0,U.filter)(U.isNonNullable)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe((0,U.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let n=(0,U.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,U.observableFrom)(["init"])).pipe((0,U.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Te(this.video)}prepare(){let e=this.selectManifest();if((0,U.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=t?.to??i??{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&a.searchParams.set(c,d)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=he(a.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),Xo(n).then(o=>{if(!(0,U.isNullable)(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if((0,U.isNullable)(u)||!isFinite(u))try{It(n).then(l=>l.text()).then(l=>{let c=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(c){let d=new URL(c,n).toString();Xo(d).then(h=>{(0,U.isNullable)(h)||this.maxSeekBackTime$.next(h)})}})}catch{}}})}playIfAllowed(){xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:U.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}};var Q=require("@vkontakte/videoplayer-shared");var aa=class{constructor(e){this.subscription=new Q.Subscription;this.videoState=new q("stopped");this.textTracksManager=new qe;this.manifests$=new Q.ValueSubject([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=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(i==="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"),w(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=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),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch(a?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?w(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):a?.to==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):a?.to==="paused"&&w(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,Q.assertNever)(t)}};this.params=e,this.video=ye(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Q.VideoQuality.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ue(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Ps(he(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:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Q.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!a&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:Q.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},a=Ee(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,Q.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(nt(this.video,t.isLooped,i)),this.subscription.add(Ie(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Fe(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,Q.isNonNullable)(l.to)){let m=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(g=>g.id===m);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ue(f.url)))}let d=this.params.desiredState.playbackRate.getState(),h=this.params.output.element$.getValue()?.playbackRate;if(d!==h){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(d),m.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe((0,Q.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!Q.clientChecker.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,Q.merge)((0,Q.fromEvent)(o,"addtrack"),(0,Q.fromEvent)(o,"removetrack"),(0,Q.fromEvent)(o,"change"),(0,Q.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=(0,Q.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,Q.observableFrom)(["init"])).pipe((0,Q.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Te(this.video)}prepare(){let e=this.selectManifest();if((0,Q.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:s,min:n}=t?.to??i??{};for(let[o,u]of[[s,"mq"],[n,"lq"]]){let l=String(parseFloat(o||""));u&&o&&a.searchParams.set(u,l)}}this.video.setAttribute("src",a.toString()),this.video.load()}playIfAllowed(){xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Q.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var J=require("@vkontakte/videoplayer-shared");var sa=class{constructor(e){this.subscription=new J.Subscription;this.videoState=new q("stopped");this.trackUrls={};this.textTracksManager=new qe;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=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"),w(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:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*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(i?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?w(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return(0,J.assertNever)(e)}};this.params=e,this.video=ye(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],a)=>{let s=a.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),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,i=o=>{e.error$.next({id:"MpegProvider",category:J.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},a=Ee(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,J.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(nt(this.video,t.isLooped,i)),this.subscription.add(Ie(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Fe(this.video,t.playbackRate,a.playbackRateState$,i)),s(Ue(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},i)).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 u=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(u!==l){let c=this.params.output.element$.getValue();c&&(this.params.desiredState.playbackRate.setState(u),c.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),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,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Te(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=zr(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ue(t))}playIfAllowed(){xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),w(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,i=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(l=>!(0,J.isInvariantQuality)(l.track.quality)&&(0,J.isHigher)(l.track.quality,e)),u=o.length;u&&(t=o[u-1].track)}t&&(i=t.quality)}else if(!e){let a=Object.values(this.trackUrls).map(s=>s.track);t=Bt(a,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput: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:i})}};var te=require("@vkontakte/videoplayer-shared");var Ef=require("@vkontakte/videoplayer-shared"),If=["stun:videostun.mycdn.me:80"],Qx=1e3,Wx=3,tu=()=>null,ks=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=tu;this.externalStopCallback=tu;this.externalErrorCallback=tu;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.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:If}]};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:Ef.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),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))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),Qx)}normalizeOptions(e={}){let t={stunServerList:If,maxRetryNumber:Wx,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var na=class{constructor(e){this.videoState=new q("stopped");this.maxSeekBackTime$=new te.ValueSubject(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=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"),w(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"),w(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return(0,te.assertNever)(e)}};this.subscription=new te.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ye(e.container,e.tuning),this.liveStreamClient=new ks(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Te(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:te.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};(0,te.merge)(this.videoState.stateChangeStarted$.pipe((0,te.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,te.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=Ee(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,i));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(Ue(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")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(a.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ie(this.video,t.volume,a.volumeState$,i)).add(a.volumeState$.subscribe(e.volume$,i)).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,te.assertNever)(n.to)}},i)).add((0,te.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,te.observableFrom)(["init"])).pipe((0,te.debounce)(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ue(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:te.VideoQuality.INVARIANT}),this.video.srcObject=e,w(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:te.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:te.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var oa=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};var v=require("@vkontakte/videoplayer-shared");var kt=require("@vkontakte/videoplayer-shared"),xf=r=>new kt.Observable(e=>{let t=new kt.Subscription,i=r.desiredPlaybackState$.stateChangeStarted$.pipe((0,kt.map)(({from:l,to:c})=>`${l}-${c}`)),a=r.desiredPlaybackState$.stateChangeEnded$,s=r.providerChanged$.pipe((0,kt.map)(({type:l})=>l!==void 0)),n=new kt.Subject,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),r.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),r.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var je=require("@vkontakte/videoplayer-shared");function Pf(){return new(window.AudioContext||window.webkitAudioContext)}var kf=require("@vkontakte/videoplayer-shared");var Ni=class r{constructor(e,t,i,a){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=a;this.destroyController=new Ce;this.subscriptions=new je.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,je.filter)(s=>!!s.type),(0,je.once)()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){kf.clientChecker.isSafari&&e!=="MPEG"||this.subscriptions.add((0,je.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,je.filter)(({playbackState:t,video:i,volume:{muted:a,volume:s}})=>t==="playing"&&!!i&&!a&&!!s),(0,je.once)()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,i=Pf();this.audioContext=i;let a=i.createGain();if(this.gainNode=a,a.gain.value=t,a.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(a),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){this.volumeMultiplierError$.next({id:r.errorId,category:je.ErrorCategory.VIDEO_PIPELINE,message:e?.message??`${r.errorId} exception`,thrown:e})}};var Yx={chunkDuration:5e3,maxParallelRequests:5},ua=class{constructor(e){this.current$=new v.ValueSubject({type:void 0});this.providerError$=new v.Subject;this.noAvailableProvidersError$=new v.Subject;this.volumeMultiplierError$=new v.Subject;this.providerOutput={position$:new v.ValueSubject(0),duration$:new v.ValueSubject(1/0),volume$:new v.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new v.ValueSubject([]),currentVideoStream$:new v.ValueSubject(void 0),availableVideoTracks$:new v.ValueSubject([]),currentVideoTrack$:new v.ValueSubject(void 0),availableAudioStreams$:new v.ValueSubject([]),currentAudioStream$:new v.ValueSubject(void 0),availableAudioTracks$:new v.ValueSubject([]),currentVideoSegmentLength$:new v.ValueSubject(0),currentAudioSegmentLength$:new v.ValueSubject(0),isAudioAvailable$:new v.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new v.ValueSubject(!1),autoVideoTrackLimits$:new v.ValueSubject(void 0),currentBuffer$:new v.ValueSubject(void 0),isBuffering$:new v.ValueSubject(!0),error$:new v.Subject,warning$:new v.Subject,willSeekEvent$:new v.Subject,soundProhibitedEvent$:new v.Subject,seekedEvent$:new v.Subject,loopedEvent$:new v.Subject,endedEvent$:new v.Subject,firstBytesEvent$:new v.Subject,loadedMetadataEvent$:new v.Subject,firstFrameEvent$:new v.Subject,canplay$:new v.Subject,isLive$:new v.ValueSubject(void 0),isLowLatency$:new v.ValueSubject(!1),canChangePlaybackSpeed$:new v.ValueSubject(!0),liveTime$:new v.ValueSubject(void 0),liveBufferTime$:new v.ValueSubject(void 0),availableTextTracks$:new v.ValueSubject([]),currentTextTrack$:new v.ValueSubject(void 0),hostname$:new v.ValueSubject(void 0),httpConnectionType$:new v.ValueSubject(void 0),httpConnectionReused$:new v.ValueSubject(void 0),inPiP$:new v.ValueSubject(!1),inFullscreen$:new v.ValueSubject(!1),element$:new v.ValueSubject(void 0),elementVisible$:new v.ValueSubject(!0),availableSources$:new v.ValueSubject(void 0),is3DVideo$:new v.ValueSubject(!1),playbackState$:new v.ValueSubject("")};this.subscription=new v.Subscription;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=fm([...gm(this.params.tuning),...bm(this.params.tuning)],this.params.tuning).filter(l=>(0,v.isNonNullable)(e.sources[l])),{forceFormat:i,formatsToAvoid:a}=this.params.tuning,s=[];i?s=[i]:a.length?s=[...t.filter(l=>!a.includes(l)),...t.filter(l=>a.includes(l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,v.flattenObject)(s)),this.screenFormatsIterator=new oa(s);let n=[...Lo(!0),...Lo(!1)];this.chromecastFormatsIterator=new oa(n.filter(l=>(0,v.isNonNullable)(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Ni.isSupported()&&(this.volumeMultiplierManager=new Ni(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,v.isNullable)(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:v.ErrorCategory.WTF,message:"Failed to create provider",thrown:a})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),a=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:a?i.position:t,forcePrecise:a?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return(0,v.assertNever)(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:a}=this.params,s=this.providerOutput,n={container:i,source:null,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,v.assertNonNullable)(o),new ea({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new ta({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),Mi||!this.params.tuning.useHlsJs?new aa({...n,source:o}):new ia({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new ra({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new sa({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new um({...n,source:o,config:{...Yx,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new na({container:i,source:o,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,v.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:a,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,v.assertNonNullable)(o),new mr({connection:o,meta:s,container:i,source:t,format:e,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return(0,v.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,v.assertNever)(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return(0,v.assertNever)(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=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:i(e.url)}}return(0,Af.default)(Object.entries(e).map(([a,s])=>[a,i(s)]))}initProviderErrorHandling(){let e=new v.Subscription,t=!1,i=0;return e.add((0,v.merge)(this.providerOutput.error$.pipe((0,v.filter)(a=>!this.params.tuning.ignoreAudioRendererError||!a.message||!/AUDIO_RENDERER_ERROR/ig.test(a.message))),xf({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,v.map)(a=>({id:`ProviderHangup:${a}`,category:v.ErrorCategory.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let a=this.params.desiredState.playbackState.transitionEnded$.pipe((0,v.filter)(({to:s})=>s==="playing"),(0,v.once)()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{let s=this.current$.getValue().destination,n={error:a,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=a.category===v.ErrorCategory.NETWORK,u=a.category===v.ErrorCategory.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c},c?(i++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s??"SCREEN")}this.tracer.error("providerError",(0,v.flattenObject)(n))})),e}};var _=require("@vkontakte/videoplayer-shared");var zx=5e3,wf="one_video_throughput",Rf="one_video_rtt",la=window.navigator.connection,$f=()=>{let r=la?.downlink;if((0,_.isNonNullable)(r)&&r!==10)return r*1e3},Lf=()=>{let r=la?.rtt;if((0,_.isNonNullable)(r)&&r!==3e3)return r},Mf=(r,e,t)=>{let i=t*8,a=i/r;return i/(a+e)},iu=class r{constructor(e){this.subscription=new _.Subscription;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=r.load(wf)||(e.useBrowserEstimation?$f():void 0)||zx,i=r.load(Rf)??(e.useBrowserEstimation?Lf():void 0)??0;if(this.throughput$=new _.ValueSubject(t),this.rtt$=new _.ValueSubject(i),this.rttAdjustedThroughput$=new _.ValueSubject(Mf(t,i,e.rttPenaltyRequestSize)),this.throughput=ii.getSmoothedValue(t,-1,e),this.rtt=ii.getSmoothedValue(i,1,e),e.useBrowserEstimation){let a=()=>{let n=$f();n&&this.throughput.next(n);let o=Lf();(0,_.isNonNullable)(o)&&this.rtt.next(o)};la&&"onchange"in la&&this.subscription.add((0,_.fromEvent)(la,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{_.safeStorage.set(wf,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{_.safeStorage.set(Rf,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,_.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,_.map)(({throughput:a,rtt:s})=>Mf(a,s,e.rttPenaltyRequestSize)),(0,_.filter)(a=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(a-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=(0,_.now)(),a=new _.Subscription;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add((0,_.fromEvent)(e,"progress").pipe((0,_.once)()).subscribe(s=>{t=s.loaded,i=(0,_.now)()}));break;case 1:case 0:a.add((0,_.fromEvent)(e,"loadstart").subscribe(()=>{t=0,i=(0,_.now)()}));break}a.add((0,_.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,_.now)(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let a=0,s=(0,_.now)(),n=0,o=(0,_.now)(),u=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(a,(0,_.now)()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=(0,_.now)();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=d.byteLength,s=(0,_.now)()}else n+=d.byteLength;o=(0,_.now)()}else a+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,_.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,_.now)()-o,this.concurrentDownloads.size),n=0,o=(0,_.now)());await i?.read().then(l,u)}};this.concurrentDownloads.add(e),i?.read().then(l,u)}addRawSpeed(e,t,i=1,a=!1){if(r.sanityCheck(e,t,a)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let a=e*8/t;return!(!a||!isFinite(a)||a>1e6||a<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=_.safeStorage.get(e);if((0,_.isNonNullable)(t))return parseInt(t,10)??void 0}},Cf=iu;var ca=require("@vkontakte/videoplayer-shared"),Df={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:1.2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:3e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:ca.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:ca.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,accumulationBufferStallSize:{shortVideoDuration:2*6e4,shortVideoBufferStallSize:0,longVideoBufferStallSize:0},qualityLimitsOnStall:{stallDurationBeforeQualityDecrease:0,stallDurationNoDataBeforeQualityDecrease:0,stallCountBeforeQualityDecrease:0,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1},Vf=r=>({...(0,ca.fillWithDefault)(r,Df),configName:[...r.configName??[],...Df.configName]});var p=require("@vkontakte/videoplayer-shared");var At=require("@vkontakte/videoplayer-shared"),ru=({seekState:r,position$:e})=>(0,At.merge)(r.stateChangeEnded$.pipe((0,At.map)(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),(0,At.filter)(At.isNonNullable)),e.pipe((0,At.filter)(()=>r.getState().state==="none")));var Bf=require("@vkontakte/videoplayer-shared"),Of=r=>{let e=typeof r.container=="string"?document.getElementById(r.container):r.container;return(0,Bf.assertNonNullable)(e,`Wrong container or containerId {${r.container}}`),e};var As=require("@vkontakte/videoplayer-shared"),_f=(r,e,t,i)=>{r!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe((0,As.filter)(a=>a.length>0),(0,As.once)()).subscribe(a=>{a.find(i)&&e.startTransitionTo(r)}):(r===void 0||t?.getValue().find(i))&&e.startTransitionTo(r)};var da=class{constructor(e={configName:[]},t=p.Tracer.createRootTracer(!1)){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.wasSetStartedQuality=!1;this.desiredState={playbackState:new q("stopped"),seekState:new q({state:"none"}),volume:new q({volume:1,muted:!1}),videoTrack:new q(void 0),videoStream:new q(void 0),audioStream:new q(void 0),autoVideoTrackSwitching:new q(!0),autoVideoTrackLimits:new q({}),isLooped:new q(!1),isLowLatency:new q(!1),playbackRate:new q(1),externalTextTracks:new q([]),internalTextTracks:new q([]),currentTextTrack:new q(void 0),textTrackCuesSettings:new q({}),cameraOrientation:new q({x:0,y:0})};this.info={playbackState$:new p.ValueSubject("stopped"),position$:new p.ValueSubject(0),duration$:new p.ValueSubject(1/0),muted$:new p.ValueSubject(!1),volume$:new p.ValueSubject(1),availableVideoStreams$:new p.ValueSubject([]),currentVideoStream$:new p.ValueSubject(void 0),availableQualities$:new p.ValueSubject([]),availableQualitiesFps$:new p.ValueSubject({}),currentQuality$:new p.ValueSubject(void 0),isAutoQualityEnabled$:new p.ValueSubject(!0),autoQualityLimitingAvailable$:new p.ValueSubject(!1),autoQualityLimits$:new p.ValueSubject({}),availableAudioStreams$:new p.ValueSubject([]),currentAudioStream$:new p.ValueSubject(void 0),availableAudioTracks$:new p.ValueSubject([]),isAudioAvailable$:new p.ValueSubject(!0),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,autoplaySoundProhibited$:new p.Subject,firstBytes$:new p.Subject,loadedMetadata$: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:Xh};if(this.initLogs(),this.tuning=Vf(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ta({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Cf(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,a,s)=>{let n=Reflect.get(i,a,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(h=>JSON.stringify(h,(m,f)=>{let g=typeof f;return["number","string","boolean"].includes(g)?f:f===null?null:`<${g}>`})),c=`Player.${String(a)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:p.ErrorCategory.WTF,message:d,thrown:u}),u}}}})}initVideo(e){this.config=e;let{container:t,...i}=e;return this.tracer.log("initVideo",(0,p.flattenObject)(i)),this.domContainer=Of(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new ua({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!yr()?(this.tracer.log("request play from hidden tab"),(0,p.fromEvent)(document,"visibilitychange").pipe((0,p.once)()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let i=this.info.duration$.getValue(),a=this.info.isLive$.getValue(),s=e;return e>=i&&!a&&(s=i-.1),this.tracer.log("seekTime",{duration:i,isLive:a,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){(0,p.assertNonNullable)(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe((0,p.filter)(i=>i.length>0),(0,p.once)()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",(0,p.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){(0,p.assertNonNullable)(this.providerContainer);let t=this.providerContainer?.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",(0,p.flattenObject)(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return _f(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let i=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let a=i.getCameraRotation(),s=i.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(),i=t.state==="none"?void 0:t.position;return(0,p.isNonNullable)(i)?i/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((i,{width:a})=>i||a||0,0),height:e.reduce((i,{height:a})=>i||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();this.tracer.log("willSeekEvent",(0,p.flattenObject)(n)),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.soundProhibitedEvent$.pipe((0,p.once)()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",(0,p.flattenObject)(n)),n.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.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add((0,p.merge)(e.providerOutput.availableVideoTracks$,e.providerOutput.currentVideoStream$).subscribe(()=>{let n=e.providerOutput.availableVideoTracks$.getValue(),o=e.providerOutput.currentVideoStream$.getValue(),u=n.filter(l=>o?.id===l.streamId).map(({quality:l})=>l).sort((l,c)=>(0,p.isInvariantQuality)(l)?1:(0,p.isInvariantQuality)(c)?-1:(0,p.isHigher)(c,l)?1:-1);this.info.availableQualities$.next(u)})).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe((0,p.filterChanged)()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe((0,p.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe((0,p.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).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:ru({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,p.map)(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/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:u})=>n&&(Math.abs(u)-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(ru({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.volumeMultiplierError$.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.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).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 i=new p.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,p.filter)(({to:n})=>n==="playing"),(0,p.once)()).subscribe(()=>i.next(!1)));let a=0,s=(0,p.merge)(e.providerOutput.isBuffering$,t,i).pipe((0,p.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.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(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?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)((i,a)=>i.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,p.filter)(i=>i.length>0),(0,p.once)()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let i=this.explicitInitialQuality??this.desiredState.videoTrack.getState()?.quality;i&&(t=e.find(({quality:a})=>a===i),t||this.setAutoQuality(!0)),t||(t=Bt(e,{container:this.domContainer.getBoundingClientRect(),estimatedThroughput: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),Jh(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Kh(t)),this.providerContainer.current$.subscribe(({type:t})=>fr("provider",t)),e.duration$.subscribe(t=>fr("duration",t)),e.availableVideoTracks$.pipe((0,p.filter)(t=>!!t.length),(0,p.once)()).subscribe(t=>fr("tracks",t)),this.events.fatalError$.subscribe(new ge("fatalError")),this.events.managedError$.subscribe(new ge("managedError")),e.position$.subscribe(new ge("position")),e.currentVideoTrack$.pipe((0,p.map)(t=>t?.quality)).subscribe(new ge("quality")),this.info.currentBuffer$.subscribe(new ge("buffer")),e.isBuffering$.subscribe(new ge("isBuffering"))].forEach(t=>this.subscription.add(t)),fr("codecs",mm())}initTracerSubscription(){let e=(0,p.getTraceSubscriptionMethod)(this.tracer.log.bind(this.tracer)),t=(0,p.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe((0,p.filterChanged)()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add((0,p.combine)({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe((0,p.filter)(({currentQuality:i,videoBitrate:a})=>!!i&&!!a),(0,p.filterChanged)((i,a)=>i.currentQuality===a.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,p.filter)(i=>i>0),(0,p.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,p.filter)(i=>i>0),(0,p.filterChanged)()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add((0,p.combine)({currentBuffer:this.info.currentBuffer$.pipe((0,p.filter)(i=>i.end>0),(0,p.filterChanged)((i,a)=>i.end===a.end&&i.start===a.start)),position:this.info.position$.pipe((0,p.filterChanged)())}).pipe((0,p.throttle)(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe((0,p.filterChanged)()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe((0,p.filterChanged)()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe((0,p.filterChanged)()).subscribe(e("canChangePlaybackSpeed"))).add((0,p.combine)({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe((0,p.filter)(({liveTime:i,liveBufferTime:a})=>!!i&&!!a),(0,p.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,p.filterChanged)(),(0,p.filter)(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,p.filterChanged)(),(0,p.filter)(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe((0,p.filterChanged)()).subscribe(e("muted"))).add(this.info.volume$.pipe((0,p.filterChanged)()).subscribe(e("volume"))).add(this.info.isEnded$.pipe((0,p.filterChanged)(),(0,p.filter)(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add((0,p.combine)({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe((0,p.filter)(({throughputEstimation:i,rtt:a})=>!!i&&!!a),(0,p.throttle)(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe((0,p.filterChanged)(),(0,p.filter)(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},i=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||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(a=>a.quality===t);this.tracer.log("setVideoTrackIdByQuality",(0,p.flattenObject)({quality:t,availableTracks:(0,p.flattenObject)(e),track:(0,p.flattenObject)(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};var ct=require("@vkontakte/videoplayer-shared"),Kx=`@vkontakte/videoplayer-core@${Rs}`;
|