@vkontakte/videoplayer-core 2.0.149-dev.a444d83a.0 → 2.0.149

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/es2024.esm.js CHANGED
@@ -1,10 +1,10 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.149-dev.a444d83a.0
3
- * Thu, 11 Dec 2025 14:48:07 GMT
2
+ * @vkontakte/videoplayer-core v2.0.149
3
+ * Tue, 16 Dec 2025 09:23:45 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-149/doc/
5
5
  */
6
- var Uw=Object.create;var ch=Object.defineProperty;var qw=Object.getOwnPropertyDescriptor;var jw=Object.getOwnPropertyNames;var Hw=Object.getPrototypeOf,zw=Object.prototype.hasOwnProperty;var b=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var Qw=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of jw(e))!zw.call(s,r)&&r!==t&&ch(s,r,{get:()=>e[r],enumerable:!(i=qw(e,r))||i.enumerable});return s};var D=(s,e,t)=>(t=s!=null?Uw(Hw(s)):{},Qw(e||!s||!s.__esModule?ch(t,"default",{value:s,enumerable:!0}):t,s));var se=b((el,ph)=>{"use strict";var xs=function(s){return s&&s.Math===Math&&s};ph.exports=xs(typeof globalThis=="object"&&globalThis)||xs(typeof window=="object"&&window)||xs(typeof self=="object"&&self)||xs(typeof global=="object"&&global)||xs(typeof el=="object"&&el)||function(){return this}()||Function("return this")()});var be=b((mN,hh)=>{"use strict";hh.exports=function(s){try{return!!s()}catch{return!0}}});var ks=b((bN,fh)=>{"use strict";var Ww=be();fh.exports=!Ww(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")})});var tl=b((gN,Sh)=>{"use strict";var Gw=ks(),gh=Function.prototype,mh=gh.apply,bh=gh.call;Sh.exports=typeof Reflect=="object"&&Reflect.apply||(Gw?bh.bind(mh):function(){return bh.apply(mh,arguments)})});var ge=b((SN,Th)=>{"use strict";var vh=ks(),yh=Function.prototype,il=yh.call,Yw=vh&&yh.bind.bind(il,il);Th.exports=vh?Yw:function(s){return function(){return il.apply(s,arguments)}}});var Ai=b((vN,Eh)=>{"use strict";var Ih=ge(),Kw=Ih({}.toString),Xw=Ih("".slice);Eh.exports=function(s){return Xw(Kw(s),8,-1)}});var rl=b((yN,wh)=>{"use strict";var Jw=Ai(),Zw=ge();wh.exports=function(s){if(Jw(s)==="Function")return Zw(s)}});var ae=b((TN,xh)=>{"use strict";var sl=typeof document=="object"&&document.all;xh.exports=typeof sl>"u"&&sl!==void 0?function(s){return typeof s=="function"||s===sl}:function(s){return typeof s=="function"}});var Je=b((IN,kh)=>{"use strict";var ex=be();kh.exports=!ex(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ze=b((EN,Ph)=>{"use strict";var tx=ks(),Un=Function.prototype.call;Ph.exports=tx?Un.bind(Un):function(){return Un.apply(Un,arguments)}});var al=b($h=>{"use strict";var Ah={}.propertyIsEnumerable,Rh=Object.getOwnPropertyDescriptor,ix=Rh&&!Ah.call({1:2},1);$h.f=ix?function(e){var t=Rh(this,e);return!!t&&t.enumerable}:Ah});var Ps=b((xN,Mh)=>{"use strict";Mh.exports=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}}});var Dh=b((kN,Lh)=>{"use strict";var rx=ge(),sx=be(),ax=Ai(),nl=Object,nx=rx("".split);Lh.exports=sx(function(){return!nl("z").propertyIsEnumerable(0)})?function(s){return ax(s)==="String"?nx(s,""):nl(s)}:nl});var As=b((PN,Bh)=>{"use strict";Bh.exports=function(s){return s==null}});var ii=b((AN,Ch)=>{"use strict";var ox=As(),ux=TypeError;Ch.exports=function(s){if(ox(s))throw new ux("Can't call method on "+s);return s}});var Ri=b((RN,Vh)=>{"use strict";var lx=Dh(),cx=ii();Vh.exports=function(s){return lx(cx(s))}});var ze=b(($N,_h)=>{"use strict";var dx=ae();_h.exports=function(s){return typeof s=="object"?s!==null:dx(s)}});var $i=b((MN,Oh)=>{"use strict";Oh.exports={}});var Vt=b((LN,Fh)=>{"use strict";var ol=$i(),ul=se(),px=ae(),Nh=function(s){return px(s)?s:void 0};Fh.exports=function(s,e){return arguments.length<2?Nh(ol[s])||Nh(ul[s]):ol[s]&&ol[s][e]||ul[s]&&ul[s][e]}});var Rs=b((DN,Uh)=>{"use strict";var hx=ge();Uh.exports=hx({}.isPrototypeOf)});var Mi=b((BN,Hh)=>{"use strict";var fx=se(),qh=fx.navigator,jh=qh&&qh.userAgent;Hh.exports=jh?String(jh):""});var cl=b((CN,Kh)=>{"use strict";var Yh=se(),ll=Mi(),zh=Yh.process,Qh=Yh.Deno,Wh=zh&&zh.versions||Qh&&Qh.version,Gh=Wh&&Wh.v8,mt,qn;Gh&&(mt=Gh.split("."),qn=mt[0]>0&&mt[0]<4?1:+(mt[0]+mt[1]));!qn&&ll&&(mt=ll.match(/Edge\/(\d+)/),(!mt||mt[1]>=74)&&(mt=ll.match(/Chrome\/(\d+)/),mt&&(qn=+mt[1])));Kh.exports=qn});var dl=b((VN,Jh)=>{"use strict";var Xh=cl(),mx=be(),bx=se(),gx=bx.String;Jh.exports=!!Object.getOwnPropertySymbols&&!mx(function(){var s=Symbol("symbol detection");return!gx(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&Xh&&Xh<41})});var pl=b((_N,Zh)=>{"use strict";var Sx=dl();Zh.exports=Sx&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var hl=b((ON,ef)=>{"use strict";var vx=Vt(),yx=ae(),Tx=Rs(),Ix=pl(),Ex=Object;ef.exports=Ix?function(s){return typeof s=="symbol"}:function(s){var e=vx("Symbol");return yx(e)&&Tx(e.prototype,Ex(s))}});var $s=b((NN,tf)=>{"use strict";var wx=String;tf.exports=function(s){try{return wx(s)}catch{return"Object"}}});var kt=b((FN,rf)=>{"use strict";var xx=ae(),kx=$s(),Px=TypeError;rf.exports=function(s){if(xx(s))return s;throw new Px(kx(s)+" is not a function")}});var Ms=b((UN,sf)=>{"use strict";var Ax=kt(),Rx=As();sf.exports=function(s,e){var t=s[e];return Rx(t)?void 0:Ax(t)}});var nf=b((qN,af)=>{"use strict";var fl=Ze(),ml=ae(),bl=ze(),$x=TypeError;af.exports=function(s,e){var t,i;if(e==="string"&&ml(t=s.toString)&&!bl(i=fl(t,s))||ml(t=s.valueOf)&&!bl(i=fl(t,s))||e!=="string"&&ml(t=s.toString)&&!bl(i=fl(t,s)))return i;throw new $x("Can't convert object to primitive value")}});var bt=b((jN,of)=>{"use strict";of.exports=!0});var cf=b((HN,lf)=>{"use strict";var uf=se(),Mx=Object.defineProperty;lf.exports=function(s,e){try{Mx(uf,s,{value:e,configurable:!0,writable:!0})}catch{uf[s]=e}return e}});var Ls=b((zN,hf)=>{"use strict";var Lx=bt(),Dx=se(),Bx=cf(),df="__core-js_shared__",pf=hf.exports=Dx[df]||Bx(df,{});(pf.versions||(pf.versions=[])).push({version:"3.43.0",mode:Lx?"pure":"global",copyright:"© 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.43.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var gl=b((QN,mf)=>{"use strict";var ff=Ls();mf.exports=function(s,e){return ff[s]||(ff[s]=e||{})}});var mr=b((WN,bf)=>{"use strict";var Cx=ii(),Vx=Object;bf.exports=function(s){return Vx(Cx(s))}});var gt=b((GN,gf)=>{"use strict";var _x=ge(),Ox=mr(),Nx=_x({}.hasOwnProperty);gf.exports=Object.hasOwn||function(e,t){return Nx(Ox(e),t)}});var Sl=b((YN,Sf)=>{"use strict";var Fx=ge(),Ux=0,qx=Math.random(),jx=Fx(1.1.toString);Sf.exports=function(s){return"Symbol("+(s===void 0?"":s)+")_"+jx(++Ux+qx,36)}});var xe=b((KN,yf)=>{"use strict";var Hx=se(),zx=gl(),vf=gt(),Qx=Sl(),Wx=dl(),Gx=pl(),br=Hx.Symbol,vl=zx("wks"),Yx=Gx?br.for||br:br&&br.withoutSetter||Qx;yf.exports=function(s){return vf(vl,s)||(vl[s]=Wx&&vf(br,s)?br[s]:Yx("Symbol."+s)),vl[s]}});var wf=b((XN,Ef)=>{"use strict";var Kx=Ze(),Tf=ze(),If=hl(),Xx=Ms(),Jx=nf(),Zx=xe(),ek=TypeError,tk=Zx("toPrimitive");Ef.exports=function(s,e){if(!Tf(s)||If(s))return s;var t=Xx(s,tk),i;if(t){if(e===void 0&&(e="default"),i=Kx(t,s,e),!Tf(i)||If(i))return i;throw new ek("Can't convert object to primitive value")}return e===void 0&&(e="number"),Jx(s,e)}});var yl=b((JN,xf)=>{"use strict";var ik=wf(),rk=hl();xf.exports=function(s){var e=ik(s,"string");return rk(e)?e:e+""}});var jn=b((ZN,Pf)=>{"use strict";var sk=se(),kf=ze(),Tl=sk.document,ak=kf(Tl)&&kf(Tl.createElement);Pf.exports=function(s){return ak?Tl.createElement(s):{}}});var Il=b((eF,Af)=>{"use strict";var nk=Je(),ok=be(),uk=jn();Af.exports=!nk&&!ok(function(){return Object.defineProperty(uk("div"),"a",{get:function(){return 7}}).a!==7})});var Mf=b($f=>{"use strict";var lk=Je(),ck=Ze(),dk=al(),pk=Ps(),hk=Ri(),fk=yl(),mk=gt(),bk=Il(),Rf=Object.getOwnPropertyDescriptor;$f.f=lk?Rf:function(e,t){if(e=hk(e),t=fk(t),bk)try{return Rf(e,t)}catch{}if(mk(e,t))return pk(!ck(dk.f,e,t),e[t])}});var El=b((iF,Lf)=>{"use strict";var gk=be(),Sk=ae(),vk=/#|\.prototype\./,Ds=function(s,e){var t=Tk[yk(s)];return t===Ek?!0:t===Ik?!1:Sk(e)?gk(e):!!e},yk=Ds.normalize=function(s){return String(s).replace(vk,".").toLowerCase()},Tk=Ds.data={},Ik=Ds.NATIVE="N",Ek=Ds.POLYFILL="P";Lf.exports=Ds});var gr=b((rF,Bf)=>{"use strict";var Df=rl(),wk=kt(),xk=ks(),kk=Df(Df.bind);Bf.exports=function(s,e){return wk(s),e===void 0?s:xk?kk(s,e):function(){return s.apply(e,arguments)}}});var wl=b((sF,Cf)=>{"use strict";var Pk=Je(),Ak=be();Cf.exports=Pk&&Ak(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Pt=b((aF,Vf)=>{"use strict";var Rk=ze(),$k=String,Mk=TypeError;Vf.exports=function(s){if(Rk(s))return s;throw new Mk($k(s)+" is not an object")}});var Li=b(Of=>{"use strict";var Lk=Je(),Dk=Il(),Bk=wl(),Hn=Pt(),_f=yl(),Ck=TypeError,xl=Object.defineProperty,Vk=Object.getOwnPropertyDescriptor,kl="enumerable",Pl="configurable",Al="writable";Of.f=Lk?Bk?function(e,t,i){if(Hn(e),t=_f(t),Hn(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Al in i&&!i[Al]){var r=Vk(e,t);r&&r[Al]&&(e[t]=i.value,i={configurable:Pl in i?i[Pl]:r[Pl],enumerable:kl in i?i[kl]:r[kl],writable:!1})}return xl(e,t,i)}:xl:function(e,t,i){if(Hn(e),t=_f(t),Hn(i),Dk)try{return xl(e,t,i)}catch{}if("get"in i||"set"in i)throw new Ck("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Sr=b((oF,Nf)=>{"use strict";var _k=Je(),Ok=Li(),Nk=Ps();Nf.exports=_k?function(s,e,t){return Ok.f(s,e,Nk(1,t))}:function(s,e,t){return s[e]=t,s}});var ue=b((uF,Uf)=>{"use strict";var Bs=se(),Fk=tl(),Uk=rl(),qk=ae(),jk=Mf().f,Hk=El(),vr=$i(),zk=gr(),yr=Sr(),Ff=gt();Ls();var Qk=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return Fk(s,this,arguments)};return e.prototype=s.prototype,e};Uf.exports=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?Bs:r?Bs[t]:Bs[t]&&Bs[t].prototype,o=i?vr:vr[t]||yr(vr,t,{})[t],u=o.prototype,l,p,c,d,h,f,m,S,g;for(d in e)l=Hk(i?d:t+(r?".":"#")+d,s.forced),p=!l&&n&&Ff(n,d),f=o[d],p&&(s.dontCallGetSet?(g=jk(n,d),m=g&&g.value):m=n[d]),h=p&&m?m:e[d],!(!l&&!a&&typeof f==typeof h)&&(s.bind&&p?S=zk(h,Bs):s.wrap&&p?S=Qk(h):a&&qk(h)?S=Uk(h):S=h,(s.sham||h&&h.sham||f&&f.sham)&&yr(S,"sham",!0),yr(o,d,S),a&&(c=t+"Prototype",Ff(vr,c)||yr(vr,c,{}),yr(vr[c],d,h),s.real&&u&&(l||!u[d])&&yr(u,d,h)))}});var zn=b((lF,jf)=>{"use strict";var Wk=gl(),Gk=Sl(),qf=Wk("keys");jf.exports=function(s){return qf[s]||(qf[s]=Gk(s))}});var zf=b((cF,Hf)=>{"use strict";var Yk=be();Hf.exports=!Yk(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype})});var Qn=b((dF,Wf)=>{"use strict";var Kk=gt(),Xk=ae(),Jk=mr(),Zk=zn(),eP=zf(),Qf=Zk("IE_PROTO"),Rl=Object,tP=Rl.prototype;Wf.exports=eP?Rl.getPrototypeOf:function(s){var e=Jk(s);if(Kk(e,Qf))return e[Qf];var t=e.constructor;return Xk(t)&&e instanceof t?t.prototype:e instanceof Rl?tP:null}});var Yf=b((pF,Gf)=>{"use strict";var iP=Math.ceil,rP=Math.floor;Gf.exports=Math.trunc||function(e){var t=+e;return(t>0?rP:iP)(t)}});var Cs=b((hF,Kf)=>{"use strict";var sP=Yf();Kf.exports=function(s){var e=+s;return e!==e||e===0?0:sP(e)}});var Jf=b((fF,Xf)=>{"use strict";var aP=Cs(),nP=Math.max,oP=Math.min;Xf.exports=function(s,e){var t=aP(s);return t<0?nP(t+e,0):oP(t,e)}});var $l=b((mF,Zf)=>{"use strict";var uP=Cs(),lP=Math.min;Zf.exports=function(s){var e=uP(s);return e>0?lP(e,9007199254740991):0}});var Tr=b((bF,em)=>{"use strict";var cP=$l();em.exports=function(s){return cP(s.length)}});var Ml=b((gF,im)=>{"use strict";var dP=Ri(),pP=Jf(),hP=Tr(),tm=function(s){return function(e,t,i){var r=dP(e),a=hP(r);if(a===0)return!s&&-1;var n=pP(i,a),o;if(s&&t!==t){for(;a>n;)if(o=r[n++],o!==o)return!0}else for(;a>n;n++)if((s||n in r)&&r[n]===t)return s||n||0;return!s&&-1}};im.exports={includes:tm(!0),indexOf:tm(!1)}});var Wn=b((SF,rm)=>{"use strict";rm.exports={}});var nm=b((vF,am)=>{"use strict";var fP=ge(),Ll=gt(),mP=Ri(),bP=Ml().indexOf,gP=Wn(),sm=fP([].push);am.exports=function(s,e){var t=mP(s),i=0,r=[],a;for(a in t)!Ll(gP,a)&&Ll(t,a)&&sm(r,a);for(;e.length>i;)Ll(t,a=e[i++])&&(~bP(r,a)||sm(r,a));return r}});var Dl=b((yF,om)=>{"use strict";om.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Bl=b((TF,um)=>{"use strict";var SP=nm(),vP=Dl();um.exports=Object.keys||function(e){return SP(e,vP)}});var Cl=b((IF,hm)=>{"use strict";var cm=Je(),yP=be(),dm=ge(),TP=Qn(),IP=Bl(),EP=Ri(),wP=al().f,pm=dm(wP),xP=dm([].push),kP=cm&&yP(function(){var s=Object.create(null);return s[2]=2,!pm(s,2)}),lm=function(s){return function(e){for(var t=EP(e),i=IP(t),r=kP&&TP(t)===null,a=i.length,n=0,o=[],u;a>n;)u=i[n++],(!cm||(r?u in t:pm(t,u)))&&xP(o,s?[u,t[u]]:t[u]);return o}};hm.exports={entries:lm(!0),values:lm(!1)}});var fm=b(()=>{"use strict";var PP=ue(),AP=Cl().values;PP({target:"Object",stat:!0},{values:function(e){return AP(e)}})});var bm=b((xF,mm)=>{"use strict";fm();var RP=$i();mm.exports=RP.Object.values});var Sm=b((kF,gm)=>{"use strict";var $P=bm();gm.exports=$P});var Di=b((PF,vm)=>{"use strict";var MP=Sm();vm.exports=MP});var Vs=b((AF,ym)=>{"use strict";ym.exports=function(){}});var Tm=b(()=>{"use strict";var LP=ue(),DP=Ml().includes,BP=be(),CP=Vs(),VP=BP(function(){return!Array(1).includes()});LP({target:"Array",proto:!0,forced:VP},{includes:function(e){return DP(this,e,arguments.length>1?arguments[1]:void 0)}});CP("includes")});var ri=b((MF,Im)=>{"use strict";var _P=Vt();Im.exports=_P});var wm=b((LF,Em)=>{"use strict";Tm();var OP=ri();Em.exports=OP("Array","includes")});var km=b((DF,xm)=>{"use strict";var NP=wm();xm.exports=NP});var ke=b((BF,Pm)=>{"use strict";var FP=km();Pm.exports=FP});var Xm=b(()=>{"use strict";var vA=ue(),yA=Cl().entries;vA({target:"Object",stat:!0},{entries:function(e){return yA(e)}})});var Zm=b((Rq,Jm)=>{"use strict";Xm();var TA=$i();Jm.exports=TA.Object.entries});var tb=b(($q,eb)=>{"use strict";var IA=Zm();eb.exports=IA});var ni=b((Mq,ib)=>{"use strict";var EA=tb();ib.exports=EA});var Vi=b((Lq,rb)=>{"use strict";rb.exports={}});var nb=b((Dq,ab)=>{"use strict";var wA=se(),xA=ae(),sb=wA.WeakMap;ab.exports=xA(sb)&&/native code/.test(String(sb))});var Kl=b((Bq,lb)=>{"use strict";var kA=nb(),ub=se(),PA=ze(),AA=Sr(),Wl=gt(),Gl=Ls(),RA=zn(),$A=Wn(),ob="Object already initialized",Yl=ub.TypeError,MA=ub.WeakMap,so,Us,ao,LA=function(s){return ao(s)?Us(s):so(s,{})},DA=function(s){return function(e){var t;if(!PA(e)||(t=Us(e)).type!==s)throw new Yl("Incompatible receiver, "+s+" required");return t}};kA||Gl.state?(vt=Gl.state||(Gl.state=new MA),vt.get=vt.get,vt.has=vt.has,vt.set=vt.set,so=function(s,e){if(vt.has(s))throw new Yl(ob);return e.facade=s,vt.set(s,e),e},Us=function(s){return vt.get(s)||{}},ao=function(s){return vt.has(s)}):(_i=RA("state"),$A[_i]=!0,so=function(s,e){if(Wl(s,_i))throw new Yl(ob);return e.facade=s,AA(s,_i,e),e},Us=function(s){return Wl(s,_i)?s[_i]:{}},ao=function(s){return Wl(s,_i)});var vt,_i;lb.exports={set:so,get:Us,has:ao,enforce:LA,getterFor:DA}});var Zl=b((Cq,db)=>{"use strict";var Xl=Je(),BA=gt(),cb=Function.prototype,CA=Xl&&Object.getOwnPropertyDescriptor,Jl=BA(cb,"name"),VA=Jl&&function(){}.name==="something",_A=Jl&&(!Xl||Xl&&CA(cb,"name").configurable);db.exports={EXISTS:Jl,PROPER:VA,CONFIGURABLE:_A}});var hb=b(pb=>{"use strict";var OA=Je(),NA=wl(),FA=Li(),UA=Pt(),qA=Ri(),jA=Bl();pb.f=OA&&!NA?Object.defineProperties:function(e,t){UA(e);for(var i=qA(t),r=jA(t),a=r.length,n=0,o;a>n;)FA.f(e,o=r[n++],i[o]);return e}});var ec=b((_q,fb)=>{"use strict";var HA=Vt();fb.exports=HA("document","documentElement")});var sc=b((Oq,Tb)=>{"use strict";var zA=Pt(),QA=hb(),mb=Dl(),WA=Wn(),GA=ec(),YA=jn(),KA=zn(),bb=">",gb="<",ic="prototype",rc="script",vb=KA("IE_PROTO"),tc=function(){},yb=function(s){return gb+rc+bb+s+gb+"/"+rc+bb},Sb=function(s){s.write(yb("")),s.close();var e=s.parentWindow.Object;return s=null,e},XA=function(){var s=YA("iframe"),e="java"+rc+":",t;return s.style.display="none",GA.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(yb("document.F=Object")),t.close(),t.F},no,oo=function(){try{no=new ActiveXObject("htmlfile")}catch{}oo=typeof document<"u"?document.domain&&no?Sb(no):XA():Sb(no);for(var s=mb.length;s--;)delete oo[ic][mb[s]];return oo()};WA[vb]=!0;Tb.exports=Object.create||function(e,t){var i;return e!==null?(tc[ic]=zA(e),i=new tc,tc[ic]=null,i[vb]=e):i=oo(),t===void 0?i:QA.f(i,t)}});var xr=b((Nq,Ib)=>{"use strict";var JA=Sr();Ib.exports=function(s,e,t,i){return i&&i.enumerable?s[e]=t:JA(s,e,t),s}});var uc=b((Fq,xb)=>{"use strict";var ZA=be(),eR=ae(),tR=ze(),iR=sc(),Eb=Qn(),rR=xr(),sR=xe(),aR=bt(),oc=sR("iterator"),wb=!1,Ot,ac,nc;[].keys&&(nc=[].keys(),"next"in nc?(ac=Eb(Eb(nc)),ac!==Object.prototype&&(Ot=ac)):wb=!0);var nR=!tR(Ot)||ZA(function(){var s={};return Ot[oc].call(s)!==s});nR?Ot={}:aR&&(Ot=iR(Ot));eR(Ot[oc])||rR(Ot,oc,function(){return this});xb.exports={IteratorPrototype:Ot,BUGGY_SAFARI_ITERATORS:wb}});var uo=b((Uq,Pb)=>{"use strict";var oR=xe(),uR=oR("toStringTag"),kb={};kb[uR]="z";Pb.exports=String(kb)==="[object z]"});var qs=b((qq,Ab)=>{"use strict";var lR=uo(),cR=ae(),lo=Ai(),dR=xe(),pR=dR("toStringTag"),hR=Object,fR=lo(function(){return arguments}())==="Arguments",mR=function(s,e){try{return s[e]}catch{}};Ab.exports=lR?lo:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=mR(e=hR(s),pR))=="string"?t:fR?lo(e):(i=lo(e))==="Object"&&cR(e.callee)?"Arguments":i}});var $b=b((jq,Rb)=>{"use strict";var bR=uo(),gR=qs();Rb.exports=bR?{}.toString:function(){return"[object "+gR(this)+"]"}});var js=b((Hq,Lb)=>{"use strict";var SR=uo(),vR=Li().f,yR=Sr(),TR=gt(),IR=$b(),ER=xe(),Mb=ER("toStringTag");Lb.exports=function(s,e,t,i){var r=t?s:s&&s.prototype;r&&(TR(r,Mb)||vR(r,Mb,{configurable:!0,value:e}),i&&!SR&&yR(r,"toString",IR))}});var Bb=b((zq,Db)=>{"use strict";var wR=uc().IteratorPrototype,xR=sc(),kR=Ps(),PR=js(),AR=Vi(),RR=function(){return this};Db.exports=function(s,e,t,i){var r=e+" Iterator";return s.prototype=xR(wR,{next:kR(+!i,t)}),PR(s,r,!1,!0),AR[r]=RR,s}});var Vb=b((Qq,Cb)=>{"use strict";var $R=ge(),MR=kt();Cb.exports=function(s,e,t){try{return $R(MR(Object.getOwnPropertyDescriptor(s,e)[t]))}catch{}}});var Ob=b((Wq,_b)=>{"use strict";var LR=ze();_b.exports=function(s){return LR(s)||s===null}});var Fb=b((Gq,Nb)=>{"use strict";var DR=Ob(),BR=String,CR=TypeError;Nb.exports=function(s){if(DR(s))return s;throw new CR("Can't set "+BR(s)+" as a prototype")}});var lc=b((Yq,Ub)=>{"use strict";var VR=Vb(),_R=ze(),OR=ii(),NR=Fb();Ub.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var s=!1,e={},t;try{t=VR(Object.prototype,"__proto__","set"),t(e,[]),s=e instanceof Array}catch{}return function(r,a){return OR(r),NR(a),_R(r)&&(s?t(r,a):r.__proto__=a),r}}():void 0)});var Jb=b((Kq,Xb)=>{"use strict";var FR=ue(),UR=Ze(),co=bt(),Yb=Zl(),qR=ae(),jR=Bb(),qb=Qn(),jb=lc(),HR=js(),zR=Sr(),cc=xr(),QR=xe(),Hb=Vi(),Kb=uc(),WR=Yb.PROPER,GR=Yb.CONFIGURABLE,zb=Kb.IteratorPrototype,po=Kb.BUGGY_SAFARI_ITERATORS,Hs=QR("iterator"),Qb="keys",zs="values",Wb="entries",Gb=function(){return this};Xb.exports=function(s,e,t,i,r,a,n){jR(t,e,i);var o=function(g){if(g===r&&d)return d;if(!po&&g&&g in p)return p[g];switch(g){case Qb:return function(){return new t(this,g)};case zs:return function(){return new t(this,g)};case Wb:return function(){return new t(this,g)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,p=s.prototype,c=p[Hs]||p["@@iterator"]||r&&p[r],d=!po&&c||o(r),h=e==="Array"&&p.entries||c,f,m,S;if(h&&(f=qb(h.call(new s)),f!==Object.prototype&&f.next&&(!co&&qb(f)!==zb&&(jb?jb(f,zb):qR(f[Hs])||cc(f,Hs,Gb)),HR(f,u,!0,!0),co&&(Hb[u]=Gb))),WR&&r===zs&&c&&c.name!==zs&&(!co&&GR?zR(p,"name",zs):(l=!0,d=function(){return UR(c,this)})),r)if(m={values:o(zs),keys:a?d:o(Qb),entries:o(Wb)},n)for(S in m)(po||l||!(S in p))&&cc(p,S,m[S]);else FR({target:e,proto:!0,forced:po||l},m);return(!co||n)&&p[Hs]!==d&&cc(p,Hs,d,{name:r}),Hb[e]=d,m}});var eg=b((Xq,Zb)=>{"use strict";Zb.exports=function(s,e){return{value:s,done:e}}});var pc=b((Jq,ag)=>{"use strict";var YR=Ri(),dc=Vs(),tg=Vi(),rg=Kl(),KR=Li().f,XR=Jb(),ho=eg(),JR=bt(),ZR=Je(),sg="Array Iterator",e$=rg.set,t$=rg.getterFor(sg);ag.exports=XR(Array,"Array",function(s,e){e$(this,{type:sg,target:YR(s),index:0,kind:e})},function(){var s=t$(this),e=s.target,t=s.index++;if(!e||t>=e.length)return s.target=null,ho(void 0,!0);switch(s.kind){case"keys":return ho(t,!1);case"values":return ho(e[t],!1)}return ho([t,e[t]],!1)},"values");var ig=tg.Arguments=tg.Array;dc("keys");dc("values");dc("entries");if(!JR&&ZR&&ig.name!=="values")try{KR(ig,"name",{value:"values"})}catch{}});var og=b((Zq,ng)=>{"use strict";var i$=xe(),r$=Vi(),s$=i$("iterator"),a$=Array.prototype;ng.exports=function(s){return s!==void 0&&(r$.Array===s||a$[s$]===s)}});var hc=b((e1,lg)=>{"use strict";var n$=qs(),ug=Ms(),o$=As(),u$=Vi(),l$=xe(),c$=l$("iterator");lg.exports=function(s){if(!o$(s))return ug(s,c$)||ug(s,"@@iterator")||u$[n$(s)]}});var dg=b((t1,cg)=>{"use strict";var d$=Ze(),p$=kt(),h$=Pt(),f$=$s(),m$=hc(),b$=TypeError;cg.exports=function(s,e){var t=arguments.length<2?m$(s):e;if(p$(t))return h$(d$(t,s));throw new b$(f$(s)+" is not iterable")}});var fg=b((i1,hg)=>{"use strict";var g$=Ze(),pg=Pt(),S$=Ms();hg.exports=function(s,e,t){var i,r;pg(s);try{if(i=S$(s,"return"),!i){if(e==="throw")throw t;return t}i=g$(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return pg(i),t}});var mo=b((r1,Sg)=>{"use strict";var v$=gr(),y$=Ze(),T$=Pt(),I$=$s(),E$=og(),w$=Tr(),mg=Rs(),x$=dg(),k$=hc(),bg=fg(),P$=TypeError,fo=function(s,e){this.stopped=s,this.result=e},gg=fo.prototype;Sg.exports=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=v$(e,i),l,p,c,d,h,f,m,S=function(v){return l&&bg(l,"normal"),new fo(!0,v)},g=function(v){return r?(T$(v),o?u(v[0],v[1],S):u(v[0],v[1])):o?u(v,S):u(v)};if(a)l=s.iterator;else if(n)l=s;else{if(p=k$(s),!p)throw new P$(I$(s)+" is not iterable");if(E$(p)){for(c=0,d=w$(s);d>c;c++)if(h=g(s[c]),h&&mg(gg,h))return h;return new fo(!1)}l=x$(s,p)}for(f=a?s.next:l.next;!(m=y$(f,l)).done;){try{h=g(m.value)}catch(v){bg(l,"throw",v)}if(typeof h=="object"&&h&&mg(gg,h))return h}return new fo(!1)}});var yg=b((s1,vg)=>{"use strict";var A$=Je(),R$=Li(),$$=Ps();vg.exports=function(s,e,t){A$?R$.f(s,e,$$(0,t)):s[e]=t}});var Tg=b(()=>{"use strict";var M$=ue(),L$=mo(),D$=yg();M$({target:"Object",stat:!0},{fromEntries:function(e){var t={};return L$(e,function(i,r){D$(t,i,r)},{AS_ENTRIES:!0}),t}})});var Eg=b((o1,Ig)=>{"use strict";pc();Tg();var B$=$i();Ig.exports=B$.Object.fromEntries});var xg=b((u1,wg)=>{"use strict";wg.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 Pg=b(()=>{"use strict";pc();var C$=xg(),V$=se(),_$=js(),kg=Vi();for(bo in C$)_$(V$[bo],bo),kg[bo]=kg.Array;var bo});var Rg=b((d1,Ag)=>{"use strict";var O$=Eg();Pg();Ag.exports=O$});var fc=b((p1,$g)=>{"use strict";var N$=Rg();$g.exports=N$});var Mg=b(()=>{"use strict"});var mc=b((m1,Lg)=>{"use strict";var Qs=se(),F$=Mi(),U$=Ai(),go=function(s){return F$.slice(0,s.length)===s};Lg.exports=function(){return go("Bun/")?"BUN":go("Cloudflare-Workers")?"CLOUDFLARE":go("Deno/")?"DENO":go("Node.js/")?"NODE":Qs.Bun&&typeof Bun.version=="string"?"BUN":Qs.Deno&&typeof Deno.version=="object"?"DENO":U$(Qs.process)==="process"?"NODE":Qs.window&&Qs.document?"BROWSER":"REST"}()});var So=b((b1,Dg)=>{"use strict";var q$=mc();Dg.exports=q$==="NODE"});var Cg=b((g1,Bg)=>{"use strict";var j$=Li();Bg.exports=function(s,e,t){return j$.f(s,e,t)}});var Og=b((S1,_g)=>{"use strict";var H$=Vt(),z$=Cg(),Q$=xe(),W$=Je(),Vg=Q$("species");_g.exports=function(s){var e=H$(s);W$&&e&&!e[Vg]&&z$(e,Vg,{configurable:!0,get:function(){return this}})}});var Fg=b((v1,Ng)=>{"use strict";var G$=Rs(),Y$=TypeError;Ng.exports=function(s,e){if(G$(e,s))return s;throw new Y$("Incorrect invocation")}});var gc=b((y1,Ug)=>{"use strict";var K$=ge(),X$=ae(),bc=Ls(),J$=K$(Function.toString);X$(bc.inspectSource)||(bc.inspectSource=function(s){return J$(s)});Ug.exports=bc.inspectSource});var vc=b((T1,Qg)=>{"use strict";var Z$=ge(),eM=be(),qg=ae(),tM=qs(),iM=Vt(),rM=gc(),jg=function(){},Hg=iM("Reflect","construct"),Sc=/^\s*(?:class|function)\b/,sM=Z$(Sc.exec),aM=!Sc.test(jg),Ws=function(e){if(!qg(e))return!1;try{return Hg(jg,[],e),!0}catch{return!1}},zg=function(e){if(!qg(e))return!1;switch(tM(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return aM||!!sM(Sc,rM(e))}catch{return!0}};zg.sham=!0;Qg.exports=!Hg||eM(function(){var s;return Ws(Ws.call)||!Ws(Object)||!Ws(function(){s=!0})||s})?zg:Ws});var Gg=b((I1,Wg)=>{"use strict";var nM=vc(),oM=$s(),uM=TypeError;Wg.exports=function(s){if(nM(s))return s;throw new uM(oM(s)+" is not a constructor")}});var yc=b((E1,Kg)=>{"use strict";var Yg=Pt(),lM=Gg(),cM=As(),dM=xe(),pM=dM("species");Kg.exports=function(s,e){var t=Yg(s).constructor,i;return t===void 0||cM(i=Yg(t)[pM])?e:lM(i)}});var Jg=b((w1,Xg)=>{"use strict";var hM=ge();Xg.exports=hM([].slice)});var eS=b((x1,Zg)=>{"use strict";var fM=TypeError;Zg.exports=function(s,e){if(s<e)throw new fM("Not enough arguments");return s}});var Tc=b((k1,tS)=>{"use strict";var mM=Mi();tS.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(mM)});var $c=b((P1,cS)=>{"use strict";var et=se(),bM=tl(),gM=gr(),iS=ae(),SM=gt(),lS=be(),rS=ec(),vM=Jg(),sS=jn(),yM=eS(),TM=Tc(),IM=So(),Pc=et.setImmediate,Ac=et.clearImmediate,EM=et.process,Ic=et.Dispatch,wM=et.Function,aS=et.MessageChannel,xM=et.String,Ec=0,Gs={},nS="onreadystatechange",Ys,Oi,wc,xc;lS(function(){Ys=et.location});var Rc=function(s){if(SM(Gs,s)){var e=Gs[s];delete Gs[s],e()}},kc=function(s){return function(){Rc(s)}},oS=function(s){Rc(s.data)},uS=function(s){et.postMessage(xM(s),Ys.protocol+"//"+Ys.host)};(!Pc||!Ac)&&(Pc=function(e){yM(arguments.length,1);var t=iS(e)?e:wM(e),i=vM(arguments,1);return Gs[++Ec]=function(){bM(t,void 0,i)},Oi(Ec),Ec},Ac=function(e){delete Gs[e]},IM?Oi=function(s){EM.nextTick(kc(s))}:Ic&&Ic.now?Oi=function(s){Ic.now(kc(s))}:aS&&!TM?(wc=new aS,xc=wc.port2,wc.port1.onmessage=oS,Oi=gM(xc.postMessage,xc)):et.addEventListener&&iS(et.postMessage)&&!et.importScripts&&Ys&&Ys.protocol!=="file:"&&!lS(uS)?(Oi=uS,et.addEventListener("message",oS,!1)):nS in sS("script")?Oi=function(s){rS.appendChild(sS("script"))[nS]=function(){rS.removeChild(this),Rc(s)}}:Oi=function(s){setTimeout(kc(s),0)});cS.exports={set:Pc,clear:Ac}});var hS=b((A1,pS)=>{"use strict";var dS=se(),kM=Je(),PM=Object.getOwnPropertyDescriptor;pS.exports=function(s){if(!kM)return dS[s];var e=PM(dS,s);return e&&e.value}});var Mc=b((R1,mS)=>{"use strict";var fS=function(){this.head=null,this.tail=null};fS.prototype={add:function(s){var e={item:s,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var s=this.head;if(s){var e=this.head=s.next;return e===null&&(this.tail=null),s.item}}};mS.exports=fS});var gS=b(($1,bS)=>{"use strict";var AM=Mi();bS.exports=/ipad|iphone|ipod/i.test(AM)&&typeof Pebble<"u"});var vS=b((M1,SS)=>{"use strict";var RM=Mi();SS.exports=/web0s(?!.*chrome)/i.test(RM)});var kS=b((L1,xS)=>{"use strict";var Pr=se(),$M=hS(),yS=gr(),Lc=$c().set,MM=Mc(),LM=Tc(),DM=gS(),BM=vS(),Dc=So(),TS=Pr.MutationObserver||Pr.WebKitMutationObserver,IS=Pr.document,ES=Pr.process,vo=Pr.Promise,Vc=$M("queueMicrotask"),kr,Bc,Cc,yo,wS;Vc||(Ks=new MM,Xs=function(){var s,e;for(Dc&&(s=ES.domain)&&s.exit();e=Ks.get();)try{e()}catch(t){throw Ks.head&&kr(),t}s&&s.enter()},!LM&&!Dc&&!BM&&TS&&IS?(Bc=!0,Cc=IS.createTextNode(""),new TS(Xs).observe(Cc,{characterData:!0}),kr=function(){Cc.data=Bc=!Bc}):!DM&&vo&&vo.resolve?(yo=vo.resolve(void 0),yo.constructor=vo,wS=yS(yo.then,yo),kr=function(){wS(Xs)}):Dc?kr=function(){ES.nextTick(Xs)}:(Lc=yS(Lc,Pr),kr=function(){Lc(Xs)}),Vc=function(s){Ks.head||kr(),Ks.add(s)});var Ks,Xs;xS.exports=Vc});var AS=b((D1,PS)=>{"use strict";PS.exports=function(s,e){try{arguments.length===1?console.error(s):console.error(s,e)}catch{}}});var To=b((B1,RS)=>{"use strict";RS.exports=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}}});var Ni=b((C1,$S)=>{"use strict";var CM=se();$S.exports=CM.Promise});var Ar=b((V1,BS)=>{"use strict";var VM=se(),Js=Ni(),_M=ae(),OM=El(),NM=gc(),FM=xe(),MS=mc(),UM=bt(),_c=cl(),LS=Js&&Js.prototype,qM=FM("species"),Oc=!1,DS=_M(VM.PromiseRejectionEvent),jM=OM("Promise",function(){var s=NM(Js),e=s!==String(Js);if(!e&&_c===66||UM&&!(LS.catch&&LS.finally))return!0;if(!_c||_c<51||!/native code/.test(s)){var t=new Js(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[qM]=i,Oc=t.then(function(){})instanceof i,!Oc)return!0}return!e&&(MS==="BROWSER"||MS==="DENO")&&!DS});BS.exports={CONSTRUCTOR:jM,REJECTION_EVENT:DS,SUBCLASSING:Oc}});var Rr=b((_1,VS)=>{"use strict";var CS=kt(),HM=TypeError,zM=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw new HM("Bad Promise constructor");e=i,t=r}),this.resolve=CS(e),this.reject=CS(t)};VS.exports.f=function(s){return new zM(s)}});var iv=b(()=>{"use strict";var QM=ue(),WM=bt(),xo=So(),oi=se(),GM=$i(),Dr=Ze(),_S=xr(),OS=lc(),YM=js(),KM=Og(),XM=kt(),wo=ae(),JM=ze(),ZM=Fg(),eL=yc(),jS=$c().set,jc=kS(),tL=AS(),iL=To(),rL=Mc(),HS=Kl(),ko=Ni(),Hc=Ar(),zS=Rr(),Po="Promise",QS=Hc.CONSTRUCTOR,sL=Hc.REJECTION_EVENT,aL=Hc.SUBCLASSING,Nc=HS.getterFor(Po),nL=HS.set,$r=ko&&ko.prototype,Fi=ko,Io=$r,WS=oi.TypeError,Fc=oi.document,zc=oi.process,Uc=zS.f,oL=Uc,uL=!!(Fc&&Fc.createEvent&&oi.dispatchEvent),GS="unhandledrejection",lL="rejectionhandled",NS=0,YS=1,cL=2,Qc=1,KS=2,Eo,FS,XS,US,JS=function(s){var e;return JM(s)&&wo(e=s.then)?e:!1},ZS=function(s,e){var t=e.value,i=e.state===YS,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,l,p;try{r?(i||(e.rejection===KS&&pL(e),e.rejection=Qc),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),p=!0)),u===s.promise?n(new WS("Promise-chain cycle")):(l=JS(u))?Dr(l,u,a,n):a(u)):n(t)}catch(c){o&&!p&&o.exit(),n(c)}},ev=function(s,e){s.notified||(s.notified=!0,jc(function(){for(var t=s.reactions,i;i=t.get();)ZS(i,s);s.notified=!1,e&&!s.rejection&&dL(s)}))},tv=function(s,e,t){var i,r;uL?(i=Fc.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),oi.dispatchEvent(i)):i={promise:e,reason:t},!sL&&(r=oi["on"+s])?r(i):s===GS&&tL("Unhandled promise rejection",t)},dL=function(s){Dr(jS,oi,function(){var e=s.facade,t=s.value,i=qS(s),r;if(i&&(r=iL(function(){xo?zc.emit("unhandledRejection",t,e):tv(GS,e,t)}),s.rejection=xo||qS(s)?KS:Qc,r.error))throw r.value})},qS=function(s){return s.rejection!==Qc&&!s.parent},pL=function(s){Dr(jS,oi,function(){var e=s.facade;xo?zc.emit("rejectionHandled",e):tv(lL,e,s.value)})},Mr=function(s,e,t){return function(i){s(e,i,t)}},Lr=function(s,e,t){s.done||(s.done=!0,t&&(s=t),s.value=e,s.state=cL,ev(s,!0))},qc=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw new WS("Promise can't be resolved itself");var i=JS(e);i?jc(function(){var r={done:!1};try{Dr(i,e,Mr(qc,r,s),Mr(Lr,r,s))}catch(a){Lr(r,a,s)}}):(s.value=e,s.state=YS,ev(s,!1))}catch(r){Lr({done:!1},r,s)}}};if(QS&&(Fi=function(e){ZM(this,Io),XM(e),Dr(Eo,this);var t=Nc(this);try{e(Mr(qc,t),Mr(Lr,t))}catch(i){Lr(t,i)}},Io=Fi.prototype,Eo=function(e){nL(this,{type:Po,done:!1,notified:!1,parent:!1,reactions:new rL,rejection:!1,state:NS,value:null})},Eo.prototype=_S(Io,"then",function(e,t){var i=Nc(this),r=Uc(eL(this,Fi));return i.parent=!0,r.ok=wo(e)?e:!0,r.fail=wo(t)&&t,r.domain=xo?zc.domain:void 0,i.state===NS?i.reactions.add(r):jc(function(){ZS(r,i)}),r.promise}),FS=function(){var s=new Eo,e=Nc(s);this.promise=s,this.resolve=Mr(qc,e),this.reject=Mr(Lr,e)},zS.f=Uc=function(s){return s===Fi||s===XS?new FS(s):oL(s)},!WM&&wo(ko)&&$r!==Object.prototype)){US=$r.then,aL||_S($r,"then",function(e,t){var i=this;return new Fi(function(r,a){Dr(US,i,r,a)}).then(e,t)},{unsafe:!0});try{delete $r.constructor}catch{}OS&&OS($r,Io)}QM({global:!0,constructor:!0,wrap:!0,forced:QS},{Promise:Fi});XS=GM.Promise;YM(Fi,Po,!1,!0);KM(Po)});var ov=b((F1,nv)=>{"use strict";var hL=xe(),sv=hL("iterator"),av=!1;try{rv=0,Wc={next:function(){return{done:!!rv++}},return:function(){av=!0}},Wc[sv]=function(){return this},Array.from(Wc,function(){throw 2})}catch{}var rv,Wc;nv.exports=function(s,e){try{if(!e&&!av)return!1}catch{return!1}var t=!1;try{var i={};i[sv]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch{}return t}});var Gc=b((U1,uv)=>{"use strict";var fL=Ni(),mL=ov(),bL=Ar().CONSTRUCTOR;uv.exports=bL||!mL(function(s){fL.all(s).then(void 0,function(){})})});var lv=b(()=>{"use strict";var gL=ue(),SL=Ze(),vL=kt(),yL=Rr(),TL=To(),IL=mo(),EL=Gc();gL({target:"Promise",stat:!0,forced:EL},{all:function(e){var t=this,i=yL.f(t),r=i.resolve,a=i.reject,n=TL(function(){var o=vL(t.resolve),u=[],l=0,p=1;IL(e,function(c){var d=l++,h=!1;p++,SL(o,t,c).then(function(f){h||(h=!0,u[d]=f,--p||r(u))},a)}),--p||r(u)});return n.error&&a(n.value),i.promise}})});var dv=b(()=>{"use strict";var wL=ue(),xL=bt(),kL=Ar().CONSTRUCTOR,Kc=Ni(),PL=Vt(),AL=ae(),RL=xr(),cv=Kc&&Kc.prototype;wL({target:"Promise",proto:!0,forced:kL,real:!0},{catch:function(s){return this.then(void 0,s)}});!xL&&AL(Kc)&&(Yc=PL("Promise").prototype.catch,cv.catch!==Yc&&RL(cv,"catch",Yc,{unsafe:!0}));var Yc});var pv=b(()=>{"use strict";var $L=ue(),ML=Ze(),LL=kt(),DL=Rr(),BL=To(),CL=mo(),VL=Gc();$L({target:"Promise",stat:!0,forced:VL},{race:function(e){var t=this,i=DL.f(t),r=i.reject,a=BL(function(){var n=LL(t.resolve);CL(e,function(o){ML(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}})});var hv=b(()=>{"use strict";var _L=ue(),OL=Rr(),NL=Ar().CONSTRUCTOR;_L({target:"Promise",stat:!0,forced:NL},{reject:function(e){var t=OL.f(this),i=t.reject;return i(e),t.promise}})});var Xc=b((K1,fv)=>{"use strict";var FL=Pt(),UL=ze(),qL=Rr();fv.exports=function(s,e){if(FL(s),UL(e)&&e.constructor===s)return e;var t=qL.f(s),i=t.resolve;return i(e),t.promise}});var gv=b(()=>{"use strict";var jL=ue(),HL=Vt(),mv=bt(),zL=Ni(),bv=Ar().CONSTRUCTOR,QL=Xc(),WL=HL("Promise"),GL=mv&&!bv;jL({target:"Promise",stat:!0,forced:mv||bv},{resolve:function(e){return QL(GL&&this===WL?zL:this,e)}})});var Sv=b(()=>{"use strict";iv();lv();dv();pv();hv();gv()});var Iv=b(()=>{"use strict";var YL=ue(),KL=bt(),Ao=Ni(),XL=be(),yv=Vt(),Tv=ae(),JL=yc(),vv=Xc(),ZL=xr(),Zc=Ao&&Ao.prototype,eD=!!Ao&&XL(function(){Zc.finally.call({then:function(){}},function(){})});YL({target:"Promise",proto:!0,real:!0,forced:eD},{finally:function(s){var e=JL(this,yv("Promise")),t=Tv(s);return this.then(t?function(i){return vv(e,s()).then(function(){return i})}:s,t?function(i){return vv(e,s()).then(function(){throw i})}:s)}});!KL&&Tv(Ao)&&(Jc=yv("Promise").prototype.finally,Zc.finally!==Jc&&ZL(Zc,"finally",Jc,{unsafe:!0}));var Jc});var wv=b((rj,Ev)=>{"use strict";Mg();Sv();Iv();var tD=ri();Ev.exports=tD("Promise","finally")});var kv=b((sj,xv)=>{"use strict";var iD=wv();xv.exports=iD});var Ro=b((aj,Pv)=>{"use strict";var rD=kv();Pv.exports=rD});var Qv=b(()=>{"use strict";var MD=ue(),LD=mr(),DD=Tr(),BD=Cs(),CD=Vs();MD({target:"Array",proto:!0},{at:function(e){var t=LD(this),i=DD(t),r=BD(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});CD("at")});var Gv=b((nH,Wv)=>{"use strict";Qv();var VD=ri();Wv.exports=VD("Array","at")});var Kv=b((oH,Yv)=>{"use strict";var _D=Gv();Yv.exports=_D});var Ge=b((uH,Xv)=>{"use strict";var OD=Kv();Xv.exports=OD});var Ld=b((TW,Hy)=>{"use strict";var UB=Ai();Hy.exports=Array.isArray||function(e){return UB(e)==="Array"}});var Qy=b((IW,zy)=>{"use strict";var qB=TypeError,jB=9007199254740991;zy.exports=function(s){if(s>jB)throw qB("Maximum allowed index exceeded");return s}});var Yy=b((EW,Gy)=>{"use strict";var HB=Ld(),zB=Tr(),QB=Qy(),WB=gr(),Wy=function(s,e,t,i,r,a,n,o){for(var u=r,l=0,p=n?WB(n,o):!1,c,d;l<i;)l in t&&(c=p?p(t[l],l,e):t[l],a>0&&HB(c)?(d=zB(c),u=Wy(s,e,c,d,u,a-1)-1):(QB(u+1),s[u]=c),u++),l++;return u};Gy.exports=Wy});var Zy=b((wW,Jy)=>{"use strict";var Ky=Ld(),GB=vc(),YB=ze(),KB=xe(),XB=KB("species"),Xy=Array;Jy.exports=function(s){var e;return Ky(s)&&(e=s.constructor,GB(e)&&(e===Xy||Ky(e.prototype))?e=void 0:YB(e)&&(e=e[XB],e===null&&(e=void 0))),e===void 0?Xy:e}});var tT=b((xW,eT)=>{"use strict";var JB=Zy();eT.exports=function(s,e){return new(JB(s))(e===0?0:e)}});var iT=b(()=>{"use strict";var ZB=ue(),eC=Yy(),tC=kt(),iC=mr(),rC=Tr(),sC=tT();ZB({target:"Array",proto:!0},{flatMap:function(e){var t=iC(this),i=rC(t),r;return tC(e),r=sC(t,0),r.length=eC(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var rT=b(()=>{"use strict";var aC=Vs();aC("flatMap")});var aT=b(($W,sT)=>{"use strict";iT();rT();var nC=ri();sT.exports=nC("Array","flatMap")});var oT=b((MW,nT)=>{"use strict";var oC=aT();nT.exports=oC});var Wi=b((LW,uT)=>{"use strict";var uC=oT();uT.exports=uC});var fa=b((WW,pT)=>{"use strict";var cC=qs(),dC=String;pT.exports=function(s){if(cC(s)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return dC(s)}});var Bd=b((GW,hT)=>{"use strict";hT.exports=`
7
- \v\f\r                 \u2028\u2029\uFEFF`});var bT=b((YW,mT)=>{"use strict";var pC=ge(),hC=ii(),fC=fa(),Vd=Bd(),fT=pC("".replace),mC=RegExp("^["+Vd+"]+"),bC=RegExp("(^|[^"+Vd+"])["+Vd+"]+$"),Cd=function(s){return function(e){var t=fC(hC(e));return s&1&&(t=fT(t,mC,"")),s&2&&(t=fT(t,bC,"$1")),t}};mT.exports={start:Cd(1),end:Cd(2),trim:Cd(3)}});var yT=b((KW,vT)=>{"use strict";var gC=Zl().PROPER,SC=be(),gT=Bd(),ST="​…᠎";vT.exports=function(s){return SC(function(){return!!gT[s]()||ST[s]()!==ST||gC&&gT[s].name!==s})}});var _d=b((XW,TT)=>{"use strict";var vC=bT().start,yC=yT();TT.exports=yC("trimStart")?function(){return vC(this)}:"".trimStart});var ET=b(()=>{"use strict";var TC=ue(),IT=_d();TC({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==IT},{trimLeft:IT})});var xT=b(()=>{"use strict";ET();var IC=ue(),wT=_d();IC({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==wT},{trimStart:wT})});var PT=b((i2,kT)=>{"use strict";xT();var EC=ri();kT.exports=EC("String","trimLeft")});var RT=b((r2,AT)=>{"use strict";var wC=PT();AT.exports=wC});var MT=b((s2,$T)=>{"use strict";var xC=RT();$T.exports=xC});var CT=b(()=>{"use strict"});var VT=b(()=>{"use strict"});var OT=b((U2,_T)=>{"use strict";var AC=ze(),RC=Ai(),$C=xe(),MC=$C("match");_T.exports=function(s){var e;return AC(s)&&((e=s[MC])!==void 0?!!e:RC(s)==="RegExp")}});var UT=b((q2,FT)=>{"use strict";var LC=se(),DC=be(),NT=LC.RegExp,BC=!DC(function(){var s=!0;try{NT(".","d")}catch{s=!1}var e={},t="",i=s?"dgimsy":"gimsy",r=function(u,l){Object.defineProperty(e,u,{get:function(){return t+=l,!0}})},a={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};s&&(a.hasIndices="d");for(var n in a)r(n,a[n]);var o=Object.getOwnPropertyDescriptor(NT.prototype,"flags").get.call(e);return o!==i||t!==i});FT.exports={correct:BC}});var jT=b((j2,qT)=>{"use strict";var CC=Pt();qT.exports=function(){var s=CC(this),e="";return s.hasIndices&&(e+="d"),s.global&&(e+="g"),s.ignoreCase&&(e+="i"),s.multiline&&(e+="m"),s.dotAll&&(e+="s"),s.unicode&&(e+="u"),s.unicodeSets&&(e+="v"),s.sticky&&(e+="y"),e}});var QT=b((H2,zT)=>{"use strict";var VC=Ze(),_C=gt(),OC=Rs(),HT=UT(),NC=jT(),FC=RegExp.prototype;zT.exports=HT.correct?function(s){return s.flags}:function(s){return!HT.correct&&OC(FC,s)&&!_C(s,"flags")?VC(NC,s):s.flags}});var GT=b((z2,WT)=>{"use strict";var qd=ge(),UC=mr(),qC=Math.floor,Fd=qd("".charAt),jC=qd("".replace),Ud=qd("".slice),HC=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,zC=/\$([$&'`]|\d{1,2})/g;WT.exports=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=zC;return r!==void 0&&(r=UC(r),u=HC),jC(a,u,function(l,p){var c;switch(Fd(p,0)){case"$":return"$";case"&":return s;case"`":return Ud(e,0,t);case"'":return Ud(e,n);case"<":c=r[Ud(p,1,-1)];break;default:var d=+p;if(d===0)return l;if(d>o){var h=qC(d/10);return h===0?l:h<=o?i[h-1]===void 0?Fd(p,1):i[h-1]+Fd(p,1):l}c=i[d-1]}return c===void 0?"":c})}});var XT=b(()=>{"use strict";var QC=ue(),WC=Ze(),Hd=ge(),YT=ii(),GC=ae(),YC=ze(),KC=OT(),Kr=fa(),XC=Ms(),JC=QT(),ZC=GT(),eV=xe(),tV=bt(),iV=eV("replace"),rV=TypeError,jd=Hd("".indexOf),sV=Hd("".replace),KT=Hd("".slice),aV=Math.max;QC({target:"String",proto:!0},{replaceAll:function(e,t){var i=YT(this),r,a,n,o,u,l,p,c,d,h,f=0,m="";if(YC(e)){if(r=KC(e),r&&(a=Kr(YT(JC(e))),!~jd(a,"g")))throw new rV("`.replaceAll` does not allow non-global regexes");if(n=XC(e,iV),n)return WC(n,e,i,t);if(tV&&r)return sV(Kr(i),e,t)}for(o=Kr(i),u=Kr(e),l=GC(t),l||(t=Kr(t)),p=u.length,c=aV(1,p),d=jd(o,u);d!==-1;)h=l?Kr(t(u,d,o)):ZC(u,o,d,[],void 0,t),m+=KT(o,f,d)+h,f=d+p,d=d+c>o.length?-1:jd(o,u,d+c);return f<o.length&&(m+=KT(o,f)),m}})});var ZT=b((G2,JT)=>{"use strict";CT();VT();XT();var nV=ri();JT.exports=nV("String","replaceAll")});var tI=b((Y2,eI)=>{"use strict";var oV=ZT();eI.exports=oV});var rI=b((K2,iI)=>{"use strict";var uV=tI();iI.exports=uV});var aI=b((X2,sI)=>{"use strict";var lV=Cs(),cV=fa(),dV=ii(),pV=RangeError;sI.exports=function(e){var t=cV(dV(this)),i="",r=lV(e);if(r<0||r===1/0)throw new pV("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var cI=b((J2,lI)=>{"use strict";var uI=ge(),hV=$l(),nI=fa(),fV=aI(),mV=ii(),bV=uI(fV),gV=uI("".slice),SV=Math.ceil,oI=function(s){return function(e,t,i){var r=nI(mV(e)),a=hV(t),n=r.length,o=i===void 0?" ":nI(i),u,l;return a<=n||o===""?r:(u=a-n,l=bV(o,SV(u/o.length)),l.length>u&&(l=gV(l,0,u)),s?r+l:l+r)}};lI.exports={start:oI(!1),end:oI(!0)}});var pI=b((Z2,dI)=>{"use strict";var vV=Mi();dI.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(vV)});var hI=b(()=>{"use strict";var yV=ue(),TV=cI().start,IV=pI();yV({target:"String",proto:!0,forced:IV},{padStart:function(e){return TV(this,e,arguments.length>1?arguments[1]:void 0)}})});var mI=b((iG,fI)=>{"use strict";hI();var EV=ri();fI.exports=EV("String","padStart")});var gI=b((rG,bI)=>{"use strict";var wV=mI();bI.exports=wV});var vI=b((sG,SI)=>{"use strict";var xV=gI();SI.exports=xV});var dh="2.0.149-dev.a444d83a.0";var we=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(we||{}),Ct=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_FMP4="HLS_FMP4",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(Ct||{});var ws=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(ws||{}),Ju=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Ju||{});var Zu=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Zu||{}),Fn=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Fn||{});var uh=D(Di(),1),Vw=D(ke(),1);import{assertNever as Dm,assertNonNullable as UP,isNonNullable as Gn,ValueSubject as Vl,Subject as qP,Subscription as jP,merge as HP,observableFrom as zP,fromEvent as Rm,map as $m,tap as Mm,filterChanged as QP,isNullable as _l,ErrorCategory as Lm}from"@vkontakte/videoplayer-shared/es2024";var Am=s=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var Yn=class{constructor(e){this.connection$=new Vl(void 0);this.castState$=new Vl("NOT_AVAILABLE");this.errorEvent$=new qP;this.realCastState$=new Vl("NOT_AVAILABLE");this.subscription=new jP;this.isDestroyed=!1;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=Gn(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=a=>{delete window.__onGCastApiAvailable,a&&!this.isDestroyed&&this.initializeCastApi()},r||Am("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Lm.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(){Gn(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();_l(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();_l(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(Rm(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{switch(r.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 Dm(r.sessionState)}})).add(HP(Rm(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Mm(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),$m(r=>r.castState)),zP([i.getCastState()])).pipe(QP(),$m(WP),Mm(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let a=r==="CONNECTED",n=Gn(this.connection$.getValue());if(a&&!n){let o=i.getCurrentSession();UP(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;(_l(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!a&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?Gn(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}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(r){this.errorEvent$.next({id:"ChromecastInitializer",category:Lm.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},WP=s=>{switch(s){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 Dm(s)}};import{assertNonNullable as Fl,combine as Ul,debounce as ql,ErrorCategory as oA,filter as Er,filterChanged as zm,isNonNullable as jl,isNullable as Qm,map as uA,Subscription as lA,ValueSubject as Hl}from"@vkontakte/videoplayer-shared/es2024";import{assertNever as GP,assertNonNullable as Bi,ErrorCategory as YP,getHighestQuality as KP,isNonNullable as Cm}from"@vkontakte/videoplayer-shared/es2024";import{assertNever as Bm}from"@vkontakte/videoplayer-shared/es2024";var ne=(s,e=0,t=0)=>{switch(t){case 0:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return s;let i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(s);return!i.searchParams.get("offset_p")&&e===0?s:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:Bm(t)}return s},si=(s,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(s);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(s);return Number(t.searchParams.get("offset_p")??0)}default:Bm(e)}};var Xn=s=>{let{source:e,format:t,meta:i,output:r}=s,a,n,o;switch(t){case"MPEG":{let c=e[t];Bi(c);let d=KP(Object.keys(c));Bi(d);let h=c[d];Bi(h),a=h,n="video/mp4",o=Kn();break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let c=e[t];Bi(c),a=c.url,n="application/x-mpegurl",o=Kn();break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=e[t];Bi(c),a=c.url,n="application/dash+xml",o=Kn();break}case"DASH_LIVE_CMAF":{let c=e[t];Bi(c),a=c.url,n="application/dash+xml",o=Vm();break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=e[t];Bi(c),a=ne(c.url),n="application/x-mpegurl",o=Vm();break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw r.error$.next({id:"ChromecastProvider.createMediaInfo()",category:YP.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${t} is no longer supported`);default:return GP(t)}let u=XP(i.videoId??a,n);u.contentUrl=a,u.streamType=o,u.metadata=JP();let{title:l,subtitle:p}=i;return Cm(l)&&(u.metadata.title=l),Cm(p)&&(u.metadata.subtitle=p),u};function Kn(){return chrome.cast?.media?.StreamType?.BUFFERED??"BUFFERED"}function Vm(){return chrome.cast?.media?.StreamType?.LIVE??"LIVE"}function XP(s,e){return chrome.cast?.media?.MediaInfo?new chrome.cast.media.MediaInfo(s,e):{contentId:s,contentType:e,metadata:{title:"",subtitle:""},streamType:Kn()}}function JP(){return chrome.cast?.media?.GenericMediaMetadata?new chrome.cast.media.GenericMediaMetadata:{images:[],metadataType:0,releaseDate:"",subtitle:"",title:"",releaseYear:1970,type:0}}var P=(s,e,t=!1)=>{let i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};var Jn=class{constructor(e){this.interval=0;this.params=e}start(e=0){clearInterval(this.interval),this.startVideoPosition=e,this.startTs=Date.now(),this.interval=window.setInterval(()=>{let t=(Date.now()-this.startTs)/1e3,i=this.startVideoPosition+t;this.params.output.position$.next(i)},1e3)}pause(){clearInterval(this.interval)}destroy(){clearInterval(this.interval)}};import{assertNever as Hm}from"@vkontakte/videoplayer-shared/es2024";var _m=D(ke(),1);var Zn=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isChromiumBased(){return(0,_m.default)(["Chrome","Chromium","Opera","Yandex","Edge","SamsungBrowser"],this.current)}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,a=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||l||r||a||o||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],a=parseInt(r,10);if(!isNaN(a))return this._current_version=a,a}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var Om=D(ke(),1);var Ci=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var eo=class{constructor(e){this._highEntropyValues={};this._os={name:"Unknown",version:"Unknown",full:"Unknown"};this._details={vendor:"Unknown",model:"Unknown"};this._displayChecker=e}get current(){return this._current}get os(){return this._os}get details(){return this._details}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||this.os.name.toLowerCase().includes("ios")||(0,Om.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.os.name.toLowerCase().includes("mac")||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.os.name.toLowerCase().includes("android")||this.current==="Android"}get isWindows(){return this.os.name.toLowerCase().includes("windows")}get isLinux(){return this.os.name.toLowerCase().includes("linux")&&!this.isAndroid}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=Ci()}catch(t){console.error(t)}this.detectDevice(e),this.detectOS(e),this.detectDeviceDetails(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e?.getHighEntropyValues){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t,t.platform&&(this._os.name=this.normalizeOSName(t.platform),t.platformVersion&&(this._os.version=this.normalizeOSVersion(t.platformVersion),this._os.full=`${this._os.name} ${this._os.version}`)),t.model&&(this._details.model=t.model)}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,a=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||a||o||n||"Desktop"}catch(t){console.error(t)}}detectOS(e){try{let t=[[/(windows nt) (6\.[23]); arm/i,["Windows RT"]],[/(windows (?:phone|mobile|iot))(?: os)?[/ ]?([\d.]*( se)?)/i,["Windows Mobile",2]],[/(windows)[/ ](1[01]|2000|3\.1|7|8(\.1)?|9[58]|me|server 20\d\d( r2)?|vista|xp)/i,[1,2]],[/windows nt ?([\d.)]*)(?!.+xbox)/i,[2]],[/\bwin(?=3| ?9|n)(?:nt| 9x )?([\d.;]*)/i,[1]],[/(mac os x) ?([\w. ]*)/i,["macOS",2]],[/(macintosh|mac_powerpc\b)(?!.+(haiku|morphos))/i,["macOS"]],[/(?:ios;fbsv|ios(?=.+ip(?:ad|hone))|ip(?:ad|hone)(?: |.+i(?:pad)?)os)[/ ]([\w.]+)/i,["iOS",1]],[/cfnetwork\/.+darwin/i,["iOS"]],[/(android|harmonyos)[/ ]?([\d.]*)/i,[1,2]],[/(linux|ubuntu|debian|fedora|red hat|centos)[-/ ]?([\w.]*)/i,[1,2]],[/(cros) \w+(?:\)| ([\w.]+)\b)/i,["Chrome OS",2]]];for(let[i,r]of t){let a=e.match(i);if(a){let n=r[0],o=r[1],u=typeof n=="number"?a[n]:n,l=typeof o=="number"?a[o]:o;u.toLowerCase().includes("mac")?u="macOS":u.toLowerCase().includes("windows")?u="Windows":u.toLowerCase().includes("android")?u="Android":(u.toLowerCase().includes("ios")||u.toLowerCase().includes("iphone")||u.toLowerCase().includes("ipad"))&&(u="iOS"),l&&(l=l.replace(/_/g,".")),this._os={name:u,version:l||"Unknown",full:l?`${u} ${l}`:u};break}}this._os.name==="Unknown"&&(e.includes("Mac")?this._os={name:"macOS",version:"Unknown",full:"macOS"}:e.includes("Win")?this._os={name:"Windows",version:"Unknown",full:"Windows"}:e.includes("Linux")&&(this._os={name:"Linux",version:"Unknown",full:"Linux"}))}catch(t){console.error("OS detection error:",t)}}detectDeviceDetails(e){try{let t=[[/(ip(hone|od|ad))/i,["Apple",1]],[/(macintosh)/i,["Apple","Macintosh"]],[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i,["Samsung",1]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,["Samsung",1]],[/samsung[- ]((?!sm-[lr]|browser)[-\w]+)/i,["Samsung",1]],[/sec-(sgh\w+)/i,["Samsung",1]],[/(?:huawei) ?([-\w ]+)[;)]/i,["Huawei",1]],[/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][\dc][adnt]?)\b(?!.+d\/s)/i,["Huawei",1]],[/\b((?:ag[rs][2356]?k?|bah[234]?|bg[2o]|bt[kv]|cmr|cpn|db[ry]2?|jdn2|got|kob2?k?|mon|pce|scm|sht?|[tw]gr|vrd)-[ad]?[lw][0125][09]b?)/i,["Huawei",1]],[/(redmi[-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note|max|cc)?[_ ]?(?:\d{0,2}\w?)[_ ]?(?:plus|se|lite|pro)?( 5g|lte)?)(?: bui|\))/i,["Xiaomi",1]],[/\b(poco[\w ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,["Xiaomi",1]],[/\b(?:xiao)?((?:red)?mi[-_ ]?pad[\w- ]*)(?: bui|\))/i,["Xiaomi",1]],[/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i,["OnePlus",1]],[/droid.+; (cph2[3-6]\d[13579]|((gm|hd)19|(ac|be|in|kb)20|(d[en]|eb|le|mt)21|ne22)[0-2]\d)(?: bui|\))/i,["OnePlus",1]],[/; (\w+) bui.+ oppo/i,["OPPO",1]],[/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i,["OPPO",1]],[/\b(opd2(\d{3}a?))(?: bui|\))/i,["OPPO",1]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i,["Realme",1]],[/; vivo (\w+)(?: bui|\))/i,["Vivo",1]],[/\b(v[12]\d{3}\w?[at])(?: bui|;)/i,["Vivo",1]],[/\bmot(?:orola)?[- ]([\w\s]+)(\)| bui)/i,["Motorola",1]],[/((?:moto(?! 360)[-\w() ]+|xt\d{3,4}[cgkosw+]?[-\d]*|nexus 6)(?= bui|\)))/i,["Motorola",1]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b/i,["Motorola",1]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i,["Motorola",1]],[/\blg[-e;/ ]+(?!.*(?:browser|netcast|android tv|watch|webos))(\w+)/i,["LG",1]],[/\blg-?([\d\w]+) bui/i,["LG",1]],[/(lm(?:-?f100[nv]?|-[\w.]+)(?= bui|\))|nexus [45])/i,["LG",1]],[/((?=lg)?[vl]k-?\d{3}) bui/i,["LG",1]],[/droid.+; (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-\w\w\d\d)(?= bui|\))/i,["Sony",1]],[/sony tablet [ps]/i,["Sony","Xperia Tablet"]],[/(sonyericsson)[-_ ]?([-\w]*)/i,["Sony Ericsson",2]],[/\b(?:sony)?sgp\w+(?: bui|\))/i,["Sony",1]],[/(pixel (c|tablet))\b/i,["Google",1]],[/droid.+;(?: google)? (g(01[13]a|020[aem]|025[jn]|1b60|1f8f|2ybb|4s1m|576d|5nz6|8hhn|8vou|a02099|c15s|d1yq|e2ae|ec77|gh2x|kv4x|p4bc|pj41|r83y|tt9q|ur25|wvk6)|pixel[\d ]*a?( pro)?( xl)?( fold)?( \(5g\))?)( bui|\))/i,["Google",1]],[/(google) (pixelbook( go)?)/i,["Google",2]],[/(?:maemo|nokia).*(n900|lumia \d+|rm-\d+)/i,["Nokia",1]],[/nokia[-_ ]?(([-\w. ]*?))( bui|\)|;|\/)/i,["Nokia",1]],[/(nokia) (t[12][01])/i,["Nokia",2]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i,["ASUS",1]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i,["ASUS",1]],[/lenovo[-_ ]?([-\w ]+?)(?: bui|\)|\/)/i,["Lenovo",1]],[/(ideatab[-\w ]+|602lv|d-42a|a101lv|a2109a|a3500-hv|s[56]000|pb-6505[my]|tb-?x?\d{3,4}(?:f[cu]|xu|[av])|yt\d?-[jx]?\d+[lfmx])( bui|;|\)|\/)/i,["Lenovo",1]],[/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,["Amazon",1]],[/(kf[a-z]+)( bui|\)).+silk\//i,["Amazon",1]],[/(alexa)webm/i,["Amazon","Echo"]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i,["Amazon",1]],[/(?:blackberry|\(bb10;) (\w+)/i,["BlackBerry",1]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,["BlackBerry",1]],[/(playbook);[-\w),; ]+(rim)/i,["BlackBerry",1]],[/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,["ZTE",2]],[/(alcatel|geeksphone|nexian|panasonic)[-_ ]?([-\w]*)/i,[1,2]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,["HTC",2]],[/(microsoft); (lumia[\w ]+)/i,["Microsoft",2]],[/(surface duo)/i,["Microsoft","Surface Duo"]],[/(dell) (streak)/i,["Dell",2]],[/(hp) ([\w ]+\w)/i,["HP",2]],[/(sharp)\/?([-\w]*)/i,["Sharp",2]],[/(benq)[-_ ]?([-\w]*)/i,["BenQ",2]],[/(palm)[-_ ]?([-\w]*)/i,["Palm",2]],[/(meizu)[-_ ]?([-\w]*)/i,["Meizu",2]],[/(tecno)[-_ ]?([-\w]*)/i,["Tecno",2]],[/(infinix)[-_ ]?([-\w]*)/i,["Infinix",2]],[/(micromax)[-_ ]?([-\w]*)/i,["Micromax",2]],[/(lava)[-_ ]?([-\w]*)/i,["Lava",2]],[/(spice)[-_ ]?([-\w]*)/i,["Spice",2]],[/(fairphone)[-_ ]?([-\w]*)/i,["Fairphone",2]],[/(cat)[-_ ]?([-\w]*)/i,["Cat",2]],[/(energy)[-_ ]?([-\w]*)/i,["Energizer",2]],[/(ulefone)[-_ ]?([-\w]*)/i,["Ulefone",2]],[/(doogee)[-_ ]?([-\w]*)/i,["Doogee",2]],[/(blackview)[-_ ]?([-\w]*)/i,["Blackview",2]],[/(shield \w+ tv)/i,["Nvidia",1]],[/(crkey)/i,["Google","Chromecast"]],[/(roku)[\dx]*[)/]((?:dvp-)?[\d.]*)/i,["Roku",1]],[/(apple) ?tv/i,["Apple","TV"]],[/(amazon) ?tv/i,["Amazon","Fire TV"]]];for(let[i,r]of t){let a=e.match(i);if(a){let n=r[0],o=r[1],u=typeof n=="number"?a[n]:n,l=typeof o=="number"?a[o]:o;this._details.vendor=u,this._details.model=l||"Unknown";break}}}catch(t){console.error("Device details detection error:",t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let a=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(a);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}normalizeOSName(e){let t=e.toLowerCase();return t.includes("mac")?"macOS":t.includes("win")?"Windows":t.includes("linux")?"Linux":t.includes("android")?"Android":t.includes("ios")||t.includes("iphone")?"iOS":e}normalizeOSVersion(e){return e.replace(/_/g,".")}};var to=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e??0,this._isHdr=!!matchMedia("(dynamic-range: high)")?.matches,this._colorDepth=screen.colorDepth}catch(t){console.error(t)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(t){console.error(t)}}};var Ve=()=>window.ManagedMediaSource||window.MediaSource,ai=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Nm=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),Ir=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var ZP=document.createElement("video"),eA='video/mp4; codecs="avc1.42000a,mp4a.40.2"',tA='video/mp4; codecs="hev1.1.6.L93.B0"',Fm='video/webm; codecs="vp09.00.10.08"',Um='video/webm; codecs="av01.0.00M.08"',iA='audio/mp4; codecs="mp4a.40.2"',rA='audio/webm; codecs="opus"',qm,sA=async()=>{if(!window.navigator.mediaCapabilities)return;let s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:Um}}),window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:Fm}})]);qm={DASH_WEBM_AV1:e,DASH_WEBM:t}};sA().catch(s=>{console.log(ZP),console.error(s)});var io=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return qm}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){this._video=document.createElement("video");try{this._protocols={mms:ai(),mse:Nm(),hls:!!(this._video.canPlayType?.("application/x-mpegurl")||this._video.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!this._video.canPlayType?.("video/mp4"),webm:!!this._video.canPlayType?.("video/webm"),cmaf:!0};let e=!!Ve()?.isTypeSupported?.(eA),t=!!Ve()?.isTypeSupported?.(tA),i=!!Ve()?.isTypeSupported?.(iA);this._codecs={h264:e,h265:t,vp9:!!Ve()?.isTypeSupported?.(Fm),av1:!!Ve()?.isTypeSupported?.(Um),aac:i,opus:!!Ve()?.isTypeSupported?.(rA),mpeg:(e||t)&&i},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(e){console.error(e)}try{this.destroyVideoElement()}catch(e){console.error("Error destroying video element:",e)}}destroyVideoElement(){if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);this._video.parentNode?.replaceChild(e,this._video),this._video=null}};var jm="audio/mpeg",ro=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){this._audio=document.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(jm)},this._codecs={mp3:!!Ve()?.isTypeSupported?.(jm)}}catch(e){console.error(e)}try{this.destroyAudioElement()}catch(e){console.error("Error destroying audio element:",e)}}destroyAudioElement(){if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);this._audio.parentNode?.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as aA}from"@vkontakte/videoplayer-shared/es2024";var Ol=class{constructor(){this.isInited$=new aA(!1);this._displayChecker=new to,this._deviceChecker=new eo(this._displayChecker),this._browserChecker=new Zn,this._videoChecker=new io(this._deviceChecker,this._browserChecker),this._audioChecker=new ro,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}async detect(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},$=new Ol;var Nl=s=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=$.video,a=(i.h264||i.h265)&&i.aac,n=t.mse||t.mms;return s.filter(o=>{switch(o){case"DASH_SEP":return n&&e.mp4&&a;case"DASH_WEBM":return n&&e.webm&&i.vp9&&i.opus;case"DASH_WEBM_AV1":return n&&e.webm&&i.av1&&i.opus;case"DASH_STREAMS":return n&&(e.mp4&&a||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return n&&e.mp4&&a;case"DASH_LIVE_CMAF":return n&&e.mp4&&a&&e.cmaf;case"DASH_ONDEMAND":return n&&e.mp4&&a;case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":case"HLS_LIVE":case"HLS_LIVE_CMAF":return r;case"MPEG":return e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return t.webrtc&&t.ws&&i.h264&&(e.mp4||e.webm);default:return Hm(o)}})},_s=s=>{switch(s){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_FMP4":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 Hm(s)}},nA=s=>{let t=Object.keys(s).filter(i=>!_s(i));return Nl(t).length>0};var Os=class{constructor(e){this.subscription=new lA;this.sessionId$=new Hl(null);this.mediaSessionId$=new Hl(null);this.contentId$=new Hl(null);this.isMobile=Ci();this.mobileVolumeState={muted:!1,volume:0};this.media=null;this.lastRequestedVolume=null;this.syncMediaState=e=>{if(Qm(e))return;this.media=e,this.mediaSessionId$.next(e.mediaSessionId??null);let t=e.media?.contentId;t&&this.contentId$.next(t),this.syncPlaybackState(e);let i=e.media?.duration;jl(i)&&this.params.output.duration$.next(Math.max(0,i));let r=e.currentTime;if(jl(r)){this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.params.output.position$.next(r);let n=this.params.output.isLive$.getValue();e.playerState==="PLAYING"&&!n?this.progressTicker.start(r):this.progressTicker.pause()}};this.params=e,this.progressTicker=new Jn(e),this.log=this.params.dependencies.logger.createComponentLog("ChromecastPresentationApiProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(_s(e.format)),this.subscribe()}subscribe(){let e=r=>{this.params.output.error$.next({category:oA.WTF,id:"ChromecastPresentationApiProvider",message:r?.message??"Unknown error",thrown:r})};this.subscription.add(this.params.chromecastConnector.message$.pipe(Er(r=>!!r)).subscribe(r=>{this.handleMessage(r)},e)),this.subscription.add(this.sessionId$.pipe(Er(jl),zm(),ql(0)).subscribe(()=>{this.loadMedia()},e));let t=this.contentId$.pipe(zm(),uA(Boolean));this.subscription.add(Ul({seekState:this.params.desiredState.seekState.stateChangeEnded$,mediaLoaded:t}).pipe(Er(({mediaLoaded:r})=>r)).subscribe(()=>{let r=this.params.desiredState.seekState.getState();r.state==="requested"&&this.seek(r.position/1e3)},e));let i=Ul({playbackState:this.params.desiredState.playbackState.stateChangeStarted$,mediaLoaded:t});this.subscription.add(i.pipe(Er(({mediaLoaded:r})=>r),ql(0)).subscribe(()=>{this.syncPlayback()},e)),this.subscription.add(i.pipe(Er(({mediaLoaded:r,playbackState:{from:a,to:n}})=>!r&&a==="stopped"&&n==="playing")).subscribe(()=>{this.loadMedia()},e)),this.subscription.add(Ul({volumeState:this.params.desiredState.volume.stateChangeStarted$.pipe(ql(30)),mediaLoaded:t}).pipe(Er(({mediaLoaded:r})=>r)).subscribe(({volumeState:r})=>{let{muted:a,volume:n}=r.to;this.setVolume(n,a)},e))}handleMessage(e){switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId);let t=e.message?.media?.[0];this.syncMediaState(t);let i=e.message?.receiver.volume;this.syncVolumeState(i)}break;case"v2_message":{switch(e.message?.type){case"MEDIA_STATUS":{let t=e.message?.status?.[0];this.syncMediaState(t);break}}break}}}loadMedia(){let e=Xn(this.params),t=this.media?.currentTime,i=this.params.desiredState.seekState.getState(),r=t??(i.state!=="none"?i.position/1e3:0),n=this.params.desiredState.playbackState.getState()==="playing";this.params.chromecastConnector.sendV2Message({type:"LOAD",requestId:0,media:e,autoplay:n,currentTime:r,customData:null,activeTrackIds:null}),this.params.output.willSeekEvent$.next()}stop(){this.params.chromecastConnector.stopMedia()}play(){let e=this.mediaSessionId$.getValue();Fl(e,"play on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PLAY",mediaSessionId:e,customData:null})}pause(){let e=this.mediaSessionId$.getValue();Fl(e,"pause on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PAUSE",mediaSessionId:e,customData:null})}seek(e){let t=this.mediaSessionId$.getValue();Fl(t,"seek on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"SEEK",currentTime:e,mediaSessionId:t}),this.params.output.willSeekEvent$.next()}setVolume(e,t){let i=e,r=`[setVolume] volume: ${e}, muted: ${t}`;this.isMobile&&(i=this.mobileVolumeState.volume,r+=`, mobile next volume: ${i}`),this.log({message:r}),this.lastRequestedVolume={volume:i,muted:t},this.params.chromecastConnector.sendV2Message({type:"SET_VOLUME",requestId:0,volume:{level:t?0:i,muted:t?!0:null}})}syncPlaybackState({playerState:e,idleReason:t}){let i=this.params.output.isBuffering$.getValue(),r=e==="BUFFERING";switch(i!==r&&this.params.output.isBuffering$.next(r),e){case"PAUSED":P(this.params.desiredState.playbackState,"paused");break;case"PLAYING":P(this.params.desiredState.playbackState,"playing");break;case"IDLE":{t==="FINISHED"?(this.params.output.endedEvent$.next(),P(this.params.desiredState.playbackState,"stopped"),this.contentId$.next(null)):P(this.params.desiredState.playbackState,"ready");break}case"BUFFERING":break}}syncPlayback(){let e=this.params.desiredState.playbackState.getState();switch(this.log({message:`[syncPlayback] ${e}`}),e){case"ready":break;case"playing":this.play();break;case"paused":this.pause();break;case"stopped":this.stop();break}}syncVolumeState(e){if(Qm(e))return;let{level:t,muted:i}=e,r={muted:i??!1,volume:t??0};this.lastRequestedVolume&&(i&&(r.volume=this.lastRequestedVolume.volume),this.lastRequestedVolume.muted&&!t&&!i&&(r.volume=this.lastRequestedVolume.volume,r.muted=!0),this.lastRequestedVolume=null);let a=`[syncVolumeState] volume: ${r.volume}, muted: ${r.muted}`;this.isMobile&&(this.mobileVolumeState.volume=r.volume,this.mobileVolumeState.muted=r.muted,r.volume=this.params.output.volume$.getValue().volume,a+=`, volume passed to state machine: ${r.volume}`),this.log({message:a}),this.params.output.volume$.next(r)}destroy(){this.progressTicker.destroy(),this.subscription.unsubscribe()}};import{assertNonNullable as cA,ErrorCategory as zl,filter as dA,Subject as pA,Subscription as Ql,tap as hA,ValueSubject as wr,fromEvent as Ns}from"@vkontakte/videoplayer-shared/es2024";var Wm=s=>({castDevice:{friendlyName:s},remotePlayer:{},remotePlayerController:{},session:{}}),Gm=()=>String(Date.now())+String(Math.floor(Math.random()*1e5));var Fs=class{constructor(e){this.capabilities=["WEB"];this.presentationRequest$=new wr(null);this.sessionId$=new wr(null);this.broadcastChannel=new BroadcastChannel("vk_player_chromecast_events");this.subscription=new Ql;this.subscriptionEvents=new Ql;this.isDestroyed=!1;this.sequenceNumber=0;this.presentationAvailable$=new wr(!1);this.presentationConnection$=new wr(null);this.message$=new wr(null);this.friendlyName$=new wr(null);this.errorEvent$=new pA;this.clientId=this.getClientId(),this.params=e,this.log=e.logger.createComponentLog("ChromecastPresentationApiConnector"),this.log({message:"constructor"}),this.reinitPresentation(),this.subscribe()}destroy(){this.log({message:"destroy"}),this.subscription.unsubscribe(),this.subscriptionEvents.unsubscribe(),this.broadcastChannel.close(),this.isDestroyed=!0}disconnect(e=!0){this.log({message:"disconnect"}),e&&this.stopMedia(),this.presentationRequest$.next(null);let t=this.presentationConnection$.getValue();t&&t.close(),this.presentationConnection$.next(null),this.friendlyName$.next(null),this.resetSequenceNumber(),this.resetSubscriptionEvents()}stopMedia(){this.log({message:"stopMedia"}),this.sendV2Message({type:"STOP"})}reinitPresentation(e=!0){let t=this.createCastUrl(),i=new PresentationRequest(t);this.presentationRequest$.next(i),this.log({message:"PresentationRequest created"}),i.getAvailability().then(r=>{let a=()=>{this.log({message:`PresentationRequest presentation availability: ${r.value}`}),this.presentationAvailable$.next(r.value)};this.subscriptionEvents.add(Ns(r,"change").subscribe(()=>{a()})),a()}).catch(()=>{this.presentationAvailable$.next(!0)}),window.navigator.presentation.defaultRequest=i,e&&i.reconnect("auto-join").then(r=>{this.log({message:"PresentationRequest reconnect success"}),this.handleConnection(r)}).catch(()=>{this.log({message:"PresentationRequest reconnect failed"})})}async connect(){this.log({message:"connect"});try{this.presentationRequest$.getValue()||(this.log({message:"reinitPresentation"}),this.reinitPresentation(!1));let e=this.presentationRequest$.getValue();cA(e,"connect with null presentationRequest");let t=await e.start();this.handleConnection(t)}catch(e){switch(e?.name){case"AbortError":case"NotAllowedError":break;default:this.errorEvent$.next({category:zl.WTF,id:"ChromecastPresentationApiConnector",message:e?.message??"connect error",thrown:e});break}}}subscribe(){this.subscription.add(Ns(this.broadcastChannel,"message").subscribe(e=>{this.log({message:`broadcast connection data: ${e.data}`}),e.data==="connection"&&this.disconnect(!1)})),this.subscription.add(this.presentationAvailable$.subscribe(e=>{this.log({message:`presentationAvailable$: ${e}`})})),this.subscription.add(this.presentationConnection$.pipe(hA(e=>{this.log({message:`presentationConnection$: ${!!e}`})}),dA(e=>!!e)).subscribe(e=>{let t=Ns(e,"message").subscribe(a=>{let n=JSON.parse(a.data);n.clientId===this.clientId&&(this.log({message:`[onmessage] ${a.data}`}),this.handleMessage(n),this.message$.next(n))}),i=Ns(e,"connect").subscribe(()=>{this.send("client_connect")}),r=Ns(e,"close").subscribe(a=>{switch(a.reason){case"error":this.errorEvent$.next({category:zl.WTF,id:"ChromecastPresentationApiConnector",message:"Session error",thrown:a});break;case"closed":break}});this.subscriptionEvents.add(t),this.subscriptionEvents.add(i),this.subscriptionEvents.add(r)}))}send(e){switch(e){case"client_connect":{let t={type:"client_connect",message:this.clientId,sequenceNumber:-1,timeoutMillis:0,clientId:this.clientId};this.safeSend(JSON.stringify(t));break}}}sendV2Message(e){let t=this.sessionId$.getValue();if(t){let i={type:"v2_message",sequenceNumber:this.getSequenceNumber(),timeoutMillis:0,clientId:this.clientId,message:{...e,sessionId:t}};this.safeSend(JSON.stringify(i))}}safeSend(e){try{this.log({message:`[send] ${e}`});let t=this.presentationConnection$.getValue();t?.state==="connected"&&t?.send(e)}catch(t){this.errorEvent$.next({category:zl.WTF,id:"ChromecastPresentationApiConnector",message:"PresentationConnection send error",data:{message:e},thrown:t})}}handleMessage(e){switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId),this.friendlyName$.next(e.message.receiver.friendlyName||"Chromecast Device");break}case"receiver_action":e.message?.action==="stop"&&this.disconnect();break}}createCastUrl(){return`cast:${this.params.appId}?clientId=${this.clientId}&autoJoinPolicy=tab_and_origin_scoped&defaultActionPolicy=create_session&launchTimeout=60000&supportedAppTypes=${this.capabilities}&appParams=%7B%22launchCheckerParams%22%3A%7B%7D%7D`}getSequenceNumber(){let e=this.sequenceNumber;return this.sequenceNumber=(this.sequenceNumber+1)%Number.MAX_SAFE_INTEGER,e}resetSequenceNumber(){this.sequenceNumber=0}getClientId(){let e="__vk_player_chromecast_id";return window[e]=window[e]||Gm()}resetSubscriptionEvents(){this.subscriptionEvents.unsubscribe(),this.subscriptionEvents=new Ql}handleConnection(e){this.log({message:"connection available"}),this.isDestroyed?(this.log({message:"connected on already destroyed component"}),e.close()):(this.broadcastChannel.postMessage("connection"),this.presentationConnection$.next(e))}};import{ValueSubject as Ym,Subject as fA,map as mA,Subscription as bA,combine as gA,filterChanged as Km,assertNonNullable as SA}from"@vkontakte/videoplayer-shared/es2024";var _t=class s{constructor(e){this.subscription=new bA;this.connection$=new Ym(void 0);this.castState$=new Ym("NOT_AVAILABLE");this.errorEvent$=new fA;let t=s.isSupported();this.log=e.dependencies.logger.createComponentLog("ChromecastPresentationApiInitializer"),this.log({message:`[constructor] receiverApplicationId: ${e.receiverApplicationId}, isDisabled: ${e.isDisabled}, isSupported: ${t}`}),!(!t||e.isDisabled||!e.receiverApplicationId)&&(this.chromecastConnector=new Fs({appId:e.receiverApplicationId,logger:e.dependencies.logger}),this.subscribe())}static isSupported(){return"chrome"in window&&"presentation"in navigator&&"BroadcastChannel"in window}subscribe(){SA(this.chromecastConnector,"subscribe with null chromecastConnector"),this.subscription.add(this.chromecastConnector.errorEvent$.subscribe(this.errorEvent$));let e=gA({connection:this.chromecastConnector.presentationConnection$,available:this.chromecastConnector.presentationAvailable$,friendlyName:this.chromecastConnector.friendlyName$.pipe(Km())});this.subscription.add(e.pipe(mA(({connection:t,friendlyName:i})=>!!(t&&i)),Km()).subscribe(t=>{let i=this.chromecastConnector?.friendlyName$.getValue()??"";this.connection$.next(t?Wm(i):void 0)})).add(e.subscribe(({available:t,connection:i})=>{t?i?this.castState$.next("CONNECTED"):this.castState$.next("AVAILABLE"):this.castState$.next("NOT_AVAILABLE")}))}connect(){this.log({message:"connect"}),this.chromecastConnector?.connect()}disconnect(){this.log({message:"disconnect"}),this.chromecastConnector?.disconnect()}async stopMedia(){this.log({message:"stopMedia"}),this.chromecastConnector?.stopMedia()}toggleConnection(){let e=!!this.chromecastConnector?.presentationConnection$.getValue();this.log({message:`toggleConnection: isConnected - ${e}`}),e?this.disconnect():this.connect()}setVolume(e){}setMuted(e){}destroy(){this.log({message:"destroy"}),this.chromecastConnector?.destroy(),this.subscription.unsubscribe()}};var Jp=D(ke(),1),Zp=D(ni(),1),mw=D(fc(),1);var Dv=D(Ro(),1);import{isNonNullable as sD,Subject as $o,merge as Av}from"@vkontakte/videoplayer-shared/es2024";var O=class{constructor(e){this.transitionStarted$=new $o;this.transitionEnded$=new $o;this.transitionUpdated$=new $o;this.forceChanged$=new $o;this.stateChangeStarted$=Av(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Av(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||sD(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}};import{assertNever as Zs,debounce as Rv,ErrorCategory as aD,fromEvent as Ui,map as $v,merge as Mv,observableFrom as nD,Subject as oD,Subscription as ed,timeout as uD}from"@vkontakte/videoplayer-shared/es2024";var lD=5,cD=5,dD=500,Lv=7e3,ea=class{constructor(e){this.subscription=new ed;this.loadMediaTimeoutSubscription=new ed;this.videoState=new O("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=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(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&a.state==="requested"&&e!=="stopped"){this.seek(a.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:Zs(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:Zs(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:Zs(e)}break}default:Zs(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(_s(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 ed;this.subscription.add(e),this.subscription.add(Mv(this.videoState.stateChangeStarted$.pipe($v(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe($v(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new oD;e.add(r.pipe(Rv(dD)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(Ui(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-a)>lD)&&r.next(o),a=o})),e.add(Ui(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Ui(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Ui(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(Ui(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:a}=this.params.connection,n=r.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()&&a.duration-a.currentTime<cD&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),P(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Zs(n)}}),t(Ui(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(Ui(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Mv(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,nD(["init"])).pipe(Rv(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"),P(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),P(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=Xn(this.params),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),P(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&P(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),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()}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((r,a)=>{this.loadMediaTimeoutSubscription.add(uD(Lv).subscribe(()=>a(`timeout(${Lv})`)))});(0,Dv.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()},r=>{let a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:aD.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var vd=D(ke(),1);import{clearVideoElement as Cv}from"@vkontakte/videoplayer-shared/es2024";import{clearVideoElement as pD}from"@vkontakte/videoplayer-shared/es2024";var Bv=s=>{try{s.pause(),s.playbackRate=0,pD(s),s.remove()}catch(e){console.error(e)}};import{fromEvent as hD,Subscription as fD}from"@vkontakte/videoplayer-shared/es2024";var td=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)}},id=window.WeakMap?new WeakMap:new td,rd=window.WeakMap?new WeakMap:new Map,mD=(s,e=20)=>{let t=0;return hD(s,"ratechange").subscribe(i=>{t++,t>=e&&(s.currentTime=s.currentTime,t=0)})},Pe=(s,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=s.querySelector("video"),r=!!i;i?Cv(i):(i=document.createElement("video"),s.appendChild(i)),id.set(i,r);let a=new fD;return a.add(mD(i,e)),rd.set(i,a),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},Ae=s=>{rd.get(s)?.unsubscribe(),rd.delete(s);let t=id.get(s);id.delete(s),t?Cv(s):Bv(s)};var ad=D(Di(),1);import{assertNonNullable as ia,isNonNullable as At,isNullable as SD,fromEvent as Br,merge as Vv,observableFrom as _v,filterChanged as Ov,map as ra,Subject as Nv,Subscription as vD,ValueSubject as yD,ErrorCategory as TD}from"@vkontakte/videoplayer-shared/es2024";import{isNonNullable as sd,isNullable as bD,Subscription as gD}from"@vkontakte/videoplayer-shared/es2024";var Mo=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{let n=s.getState(),o=e(),u=bD(r),l=new gD;return r&&l.add(r.subscribe(p=>{let c=s.getState();i(p,c)&&s.setState(p)},a)),i(o,n)||(t(n),u&&s.setState(n)),l.add(s.stateChangeStarted$.subscribe(p=>{t(p.to),u&&s.setState(p.to)},a)),l},ot=(s,e,t)=>Mo(e,()=>s.loop,i=>{sd(i)&&(s.loop=i)},{onError:t}),Re=(s,e,t,i)=>Mo(e,()=>({muted:s.muted,volume:s.volume}),r=>{sd(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||r?.muted===a?.muted&&r?.volume===a?.volume,changed$:t,onError:i}),Qe=(s,e,t,i)=>Mo(e,()=>s.playbackRate,r=>{sd(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),ta=Mo;var ID=s=>["__",s.language,s.label].join("|"),ED=(s,e)=>{if(s.id===e)return!0;let[t,i,r]=e.split("|");return s.language===i&&s.label===r},nd=class s{constructor(e){this.available$=new Nv;this.current$=new yD(void 0);this.error$=new Nv;this.subscription=new vD;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=a=>{this.error$.next({id:"TextTracksManager",category:TD.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};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(ta(t.internalTextTracks,()=>(0,ad.default)(this.internalTracks),a=>{At(a)&&this.setInternal(a)},{equal:(a,n)=>At(a)&&At(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(ra(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(ta(t.externalTextTracks,()=>(0,ad.default)(this.externalTracks),a=>{At(a)&&this.setExternal(a)},{equal:(a,n)=>At(a)&&At(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(ra(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(ta(t.currentTextTrack,()=>{if(this.video)return;let a=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(ta(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){ia(this.video);let{textTracks:e}=this.video;this.subscription.add(Br(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(Vv(Br(e,"addtrack"),Br(e,"removetrack"),_v(["init"])).pipe(ra(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),Ov((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(Vv(Br(e,"change"),_v(["init"])).pipe(ra(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),ra(i=>i&&this.htmlTextTrackToITextTrack(i).id),Ov()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(Br(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=a=>{let n=a.target?.cues??null;n&&n.length&&(this.applyCueSettings(a.target?.cues??null),a.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add(Br(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 r=i;At(t.align)&&(r.align=t.align),At(t.position)&&(r.position=t.position),At(t.size)&&(r.size=t.size),At(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){ia(this.video);let t=[...this.video.textTracks];return e?t:t.filter(s.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:ID(e),a=this.externalTracks.has(r),n=(a?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??r.includes("auto");return a?{id:r,type:"external",isAuto:n,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:this.internalTracks.get(r)?.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:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){ia(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(SD(e)||!ED(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){ia(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):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){ia(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)}},We=nd;var qi=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 Fv=s=>{let e=s;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},od=s=>{let e=Fv(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},Uv=s=>{let e=Fv(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};import{fromEvent as _e,map as Rt,merge as Lo,filterChanged as jv,isNonNullable as Hv,Subject as xD,filter as ud,mapTo as ld,combine as kD,once as PD,shareReplay as Oe,throttle as AD,ErrorCategory as RD,ValueSubject as zv,Subscription as $D}from"@vkontakte/videoplayer-shared/es2024";var wD=3,qv=(s,e,t=wD)=>{let i=0,r=0;for(let a=0;a<s.length;a++){let n=s.start(a),o=s.end(a);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)s.end(u)+t>=i&&(i=s.start(u));for(let u=a+1;u<s.length;u++)s.start(u)-t<=r&&(r=s.end(u))}}return{from:i,to:r}};var $e=s=>{let e=k=>_e(s,k).pipe(ld(void 0),Oe(1)),t=new $D,i=()=>t.unsubscribe(),r=Lo(_e(s,"progress"),_e(s,"timeupdate")).pipe(Rt(()=>qv(s.buffered,s.currentTime)),Oe(1)),a=$.browser.isSafari?kD({play:e("play").pipe(PD()),playing:e("playing")}).pipe(ld(void 0),Oe(1)):e("playing"),n=_e(s,"volumechange").pipe(Rt(()=>({muted:s.muted,volume:s.volume})),Oe(1)),o=_e(s,"ratechange").pipe(Rt(()=>s.playbackRate),Oe(1)),u=_e(s,"error").pipe(ud(()=>!!(s.error||s.played.length)),Rt(()=>{let k=s.error;return{id:k?`MediaError#${k.code}`:"HtmlVideoError",category:RD.VIDEO_PIPELINE,message:k?k.message:"Error event from HTML video element",thrown:s.error??void 0}}),Oe(1)),l=_e(s,"timeupdate").pipe(Rt(()=>s.currentTime),Oe(1)),p=["waiting","seeking","seeked","timeupdate"],c=new xD,d=.3,h;t.add(Lo(...p.map(k=>_e(s,k))).subscribe(k=>{let F=s.currentTime;s.loop&&Hv(h)&&Hv(F)&&h>=s.duration-d&&F<=d&&c.next(h),h=F}));let f=e("pause").pipe(ud(()=>!s.error&&h!==s.duration),Oe(1)),m=_e(s,"enterpictureinpicture").pipe(Oe(1)),S=_e(s,"leavepictureinpicture").pipe(Oe(1)),g=new zv(Uv(s));t.add(m.subscribe(()=>g.next(!0))),t.add(S.subscribe(()=>g.next(!1)));let v=new zv(od(s)),T=_e(s,"fullscreenchange").pipe(Oe(1));t.add(T.pipe(Rt(()=>od(s))).subscribe(v));let y=.1,x=1e3,A=_e(s,"timeupdate").pipe(Rt(k=>s.duration-s.currentTime<y),jv(),Oe(1)),R=Lo(A.pipe(ud(k=>!s.loop&&k)),_e(s,"ended")).pipe(AD(x),ld(void 0),Oe(1)),B=Lo(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(k=>_e(s,k)),A.pipe(Rt(k=>({type:k?"ended":"unknown"})))).pipe(Rt(k=>$.browser.isFirefox&&k.type==="ended"?s.readyState<2:s.readyState<3),jv(),Oe(1));return{playing$:a,pause$:f,canplay$:e("canplay"),ended$:R,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$:_e(s,"durationchange").pipe(Rt(()=>s.duration),Oe(1)),isBuffering$:B,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v,enterPip$:m,leavePip$:S,destroy:i}};import{VideoQuality as ui}from"@vkontakte/videoplayer-shared/es2024";var $t=s=>{switch(s){case"mobile":return ui.Q_144P;case"lowest":return ui.Q_240P;case"low":return ui.Q_360P;case"sd":case"medium":return ui.Q_480P;case"hd":case"high":return ui.Q_720P;case"fullhd":case"full":return ui.Q_1080P;case"quadhd":case"quad":return ui.Q_1440P;case"ultrahd":case"ultra":return ui.Q_2160P}};var Fe=D(Ge(),1),dd=D(ke(),1),Hi=D(ni(),1);import{isNonNullable as K,isNullable as Vo,now as uy,isHigher as _o,isHigherOrEqual as ji,isInvariantQuality as Oo,isLowerOrEqual as Vr,videoSizeToQuality as ly,assertNotEmptyArray as No,assertNonNullable as cy}from"@vkontakte/videoplayer-shared/es2024";var cd=!1,Nt={},Jv=s=>{cd=s},Zv=()=>{Nt={}},ey=s=>{s(Nt)},sa=(s,e)=>{cd&&(Nt.meta=Nt.meta??{},Nt.meta[s]=e)},Ne=class{constructor(e){this.name=e}next(e){if(!cd)return;Nt.series=Nt.series??{};let t=Nt.series[this.name]??[];t.push([Date.now(),e]),Nt.series[this.name]=t}};import{isHigher as ND,isHigherOrEqual as fH,isLower as ty,isLowerOrEqual as mH,isNonNullable as Do,isNullable as FD,videoHeightToQuality as Bo}from"@vkontakte/videoplayer-shared/es2024";function iy(s,e,t){return!s.max&&s.min===e?"high_quality":!s.min&&s.max===t?"traffic_saving":"unknown"}function Cr(s,e,t){return FD(s)||Do(s.min)&&Do(s.max)&&ty(s.max,s.min)||Do(s.min)&&e&&ND(s.min,e)||Do(s.max)&&t&&ty(s.max,t)}function ry({limits:s,highestAvailableHeight:e,lowestAvailableHeight:t}){return Cr({max:s?.max?Bo(s.max):void 0,min:s?.min?Bo(s.min):void 0},e?Bo(e):void 0,t?Bo(t):void 0)}var dy=new Ne("best_bitrate"),Fo=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;var _r=s=>(e,t)=>s*(Number(e.bitrate)-Number(t.bitrate)),yt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=uy()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Uo='Assertion "ABR Tracks is empty array" failed',Co=new WeakMap,sy=new WeakMap,ay=new WeakMap,zi=(s,e,t,i)=>{let r=[...e].sort(_r(1)),a=[...t].sort(_r(1)),n=a.filter(u=>K(u.bitrate)&&K(s.bitrate)?s.bitrate/u.bitrate>i:!0),o=(0,Fe.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1)))??(0,Fe.default)(a,-1);return o&&(0,dd.default)(n,o)?o:n.length?(0,Fe.default)(n,-1):(0,Fe.default)(a,0)},Qi=(s,e,t,i)=>{let r=Co.get(e);r||(r=[...e].sort(_r(1)),Co.set(e,r));let a=Co.get(t);a||(a=[...t].sort(_r(1)),Co.set(t,a));let n=ay.get(s);n||(n=a.filter(u=>K(u.bitrate)&&K(s.bitrate)?s.bitrate/u.bitrate>i:!0),ay.set(s,n));let o=(0,Fe.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1)))??(0,Fe.default)(a,-1);return o&&(0,dd.default)(n,o)?o:n.length?(0,Fe.default)(n,-1):(0,Fe.default)(a,0)},ny=s=>"quality"in s,qo=(s,e,t,i)=>{let r=K(i?.last?.bitrate)&&K(t?.bitrate)&&i.last.bitrate<t.bitrate?s.trackCooldownIncreaseQuality:s.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&uy()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!a&&i.recordSelection(t),a&&i?.last){let n=i.last;i?.recordSwitch(n);let o=ny(n)?"video":"audio",u=ny(n)?n.quality:n.bitrate;return e({message:`
6
+ var Uw=Object.create;var ch=Object.defineProperty;var qw=Object.getOwnPropertyDescriptor;var jw=Object.getOwnPropertyNames;var Hw=Object.getPrototypeOf,zw=Object.prototype.hasOwnProperty;var b=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var Qw=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of jw(e))!zw.call(s,r)&&r!==t&&ch(s,r,{get:()=>e[r],enumerable:!(i=qw(e,r))||i.enumerable});return s};var D=(s,e,t)=>(t=s!=null?Uw(Hw(s)):{},Qw(e||!s||!s.__esModule?ch(t,"default",{value:s,enumerable:!0}):t,s));var se=b((el,ph)=>{"use strict";var xs=function(s){return s&&s.Math===Math&&s};ph.exports=xs(typeof globalThis=="object"&&globalThis)||xs(typeof window=="object"&&window)||xs(typeof self=="object"&&self)||xs(typeof global=="object"&&global)||xs(typeof el=="object"&&el)||function(){return this}()||Function("return this")()});var be=b((mN,hh)=>{"use strict";hh.exports=function(s){try{return!!s()}catch{return!0}}});var ks=b((bN,fh)=>{"use strict";var Ww=be();fh.exports=!Ww(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")})});var tl=b((gN,Sh)=>{"use strict";var Gw=ks(),gh=Function.prototype,mh=gh.apply,bh=gh.call;Sh.exports=typeof Reflect=="object"&&Reflect.apply||(Gw?bh.bind(mh):function(){return bh.apply(mh,arguments)})});var ge=b((SN,Th)=>{"use strict";var vh=ks(),yh=Function.prototype,il=yh.call,Yw=vh&&yh.bind.bind(il,il);Th.exports=vh?Yw:function(s){return function(){return il.apply(s,arguments)}}});var Ai=b((vN,Eh)=>{"use strict";var Ih=ge(),Kw=Ih({}.toString),Xw=Ih("".slice);Eh.exports=function(s){return Xw(Kw(s),8,-1)}});var rl=b((yN,wh)=>{"use strict";var Jw=Ai(),Zw=ge();wh.exports=function(s){if(Jw(s)==="Function")return Zw(s)}});var ae=b((TN,xh)=>{"use strict";var sl=typeof document=="object"&&document.all;xh.exports=typeof sl>"u"&&sl!==void 0?function(s){return typeof s=="function"||s===sl}:function(s){return typeof s=="function"}});var Je=b((IN,kh)=>{"use strict";var ex=be();kh.exports=!ex(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ze=b((EN,Ph)=>{"use strict";var tx=ks(),Un=Function.prototype.call;Ph.exports=tx?Un.bind(Un):function(){return Un.apply(Un,arguments)}});var al=b($h=>{"use strict";var Ah={}.propertyIsEnumerable,Rh=Object.getOwnPropertyDescriptor,ix=Rh&&!Ah.call({1:2},1);$h.f=ix?function(e){var t=Rh(this,e);return!!t&&t.enumerable}:Ah});var Ps=b((xN,Mh)=>{"use strict";Mh.exports=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}}});var Dh=b((kN,Lh)=>{"use strict";var rx=ge(),sx=be(),ax=Ai(),nl=Object,nx=rx("".split);Lh.exports=sx(function(){return!nl("z").propertyIsEnumerable(0)})?function(s){return ax(s)==="String"?nx(s,""):nl(s)}:nl});var As=b((PN,Bh)=>{"use strict";Bh.exports=function(s){return s==null}});var ii=b((AN,Ch)=>{"use strict";var ox=As(),ux=TypeError;Ch.exports=function(s){if(ox(s))throw new ux("Can't call method on "+s);return s}});var Ri=b((RN,Vh)=>{"use strict";var lx=Dh(),cx=ii();Vh.exports=function(s){return lx(cx(s))}});var ze=b(($N,_h)=>{"use strict";var dx=ae();_h.exports=function(s){return typeof s=="object"?s!==null:dx(s)}});var $i=b((MN,Oh)=>{"use strict";Oh.exports={}});var Vt=b((LN,Fh)=>{"use strict";var ol=$i(),ul=se(),px=ae(),Nh=function(s){return px(s)?s:void 0};Fh.exports=function(s,e){return arguments.length<2?Nh(ol[s])||Nh(ul[s]):ol[s]&&ol[s][e]||ul[s]&&ul[s][e]}});var Rs=b((DN,Uh)=>{"use strict";var hx=ge();Uh.exports=hx({}.isPrototypeOf)});var Mi=b((BN,Hh)=>{"use strict";var fx=se(),qh=fx.navigator,jh=qh&&qh.userAgent;Hh.exports=jh?String(jh):""});var cl=b((CN,Kh)=>{"use strict";var Yh=se(),ll=Mi(),zh=Yh.process,Qh=Yh.Deno,Wh=zh&&zh.versions||Qh&&Qh.version,Gh=Wh&&Wh.v8,mt,qn;Gh&&(mt=Gh.split("."),qn=mt[0]>0&&mt[0]<4?1:+(mt[0]+mt[1]));!qn&&ll&&(mt=ll.match(/Edge\/(\d+)/),(!mt||mt[1]>=74)&&(mt=ll.match(/Chrome\/(\d+)/),mt&&(qn=+mt[1])));Kh.exports=qn});var dl=b((VN,Jh)=>{"use strict";var Xh=cl(),mx=be(),bx=se(),gx=bx.String;Jh.exports=!!Object.getOwnPropertySymbols&&!mx(function(){var s=Symbol("symbol detection");return!gx(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&Xh&&Xh<41})});var pl=b((_N,Zh)=>{"use strict";var Sx=dl();Zh.exports=Sx&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var hl=b((ON,ef)=>{"use strict";var vx=Vt(),yx=ae(),Tx=Rs(),Ix=pl(),Ex=Object;ef.exports=Ix?function(s){return typeof s=="symbol"}:function(s){var e=vx("Symbol");return yx(e)&&Tx(e.prototype,Ex(s))}});var $s=b((NN,tf)=>{"use strict";var wx=String;tf.exports=function(s){try{return wx(s)}catch{return"Object"}}});var kt=b((FN,rf)=>{"use strict";var xx=ae(),kx=$s(),Px=TypeError;rf.exports=function(s){if(xx(s))return s;throw new Px(kx(s)+" is not a function")}});var Ms=b((UN,sf)=>{"use strict";var Ax=kt(),Rx=As();sf.exports=function(s,e){var t=s[e];return Rx(t)?void 0:Ax(t)}});var nf=b((qN,af)=>{"use strict";var fl=Ze(),ml=ae(),bl=ze(),$x=TypeError;af.exports=function(s,e){var t,i;if(e==="string"&&ml(t=s.toString)&&!bl(i=fl(t,s))||ml(t=s.valueOf)&&!bl(i=fl(t,s))||e!=="string"&&ml(t=s.toString)&&!bl(i=fl(t,s)))return i;throw new $x("Can't convert object to primitive value")}});var bt=b((jN,of)=>{"use strict";of.exports=!0});var cf=b((HN,lf)=>{"use strict";var uf=se(),Mx=Object.defineProperty;lf.exports=function(s,e){try{Mx(uf,s,{value:e,configurable:!0,writable:!0})}catch{uf[s]=e}return e}});var Ls=b((zN,hf)=>{"use strict";var Lx=bt(),Dx=se(),Bx=cf(),df="__core-js_shared__",pf=hf.exports=Dx[df]||Bx(df,{});(pf.versions||(pf.versions=[])).push({version:"3.43.0",mode:Lx?"pure":"global",copyright:"© 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.43.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var gl=b((QN,mf)=>{"use strict";var ff=Ls();mf.exports=function(s,e){return ff[s]||(ff[s]=e||{})}});var mr=b((WN,bf)=>{"use strict";var Cx=ii(),Vx=Object;bf.exports=function(s){return Vx(Cx(s))}});var gt=b((GN,gf)=>{"use strict";var _x=ge(),Ox=mr(),Nx=_x({}.hasOwnProperty);gf.exports=Object.hasOwn||function(e,t){return Nx(Ox(e),t)}});var Sl=b((YN,Sf)=>{"use strict";var Fx=ge(),Ux=0,qx=Math.random(),jx=Fx(1.1.toString);Sf.exports=function(s){return"Symbol("+(s===void 0?"":s)+")_"+jx(++Ux+qx,36)}});var xe=b((KN,yf)=>{"use strict";var Hx=se(),zx=gl(),vf=gt(),Qx=Sl(),Wx=dl(),Gx=pl(),br=Hx.Symbol,vl=zx("wks"),Yx=Gx?br.for||br:br&&br.withoutSetter||Qx;yf.exports=function(s){return vf(vl,s)||(vl[s]=Wx&&vf(br,s)?br[s]:Yx("Symbol."+s)),vl[s]}});var wf=b((XN,Ef)=>{"use strict";var Kx=Ze(),Tf=ze(),If=hl(),Xx=Ms(),Jx=nf(),Zx=xe(),ek=TypeError,tk=Zx("toPrimitive");Ef.exports=function(s,e){if(!Tf(s)||If(s))return s;var t=Xx(s,tk),i;if(t){if(e===void 0&&(e="default"),i=Kx(t,s,e),!Tf(i)||If(i))return i;throw new ek("Can't convert object to primitive value")}return e===void 0&&(e="number"),Jx(s,e)}});var yl=b((JN,xf)=>{"use strict";var ik=wf(),rk=hl();xf.exports=function(s){var e=ik(s,"string");return rk(e)?e:e+""}});var jn=b((ZN,Pf)=>{"use strict";var sk=se(),kf=ze(),Tl=sk.document,ak=kf(Tl)&&kf(Tl.createElement);Pf.exports=function(s){return ak?Tl.createElement(s):{}}});var Il=b((eF,Af)=>{"use strict";var nk=Je(),ok=be(),uk=jn();Af.exports=!nk&&!ok(function(){return Object.defineProperty(uk("div"),"a",{get:function(){return 7}}).a!==7})});var Mf=b($f=>{"use strict";var lk=Je(),ck=Ze(),dk=al(),pk=Ps(),hk=Ri(),fk=yl(),mk=gt(),bk=Il(),Rf=Object.getOwnPropertyDescriptor;$f.f=lk?Rf:function(e,t){if(e=hk(e),t=fk(t),bk)try{return Rf(e,t)}catch{}if(mk(e,t))return pk(!ck(dk.f,e,t),e[t])}});var El=b((iF,Lf)=>{"use strict";var gk=be(),Sk=ae(),vk=/#|\.prototype\./,Ds=function(s,e){var t=Tk[yk(s)];return t===Ek?!0:t===Ik?!1:Sk(e)?gk(e):!!e},yk=Ds.normalize=function(s){return String(s).replace(vk,".").toLowerCase()},Tk=Ds.data={},Ik=Ds.NATIVE="N",Ek=Ds.POLYFILL="P";Lf.exports=Ds});var gr=b((rF,Bf)=>{"use strict";var Df=rl(),wk=kt(),xk=ks(),kk=Df(Df.bind);Bf.exports=function(s,e){return wk(s),e===void 0?s:xk?kk(s,e):function(){return s.apply(e,arguments)}}});var wl=b((sF,Cf)=>{"use strict";var Pk=Je(),Ak=be();Cf.exports=Pk&&Ak(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Pt=b((aF,Vf)=>{"use strict";var Rk=ze(),$k=String,Mk=TypeError;Vf.exports=function(s){if(Rk(s))return s;throw new Mk($k(s)+" is not an object")}});var Li=b(Of=>{"use strict";var Lk=Je(),Dk=Il(),Bk=wl(),Hn=Pt(),_f=yl(),Ck=TypeError,xl=Object.defineProperty,Vk=Object.getOwnPropertyDescriptor,kl="enumerable",Pl="configurable",Al="writable";Of.f=Lk?Bk?function(e,t,i){if(Hn(e),t=_f(t),Hn(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Al in i&&!i[Al]){var r=Vk(e,t);r&&r[Al]&&(e[t]=i.value,i={configurable:Pl in i?i[Pl]:r[Pl],enumerable:kl in i?i[kl]:r[kl],writable:!1})}return xl(e,t,i)}:xl:function(e,t,i){if(Hn(e),t=_f(t),Hn(i),Dk)try{return xl(e,t,i)}catch{}if("get"in i||"set"in i)throw new Ck("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Sr=b((oF,Nf)=>{"use strict";var _k=Je(),Ok=Li(),Nk=Ps();Nf.exports=_k?function(s,e,t){return Ok.f(s,e,Nk(1,t))}:function(s,e,t){return s[e]=t,s}});var ue=b((uF,Uf)=>{"use strict";var Bs=se(),Fk=tl(),Uk=rl(),qk=ae(),jk=Mf().f,Hk=El(),vr=$i(),zk=gr(),yr=Sr(),Ff=gt();Ls();var Qk=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return Fk(s,this,arguments)};return e.prototype=s.prototype,e};Uf.exports=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?Bs:r?Bs[t]:Bs[t]&&Bs[t].prototype,o=i?vr:vr[t]||yr(vr,t,{})[t],u=o.prototype,l,p,c,d,h,f,m,S,g;for(d in e)l=Hk(i?d:t+(r?".":"#")+d,s.forced),p=!l&&n&&Ff(n,d),f=o[d],p&&(s.dontCallGetSet?(g=jk(n,d),m=g&&g.value):m=n[d]),h=p&&m?m:e[d],!(!l&&!a&&typeof f==typeof h)&&(s.bind&&p?S=zk(h,Bs):s.wrap&&p?S=Qk(h):a&&qk(h)?S=Uk(h):S=h,(s.sham||h&&h.sham||f&&f.sham)&&yr(S,"sham",!0),yr(o,d,S),a&&(c=t+"Prototype",Ff(vr,c)||yr(vr,c,{}),yr(vr[c],d,h),s.real&&u&&(l||!u[d])&&yr(u,d,h)))}});var zn=b((lF,jf)=>{"use strict";var Wk=gl(),Gk=Sl(),qf=Wk("keys");jf.exports=function(s){return qf[s]||(qf[s]=Gk(s))}});var zf=b((cF,Hf)=>{"use strict";var Yk=be();Hf.exports=!Yk(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype})});var Qn=b((dF,Wf)=>{"use strict";var Kk=gt(),Xk=ae(),Jk=mr(),Zk=zn(),eP=zf(),Qf=Zk("IE_PROTO"),Rl=Object,tP=Rl.prototype;Wf.exports=eP?Rl.getPrototypeOf:function(s){var e=Jk(s);if(Kk(e,Qf))return e[Qf];var t=e.constructor;return Xk(t)&&e instanceof t?t.prototype:e instanceof Rl?tP:null}});var Yf=b((pF,Gf)=>{"use strict";var iP=Math.ceil,rP=Math.floor;Gf.exports=Math.trunc||function(e){var t=+e;return(t>0?rP:iP)(t)}});var Cs=b((hF,Kf)=>{"use strict";var sP=Yf();Kf.exports=function(s){var e=+s;return e!==e||e===0?0:sP(e)}});var Jf=b((fF,Xf)=>{"use strict";var aP=Cs(),nP=Math.max,oP=Math.min;Xf.exports=function(s,e){var t=aP(s);return t<0?nP(t+e,0):oP(t,e)}});var $l=b((mF,Zf)=>{"use strict";var uP=Cs(),lP=Math.min;Zf.exports=function(s){var e=uP(s);return e>0?lP(e,9007199254740991):0}});var Tr=b((bF,em)=>{"use strict";var cP=$l();em.exports=function(s){return cP(s.length)}});var Ml=b((gF,im)=>{"use strict";var dP=Ri(),pP=Jf(),hP=Tr(),tm=function(s){return function(e,t,i){var r=dP(e),a=hP(r);if(a===0)return!s&&-1;var n=pP(i,a),o;if(s&&t!==t){for(;a>n;)if(o=r[n++],o!==o)return!0}else for(;a>n;n++)if((s||n in r)&&r[n]===t)return s||n||0;return!s&&-1}};im.exports={includes:tm(!0),indexOf:tm(!1)}});var Wn=b((SF,rm)=>{"use strict";rm.exports={}});var nm=b((vF,am)=>{"use strict";var fP=ge(),Ll=gt(),mP=Ri(),bP=Ml().indexOf,gP=Wn(),sm=fP([].push);am.exports=function(s,e){var t=mP(s),i=0,r=[],a;for(a in t)!Ll(gP,a)&&Ll(t,a)&&sm(r,a);for(;e.length>i;)Ll(t,a=e[i++])&&(~bP(r,a)||sm(r,a));return r}});var Dl=b((yF,om)=>{"use strict";om.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Bl=b((TF,um)=>{"use strict";var SP=nm(),vP=Dl();um.exports=Object.keys||function(e){return SP(e,vP)}});var Cl=b((IF,hm)=>{"use strict";var cm=Je(),yP=be(),dm=ge(),TP=Qn(),IP=Bl(),EP=Ri(),wP=al().f,pm=dm(wP),xP=dm([].push),kP=cm&&yP(function(){var s=Object.create(null);return s[2]=2,!pm(s,2)}),lm=function(s){return function(e){for(var t=EP(e),i=IP(t),r=kP&&TP(t)===null,a=i.length,n=0,o=[],u;a>n;)u=i[n++],(!cm||(r?u in t:pm(t,u)))&&xP(o,s?[u,t[u]]:t[u]);return o}};hm.exports={entries:lm(!0),values:lm(!1)}});var fm=b(()=>{"use strict";var PP=ue(),AP=Cl().values;PP({target:"Object",stat:!0},{values:function(e){return AP(e)}})});var bm=b((xF,mm)=>{"use strict";fm();var RP=$i();mm.exports=RP.Object.values});var Sm=b((kF,gm)=>{"use strict";var $P=bm();gm.exports=$P});var Di=b((PF,vm)=>{"use strict";var MP=Sm();vm.exports=MP});var Vs=b((AF,ym)=>{"use strict";ym.exports=function(){}});var Tm=b(()=>{"use strict";var LP=ue(),DP=Ml().includes,BP=be(),CP=Vs(),VP=BP(function(){return!Array(1).includes()});LP({target:"Array",proto:!0,forced:VP},{includes:function(e){return DP(this,e,arguments.length>1?arguments[1]:void 0)}});CP("includes")});var ri=b((MF,Im)=>{"use strict";var _P=Vt();Im.exports=_P});var wm=b((LF,Em)=>{"use strict";Tm();var OP=ri();Em.exports=OP("Array","includes")});var km=b((DF,xm)=>{"use strict";var NP=wm();xm.exports=NP});var ke=b((BF,Pm)=>{"use strict";var FP=km();Pm.exports=FP});var Xm=b(()=>{"use strict";var vA=ue(),yA=Cl().entries;vA({target:"Object",stat:!0},{entries:function(e){return yA(e)}})});var Zm=b((R1,Jm)=>{"use strict";Xm();var TA=$i();Jm.exports=TA.Object.entries});var tb=b(($1,eb)=>{"use strict";var IA=Zm();eb.exports=IA});var ni=b((M1,ib)=>{"use strict";var EA=tb();ib.exports=EA});var Vi=b((L1,rb)=>{"use strict";rb.exports={}});var nb=b((D1,ab)=>{"use strict";var wA=se(),xA=ae(),sb=wA.WeakMap;ab.exports=xA(sb)&&/native code/.test(String(sb))});var Kl=b((B1,lb)=>{"use strict";var kA=nb(),ub=se(),PA=ze(),AA=Sr(),Wl=gt(),Gl=Ls(),RA=zn(),$A=Wn(),ob="Object already initialized",Yl=ub.TypeError,MA=ub.WeakMap,so,Us,ao,LA=function(s){return ao(s)?Us(s):so(s,{})},DA=function(s){return function(e){var t;if(!PA(e)||(t=Us(e)).type!==s)throw new Yl("Incompatible receiver, "+s+" required");return t}};kA||Gl.state?(vt=Gl.state||(Gl.state=new MA),vt.get=vt.get,vt.has=vt.has,vt.set=vt.set,so=function(s,e){if(vt.has(s))throw new Yl(ob);return e.facade=s,vt.set(s,e),e},Us=function(s){return vt.get(s)||{}},ao=function(s){return vt.has(s)}):(_i=RA("state"),$A[_i]=!0,so=function(s,e){if(Wl(s,_i))throw new Yl(ob);return e.facade=s,AA(s,_i,e),e},Us=function(s){return Wl(s,_i)?s[_i]:{}},ao=function(s){return Wl(s,_i)});var vt,_i;lb.exports={set:so,get:Us,has:ao,enforce:LA,getterFor:DA}});var Zl=b((C1,db)=>{"use strict";var Xl=Je(),BA=gt(),cb=Function.prototype,CA=Xl&&Object.getOwnPropertyDescriptor,Jl=BA(cb,"name"),VA=Jl&&function(){}.name==="something",_A=Jl&&(!Xl||Xl&&CA(cb,"name").configurable);db.exports={EXISTS:Jl,PROPER:VA,CONFIGURABLE:_A}});var hb=b(pb=>{"use strict";var OA=Je(),NA=wl(),FA=Li(),UA=Pt(),qA=Ri(),jA=Bl();pb.f=OA&&!NA?Object.defineProperties:function(e,t){UA(e);for(var i=qA(t),r=jA(t),a=r.length,n=0,o;a>n;)FA.f(e,o=r[n++],i[o]);return e}});var ec=b((_1,fb)=>{"use strict";var HA=Vt();fb.exports=HA("document","documentElement")});var sc=b((O1,Tb)=>{"use strict";var zA=Pt(),QA=hb(),mb=Dl(),WA=Wn(),GA=ec(),YA=jn(),KA=zn(),bb=">",gb="<",ic="prototype",rc="script",vb=KA("IE_PROTO"),tc=function(){},yb=function(s){return gb+rc+bb+s+gb+"/"+rc+bb},Sb=function(s){s.write(yb("")),s.close();var e=s.parentWindow.Object;return s=null,e},XA=function(){var s=YA("iframe"),e="java"+rc+":",t;return s.style.display="none",GA.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(yb("document.F=Object")),t.close(),t.F},no,oo=function(){try{no=new ActiveXObject("htmlfile")}catch{}oo=typeof document<"u"?document.domain&&no?Sb(no):XA():Sb(no);for(var s=mb.length;s--;)delete oo[ic][mb[s]];return oo()};WA[vb]=!0;Tb.exports=Object.create||function(e,t){var i;return e!==null?(tc[ic]=zA(e),i=new tc,tc[ic]=null,i[vb]=e):i=oo(),t===void 0?i:QA.f(i,t)}});var xr=b((N1,Ib)=>{"use strict";var JA=Sr();Ib.exports=function(s,e,t,i){return i&&i.enumerable?s[e]=t:JA(s,e,t),s}});var uc=b((F1,xb)=>{"use strict";var ZA=be(),eR=ae(),tR=ze(),iR=sc(),Eb=Qn(),rR=xr(),sR=xe(),aR=bt(),oc=sR("iterator"),wb=!1,Ot,ac,nc;[].keys&&(nc=[].keys(),"next"in nc?(ac=Eb(Eb(nc)),ac!==Object.prototype&&(Ot=ac)):wb=!0);var nR=!tR(Ot)||ZA(function(){var s={};return Ot[oc].call(s)!==s});nR?Ot={}:aR&&(Ot=iR(Ot));eR(Ot[oc])||rR(Ot,oc,function(){return this});xb.exports={IteratorPrototype:Ot,BUGGY_SAFARI_ITERATORS:wb}});var uo=b((U1,Pb)=>{"use strict";var oR=xe(),uR=oR("toStringTag"),kb={};kb[uR]="z";Pb.exports=String(kb)==="[object z]"});var qs=b((q1,Ab)=>{"use strict";var lR=uo(),cR=ae(),lo=Ai(),dR=xe(),pR=dR("toStringTag"),hR=Object,fR=lo(function(){return arguments}())==="Arguments",mR=function(s,e){try{return s[e]}catch{}};Ab.exports=lR?lo:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=mR(e=hR(s),pR))=="string"?t:fR?lo(e):(i=lo(e))==="Object"&&cR(e.callee)?"Arguments":i}});var $b=b((j1,Rb)=>{"use strict";var bR=uo(),gR=qs();Rb.exports=bR?{}.toString:function(){return"[object "+gR(this)+"]"}});var js=b((H1,Lb)=>{"use strict";var SR=uo(),vR=Li().f,yR=Sr(),TR=gt(),IR=$b(),ER=xe(),Mb=ER("toStringTag");Lb.exports=function(s,e,t,i){var r=t?s:s&&s.prototype;r&&(TR(r,Mb)||vR(r,Mb,{configurable:!0,value:e}),i&&!SR&&yR(r,"toString",IR))}});var Bb=b((z1,Db)=>{"use strict";var wR=uc().IteratorPrototype,xR=sc(),kR=Ps(),PR=js(),AR=Vi(),RR=function(){return this};Db.exports=function(s,e,t,i){var r=e+" Iterator";return s.prototype=xR(wR,{next:kR(+!i,t)}),PR(s,r,!1,!0),AR[r]=RR,s}});var Vb=b((Q1,Cb)=>{"use strict";var $R=ge(),MR=kt();Cb.exports=function(s,e,t){try{return $R(MR(Object.getOwnPropertyDescriptor(s,e)[t]))}catch{}}});var Ob=b((W1,_b)=>{"use strict";var LR=ze();_b.exports=function(s){return LR(s)||s===null}});var Fb=b((G1,Nb)=>{"use strict";var DR=Ob(),BR=String,CR=TypeError;Nb.exports=function(s){if(DR(s))return s;throw new CR("Can't set "+BR(s)+" as a prototype")}});var lc=b((Y1,Ub)=>{"use strict";var VR=Vb(),_R=ze(),OR=ii(),NR=Fb();Ub.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var s=!1,e={},t;try{t=VR(Object.prototype,"__proto__","set"),t(e,[]),s=e instanceof Array}catch{}return function(r,a){return OR(r),NR(a),_R(r)&&(s?t(r,a):r.__proto__=a),r}}():void 0)});var Jb=b((K1,Xb)=>{"use strict";var FR=ue(),UR=Ze(),co=bt(),Yb=Zl(),qR=ae(),jR=Bb(),qb=Qn(),jb=lc(),HR=js(),zR=Sr(),cc=xr(),QR=xe(),Hb=Vi(),Kb=uc(),WR=Yb.PROPER,GR=Yb.CONFIGURABLE,zb=Kb.IteratorPrototype,po=Kb.BUGGY_SAFARI_ITERATORS,Hs=QR("iterator"),Qb="keys",zs="values",Wb="entries",Gb=function(){return this};Xb.exports=function(s,e,t,i,r,a,n){jR(t,e,i);var o=function(g){if(g===r&&d)return d;if(!po&&g&&g in p)return p[g];switch(g){case Qb:return function(){return new t(this,g)};case zs:return function(){return new t(this,g)};case Wb:return function(){return new t(this,g)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,p=s.prototype,c=p[Hs]||p["@@iterator"]||r&&p[r],d=!po&&c||o(r),h=e==="Array"&&p.entries||c,f,m,S;if(h&&(f=qb(h.call(new s)),f!==Object.prototype&&f.next&&(!co&&qb(f)!==zb&&(jb?jb(f,zb):qR(f[Hs])||cc(f,Hs,Gb)),HR(f,u,!0,!0),co&&(Hb[u]=Gb))),WR&&r===zs&&c&&c.name!==zs&&(!co&&GR?zR(p,"name",zs):(l=!0,d=function(){return UR(c,this)})),r)if(m={values:o(zs),keys:a?d:o(Qb),entries:o(Wb)},n)for(S in m)(po||l||!(S in p))&&cc(p,S,m[S]);else FR({target:e,proto:!0,forced:po||l},m);return(!co||n)&&p[Hs]!==d&&cc(p,Hs,d,{name:r}),Hb[e]=d,m}});var eg=b((X1,Zb)=>{"use strict";Zb.exports=function(s,e){return{value:s,done:e}}});var pc=b((J1,ag)=>{"use strict";var YR=Ri(),dc=Vs(),tg=Vi(),rg=Kl(),KR=Li().f,XR=Jb(),ho=eg(),JR=bt(),ZR=Je(),sg="Array Iterator",e$=rg.set,t$=rg.getterFor(sg);ag.exports=XR(Array,"Array",function(s,e){e$(this,{type:sg,target:YR(s),index:0,kind:e})},function(){var s=t$(this),e=s.target,t=s.index++;if(!e||t>=e.length)return s.target=null,ho(void 0,!0);switch(s.kind){case"keys":return ho(t,!1);case"values":return ho(e[t],!1)}return ho([t,e[t]],!1)},"values");var ig=tg.Arguments=tg.Array;dc("keys");dc("values");dc("entries");if(!JR&&ZR&&ig.name!=="values")try{KR(ig,"name",{value:"values"})}catch{}});var og=b((Z1,ng)=>{"use strict";var i$=xe(),r$=Vi(),s$=i$("iterator"),a$=Array.prototype;ng.exports=function(s){return s!==void 0&&(r$.Array===s||a$[s$]===s)}});var hc=b((eq,lg)=>{"use strict";var n$=qs(),ug=Ms(),o$=As(),u$=Vi(),l$=xe(),c$=l$("iterator");lg.exports=function(s){if(!o$(s))return ug(s,c$)||ug(s,"@@iterator")||u$[n$(s)]}});var dg=b((tq,cg)=>{"use strict";var d$=Ze(),p$=kt(),h$=Pt(),f$=$s(),m$=hc(),b$=TypeError;cg.exports=function(s,e){var t=arguments.length<2?m$(s):e;if(p$(t))return h$(d$(t,s));throw new b$(f$(s)+" is not iterable")}});var fg=b((iq,hg)=>{"use strict";var g$=Ze(),pg=Pt(),S$=Ms();hg.exports=function(s,e,t){var i,r;pg(s);try{if(i=S$(s,"return"),!i){if(e==="throw")throw t;return t}i=g$(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return pg(i),t}});var mo=b((rq,Sg)=>{"use strict";var v$=gr(),y$=Ze(),T$=Pt(),I$=$s(),E$=og(),w$=Tr(),mg=Rs(),x$=dg(),k$=hc(),bg=fg(),P$=TypeError,fo=function(s,e){this.stopped=s,this.result=e},gg=fo.prototype;Sg.exports=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=v$(e,i),l,p,c,d,h,f,m,S=function(v){return l&&bg(l,"normal"),new fo(!0,v)},g=function(v){return r?(T$(v),o?u(v[0],v[1],S):u(v[0],v[1])):o?u(v,S):u(v)};if(a)l=s.iterator;else if(n)l=s;else{if(p=k$(s),!p)throw new P$(I$(s)+" is not iterable");if(E$(p)){for(c=0,d=w$(s);d>c;c++)if(h=g(s[c]),h&&mg(gg,h))return h;return new fo(!1)}l=x$(s,p)}for(f=a?s.next:l.next;!(m=y$(f,l)).done;){try{h=g(m.value)}catch(v){bg(l,"throw",v)}if(typeof h=="object"&&h&&mg(gg,h))return h}return new fo(!1)}});var yg=b((sq,vg)=>{"use strict";var A$=Je(),R$=Li(),$$=Ps();vg.exports=function(s,e,t){A$?R$.f(s,e,$$(0,t)):s[e]=t}});var Tg=b(()=>{"use strict";var M$=ue(),L$=mo(),D$=yg();M$({target:"Object",stat:!0},{fromEntries:function(e){var t={};return L$(e,function(i,r){D$(t,i,r)},{AS_ENTRIES:!0}),t}})});var Eg=b((oq,Ig)=>{"use strict";pc();Tg();var B$=$i();Ig.exports=B$.Object.fromEntries});var xg=b((uq,wg)=>{"use strict";wg.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 Pg=b(()=>{"use strict";pc();var C$=xg(),V$=se(),_$=js(),kg=Vi();for(bo in C$)_$(V$[bo],bo),kg[bo]=kg.Array;var bo});var Rg=b((dq,Ag)=>{"use strict";var O$=Eg();Pg();Ag.exports=O$});var fc=b((pq,$g)=>{"use strict";var N$=Rg();$g.exports=N$});var Mg=b(()=>{"use strict"});var mc=b((mq,Lg)=>{"use strict";var Qs=se(),F$=Mi(),U$=Ai(),go=function(s){return F$.slice(0,s.length)===s};Lg.exports=function(){return go("Bun/")?"BUN":go("Cloudflare-Workers")?"CLOUDFLARE":go("Deno/")?"DENO":go("Node.js/")?"NODE":Qs.Bun&&typeof Bun.version=="string"?"BUN":Qs.Deno&&typeof Deno.version=="object"?"DENO":U$(Qs.process)==="process"?"NODE":Qs.window&&Qs.document?"BROWSER":"REST"}()});var So=b((bq,Dg)=>{"use strict";var q$=mc();Dg.exports=q$==="NODE"});var Cg=b((gq,Bg)=>{"use strict";var j$=Li();Bg.exports=function(s,e,t){return j$.f(s,e,t)}});var Og=b((Sq,_g)=>{"use strict";var H$=Vt(),z$=Cg(),Q$=xe(),W$=Je(),Vg=Q$("species");_g.exports=function(s){var e=H$(s);W$&&e&&!e[Vg]&&z$(e,Vg,{configurable:!0,get:function(){return this}})}});var Fg=b((vq,Ng)=>{"use strict";var G$=Rs(),Y$=TypeError;Ng.exports=function(s,e){if(G$(e,s))return s;throw new Y$("Incorrect invocation")}});var gc=b((yq,Ug)=>{"use strict";var K$=ge(),X$=ae(),bc=Ls(),J$=K$(Function.toString);X$(bc.inspectSource)||(bc.inspectSource=function(s){return J$(s)});Ug.exports=bc.inspectSource});var vc=b((Tq,Qg)=>{"use strict";var Z$=ge(),eM=be(),qg=ae(),tM=qs(),iM=Vt(),rM=gc(),jg=function(){},Hg=iM("Reflect","construct"),Sc=/^\s*(?:class|function)\b/,sM=Z$(Sc.exec),aM=!Sc.test(jg),Ws=function(e){if(!qg(e))return!1;try{return Hg(jg,[],e),!0}catch{return!1}},zg=function(e){if(!qg(e))return!1;switch(tM(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return aM||!!sM(Sc,rM(e))}catch{return!0}};zg.sham=!0;Qg.exports=!Hg||eM(function(){var s;return Ws(Ws.call)||!Ws(Object)||!Ws(function(){s=!0})||s})?zg:Ws});var Gg=b((Iq,Wg)=>{"use strict";var nM=vc(),oM=$s(),uM=TypeError;Wg.exports=function(s){if(nM(s))return s;throw new uM(oM(s)+" is not a constructor")}});var yc=b((Eq,Kg)=>{"use strict";var Yg=Pt(),lM=Gg(),cM=As(),dM=xe(),pM=dM("species");Kg.exports=function(s,e){var t=Yg(s).constructor,i;return t===void 0||cM(i=Yg(t)[pM])?e:lM(i)}});var Jg=b((wq,Xg)=>{"use strict";var hM=ge();Xg.exports=hM([].slice)});var eS=b((xq,Zg)=>{"use strict";var fM=TypeError;Zg.exports=function(s,e){if(s<e)throw new fM("Not enough arguments");return s}});var Tc=b((kq,tS)=>{"use strict";var mM=Mi();tS.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(mM)});var $c=b((Pq,cS)=>{"use strict";var et=se(),bM=tl(),gM=gr(),iS=ae(),SM=gt(),lS=be(),rS=ec(),vM=Jg(),sS=jn(),yM=eS(),TM=Tc(),IM=So(),Pc=et.setImmediate,Ac=et.clearImmediate,EM=et.process,Ic=et.Dispatch,wM=et.Function,aS=et.MessageChannel,xM=et.String,Ec=0,Gs={},nS="onreadystatechange",Ys,Oi,wc,xc;lS(function(){Ys=et.location});var Rc=function(s){if(SM(Gs,s)){var e=Gs[s];delete Gs[s],e()}},kc=function(s){return function(){Rc(s)}},oS=function(s){Rc(s.data)},uS=function(s){et.postMessage(xM(s),Ys.protocol+"//"+Ys.host)};(!Pc||!Ac)&&(Pc=function(e){yM(arguments.length,1);var t=iS(e)?e:wM(e),i=vM(arguments,1);return Gs[++Ec]=function(){bM(t,void 0,i)},Oi(Ec),Ec},Ac=function(e){delete Gs[e]},IM?Oi=function(s){EM.nextTick(kc(s))}:Ic&&Ic.now?Oi=function(s){Ic.now(kc(s))}:aS&&!TM?(wc=new aS,xc=wc.port2,wc.port1.onmessage=oS,Oi=gM(xc.postMessage,xc)):et.addEventListener&&iS(et.postMessage)&&!et.importScripts&&Ys&&Ys.protocol!=="file:"&&!lS(uS)?(Oi=uS,et.addEventListener("message",oS,!1)):nS in sS("script")?Oi=function(s){rS.appendChild(sS("script"))[nS]=function(){rS.removeChild(this),Rc(s)}}:Oi=function(s){setTimeout(kc(s),0)});cS.exports={set:Pc,clear:Ac}});var hS=b((Aq,pS)=>{"use strict";var dS=se(),kM=Je(),PM=Object.getOwnPropertyDescriptor;pS.exports=function(s){if(!kM)return dS[s];var e=PM(dS,s);return e&&e.value}});var Mc=b((Rq,mS)=>{"use strict";var fS=function(){this.head=null,this.tail=null};fS.prototype={add:function(s){var e={item:s,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var s=this.head;if(s){var e=this.head=s.next;return e===null&&(this.tail=null),s.item}}};mS.exports=fS});var gS=b(($q,bS)=>{"use strict";var AM=Mi();bS.exports=/ipad|iphone|ipod/i.test(AM)&&typeof Pebble<"u"});var vS=b((Mq,SS)=>{"use strict";var RM=Mi();SS.exports=/web0s(?!.*chrome)/i.test(RM)});var kS=b((Lq,xS)=>{"use strict";var Pr=se(),$M=hS(),yS=gr(),Lc=$c().set,MM=Mc(),LM=Tc(),DM=gS(),BM=vS(),Dc=So(),TS=Pr.MutationObserver||Pr.WebKitMutationObserver,IS=Pr.document,ES=Pr.process,vo=Pr.Promise,Vc=$M("queueMicrotask"),kr,Bc,Cc,yo,wS;Vc||(Ks=new MM,Xs=function(){var s,e;for(Dc&&(s=ES.domain)&&s.exit();e=Ks.get();)try{e()}catch(t){throw Ks.head&&kr(),t}s&&s.enter()},!LM&&!Dc&&!BM&&TS&&IS?(Bc=!0,Cc=IS.createTextNode(""),new TS(Xs).observe(Cc,{characterData:!0}),kr=function(){Cc.data=Bc=!Bc}):!DM&&vo&&vo.resolve?(yo=vo.resolve(void 0),yo.constructor=vo,wS=yS(yo.then,yo),kr=function(){wS(Xs)}):Dc?kr=function(){ES.nextTick(Xs)}:(Lc=yS(Lc,Pr),kr=function(){Lc(Xs)}),Vc=function(s){Ks.head||kr(),Ks.add(s)});var Ks,Xs;xS.exports=Vc});var AS=b((Dq,PS)=>{"use strict";PS.exports=function(s,e){try{arguments.length===1?console.error(s):console.error(s,e)}catch{}}});var To=b((Bq,RS)=>{"use strict";RS.exports=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}}});var Ni=b((Cq,$S)=>{"use strict";var CM=se();$S.exports=CM.Promise});var Ar=b((Vq,BS)=>{"use strict";var VM=se(),Js=Ni(),_M=ae(),OM=El(),NM=gc(),FM=xe(),MS=mc(),UM=bt(),_c=cl(),LS=Js&&Js.prototype,qM=FM("species"),Oc=!1,DS=_M(VM.PromiseRejectionEvent),jM=OM("Promise",function(){var s=NM(Js),e=s!==String(Js);if(!e&&_c===66||UM&&!(LS.catch&&LS.finally))return!0;if(!_c||_c<51||!/native code/.test(s)){var t=new Js(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[qM]=i,Oc=t.then(function(){})instanceof i,!Oc)return!0}return!e&&(MS==="BROWSER"||MS==="DENO")&&!DS});BS.exports={CONSTRUCTOR:jM,REJECTION_EVENT:DS,SUBCLASSING:Oc}});var Rr=b((_q,VS)=>{"use strict";var CS=kt(),HM=TypeError,zM=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw new HM("Bad Promise constructor");e=i,t=r}),this.resolve=CS(e),this.reject=CS(t)};VS.exports.f=function(s){return new zM(s)}});var iv=b(()=>{"use strict";var QM=ue(),WM=bt(),xo=So(),oi=se(),GM=$i(),Dr=Ze(),_S=xr(),OS=lc(),YM=js(),KM=Og(),XM=kt(),wo=ae(),JM=ze(),ZM=Fg(),eL=yc(),jS=$c().set,jc=kS(),tL=AS(),iL=To(),rL=Mc(),HS=Kl(),ko=Ni(),Hc=Ar(),zS=Rr(),Po="Promise",QS=Hc.CONSTRUCTOR,sL=Hc.REJECTION_EVENT,aL=Hc.SUBCLASSING,Nc=HS.getterFor(Po),nL=HS.set,$r=ko&&ko.prototype,Fi=ko,Io=$r,WS=oi.TypeError,Fc=oi.document,zc=oi.process,Uc=zS.f,oL=Uc,uL=!!(Fc&&Fc.createEvent&&oi.dispatchEvent),GS="unhandledrejection",lL="rejectionhandled",NS=0,YS=1,cL=2,Qc=1,KS=2,Eo,FS,XS,US,JS=function(s){var e;return JM(s)&&wo(e=s.then)?e:!1},ZS=function(s,e){var t=e.value,i=e.state===YS,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,l,p;try{r?(i||(e.rejection===KS&&pL(e),e.rejection=Qc),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),p=!0)),u===s.promise?n(new WS("Promise-chain cycle")):(l=JS(u))?Dr(l,u,a,n):a(u)):n(t)}catch(c){o&&!p&&o.exit(),n(c)}},ev=function(s,e){s.notified||(s.notified=!0,jc(function(){for(var t=s.reactions,i;i=t.get();)ZS(i,s);s.notified=!1,e&&!s.rejection&&dL(s)}))},tv=function(s,e,t){var i,r;uL?(i=Fc.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),oi.dispatchEvent(i)):i={promise:e,reason:t},!sL&&(r=oi["on"+s])?r(i):s===GS&&tL("Unhandled promise rejection",t)},dL=function(s){Dr(jS,oi,function(){var e=s.facade,t=s.value,i=qS(s),r;if(i&&(r=iL(function(){xo?zc.emit("unhandledRejection",t,e):tv(GS,e,t)}),s.rejection=xo||qS(s)?KS:Qc,r.error))throw r.value})},qS=function(s){return s.rejection!==Qc&&!s.parent},pL=function(s){Dr(jS,oi,function(){var e=s.facade;xo?zc.emit("rejectionHandled",e):tv(lL,e,s.value)})},Mr=function(s,e,t){return function(i){s(e,i,t)}},Lr=function(s,e,t){s.done||(s.done=!0,t&&(s=t),s.value=e,s.state=cL,ev(s,!0))},qc=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw new WS("Promise can't be resolved itself");var i=JS(e);i?jc(function(){var r={done:!1};try{Dr(i,e,Mr(qc,r,s),Mr(Lr,r,s))}catch(a){Lr(r,a,s)}}):(s.value=e,s.state=YS,ev(s,!1))}catch(r){Lr({done:!1},r,s)}}};if(QS&&(Fi=function(e){ZM(this,Io),XM(e),Dr(Eo,this);var t=Nc(this);try{e(Mr(qc,t),Mr(Lr,t))}catch(i){Lr(t,i)}},Io=Fi.prototype,Eo=function(e){nL(this,{type:Po,done:!1,notified:!1,parent:!1,reactions:new rL,rejection:!1,state:NS,value:null})},Eo.prototype=_S(Io,"then",function(e,t){var i=Nc(this),r=Uc(eL(this,Fi));return i.parent=!0,r.ok=wo(e)?e:!0,r.fail=wo(t)&&t,r.domain=xo?zc.domain:void 0,i.state===NS?i.reactions.add(r):jc(function(){ZS(r,i)}),r.promise}),FS=function(){var s=new Eo,e=Nc(s);this.promise=s,this.resolve=Mr(qc,e),this.reject=Mr(Lr,e)},zS.f=Uc=function(s){return s===Fi||s===XS?new FS(s):oL(s)},!WM&&wo(ko)&&$r!==Object.prototype)){US=$r.then,aL||_S($r,"then",function(e,t){var i=this;return new Fi(function(r,a){Dr(US,i,r,a)}).then(e,t)},{unsafe:!0});try{delete $r.constructor}catch{}OS&&OS($r,Io)}QM({global:!0,constructor:!0,wrap:!0,forced:QS},{Promise:Fi});XS=GM.Promise;YM(Fi,Po,!1,!0);KM(Po)});var ov=b((Fq,nv)=>{"use strict";var hL=xe(),sv=hL("iterator"),av=!1;try{rv=0,Wc={next:function(){return{done:!!rv++}},return:function(){av=!0}},Wc[sv]=function(){return this},Array.from(Wc,function(){throw 2})}catch{}var rv,Wc;nv.exports=function(s,e){try{if(!e&&!av)return!1}catch{return!1}var t=!1;try{var i={};i[sv]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch{}return t}});var Gc=b((Uq,uv)=>{"use strict";var fL=Ni(),mL=ov(),bL=Ar().CONSTRUCTOR;uv.exports=bL||!mL(function(s){fL.all(s).then(void 0,function(){})})});var lv=b(()=>{"use strict";var gL=ue(),SL=Ze(),vL=kt(),yL=Rr(),TL=To(),IL=mo(),EL=Gc();gL({target:"Promise",stat:!0,forced:EL},{all:function(e){var t=this,i=yL.f(t),r=i.resolve,a=i.reject,n=TL(function(){var o=vL(t.resolve),u=[],l=0,p=1;IL(e,function(c){var d=l++,h=!1;p++,SL(o,t,c).then(function(f){h||(h=!0,u[d]=f,--p||r(u))},a)}),--p||r(u)});return n.error&&a(n.value),i.promise}})});var dv=b(()=>{"use strict";var wL=ue(),xL=bt(),kL=Ar().CONSTRUCTOR,Kc=Ni(),PL=Vt(),AL=ae(),RL=xr(),cv=Kc&&Kc.prototype;wL({target:"Promise",proto:!0,forced:kL,real:!0},{catch:function(s){return this.then(void 0,s)}});!xL&&AL(Kc)&&(Yc=PL("Promise").prototype.catch,cv.catch!==Yc&&RL(cv,"catch",Yc,{unsafe:!0}));var Yc});var pv=b(()=>{"use strict";var $L=ue(),ML=Ze(),LL=kt(),DL=Rr(),BL=To(),CL=mo(),VL=Gc();$L({target:"Promise",stat:!0,forced:VL},{race:function(e){var t=this,i=DL.f(t),r=i.reject,a=BL(function(){var n=LL(t.resolve);CL(e,function(o){ML(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}})});var hv=b(()=>{"use strict";var _L=ue(),OL=Rr(),NL=Ar().CONSTRUCTOR;_L({target:"Promise",stat:!0,forced:NL},{reject:function(e){var t=OL.f(this),i=t.reject;return i(e),t.promise}})});var Xc=b((Kq,fv)=>{"use strict";var FL=Pt(),UL=ze(),qL=Rr();fv.exports=function(s,e){if(FL(s),UL(e)&&e.constructor===s)return e;var t=qL.f(s),i=t.resolve;return i(e),t.promise}});var gv=b(()=>{"use strict";var jL=ue(),HL=Vt(),mv=bt(),zL=Ni(),bv=Ar().CONSTRUCTOR,QL=Xc(),WL=HL("Promise"),GL=mv&&!bv;jL({target:"Promise",stat:!0,forced:mv||bv},{resolve:function(e){return QL(GL&&this===WL?zL:this,e)}})});var Sv=b(()=>{"use strict";iv();lv();dv();pv();hv();gv()});var Iv=b(()=>{"use strict";var YL=ue(),KL=bt(),Ao=Ni(),XL=be(),yv=Vt(),Tv=ae(),JL=yc(),vv=Xc(),ZL=xr(),Zc=Ao&&Ao.prototype,eD=!!Ao&&XL(function(){Zc.finally.call({then:function(){}},function(){})});YL({target:"Promise",proto:!0,real:!0,forced:eD},{finally:function(s){var e=JL(this,yv("Promise")),t=Tv(s);return this.then(t?function(i){return vv(e,s()).then(function(){return i})}:s,t?function(i){return vv(e,s()).then(function(){throw i})}:s)}});!KL&&Tv(Ao)&&(Jc=yv("Promise").prototype.finally,Zc.finally!==Jc&&ZL(Zc,"finally",Jc,{unsafe:!0}));var Jc});var wv=b((rj,Ev)=>{"use strict";Mg();Sv();Iv();var tD=ri();Ev.exports=tD("Promise","finally")});var kv=b((sj,xv)=>{"use strict";var iD=wv();xv.exports=iD});var Ro=b((aj,Pv)=>{"use strict";var rD=kv();Pv.exports=rD});var Qv=b(()=>{"use strict";var MD=ue(),LD=mr(),DD=Tr(),BD=Cs(),CD=Vs();MD({target:"Array",proto:!0},{at:function(e){var t=LD(this),i=DD(t),r=BD(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});CD("at")});var Gv=b((nH,Wv)=>{"use strict";Qv();var VD=ri();Wv.exports=VD("Array","at")});var Kv=b((oH,Yv)=>{"use strict";var _D=Gv();Yv.exports=_D});var Ge=b((uH,Xv)=>{"use strict";var OD=Kv();Xv.exports=OD});var Ld=b((TQ,Hy)=>{"use strict";var UB=Ai();Hy.exports=Array.isArray||function(e){return UB(e)==="Array"}});var Qy=b((IQ,zy)=>{"use strict";var qB=TypeError,jB=9007199254740991;zy.exports=function(s){if(s>jB)throw qB("Maximum allowed index exceeded");return s}});var Yy=b((EQ,Gy)=>{"use strict";var HB=Ld(),zB=Tr(),QB=Qy(),WB=gr(),Wy=function(s,e,t,i,r,a,n,o){for(var u=r,l=0,p=n?WB(n,o):!1,c,d;l<i;)l in t&&(c=p?p(t[l],l,e):t[l],a>0&&HB(c)?(d=zB(c),u=Wy(s,e,c,d,u,a-1)-1):(QB(u+1),s[u]=c),u++),l++;return u};Gy.exports=Wy});var Zy=b((wQ,Jy)=>{"use strict";var Ky=Ld(),GB=vc(),YB=ze(),KB=xe(),XB=KB("species"),Xy=Array;Jy.exports=function(s){var e;return Ky(s)&&(e=s.constructor,GB(e)&&(e===Xy||Ky(e.prototype))?e=void 0:YB(e)&&(e=e[XB],e===null&&(e=void 0))),e===void 0?Xy:e}});var tT=b((xQ,eT)=>{"use strict";var JB=Zy();eT.exports=function(s,e){return new(JB(s))(e===0?0:e)}});var iT=b(()=>{"use strict";var ZB=ue(),eC=Yy(),tC=kt(),iC=mr(),rC=Tr(),sC=tT();ZB({target:"Array",proto:!0},{flatMap:function(e){var t=iC(this),i=rC(t),r;return tC(e),r=sC(t,0),r.length=eC(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var rT=b(()=>{"use strict";var aC=Vs();aC("flatMap")});var aT=b(($Q,sT)=>{"use strict";iT();rT();var nC=ri();sT.exports=nC("Array","flatMap")});var oT=b((MQ,nT)=>{"use strict";var oC=aT();nT.exports=oC});var Wi=b((LQ,uT)=>{"use strict";var uC=oT();uT.exports=uC});var fa=b((WQ,pT)=>{"use strict";var cC=qs(),dC=String;pT.exports=function(s){if(cC(s)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return dC(s)}});var Bd=b((GQ,hT)=>{"use strict";hT.exports=`
7
+ \v\f\r                 \u2028\u2029\uFEFF`});var bT=b((YQ,mT)=>{"use strict";var pC=ge(),hC=ii(),fC=fa(),Vd=Bd(),fT=pC("".replace),mC=RegExp("^["+Vd+"]+"),bC=RegExp("(^|[^"+Vd+"])["+Vd+"]+$"),Cd=function(s){return function(e){var t=fC(hC(e));return s&1&&(t=fT(t,mC,"")),s&2&&(t=fT(t,bC,"$1")),t}};mT.exports={start:Cd(1),end:Cd(2),trim:Cd(3)}});var yT=b((KQ,vT)=>{"use strict";var gC=Zl().PROPER,SC=be(),gT=Bd(),ST="​…᠎";vT.exports=function(s){return SC(function(){return!!gT[s]()||ST[s]()!==ST||gC&&gT[s].name!==s})}});var _d=b((XQ,TT)=>{"use strict";var vC=bT().start,yC=yT();TT.exports=yC("trimStart")?function(){return vC(this)}:"".trimStart});var ET=b(()=>{"use strict";var TC=ue(),IT=_d();TC({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==IT},{trimLeft:IT})});var xT=b(()=>{"use strict";ET();var IC=ue(),wT=_d();IC({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==wT},{trimStart:wT})});var PT=b((iW,kT)=>{"use strict";xT();var EC=ri();kT.exports=EC("String","trimLeft")});var RT=b((rW,AT)=>{"use strict";var wC=PT();AT.exports=wC});var MT=b((sW,$T)=>{"use strict";var xC=RT();$T.exports=xC});var CT=b(()=>{"use strict"});var VT=b(()=>{"use strict"});var OT=b((UW,_T)=>{"use strict";var AC=ze(),RC=Ai(),$C=xe(),MC=$C("match");_T.exports=function(s){var e;return AC(s)&&((e=s[MC])!==void 0?!!e:RC(s)==="RegExp")}});var UT=b((qW,FT)=>{"use strict";var LC=se(),DC=be(),NT=LC.RegExp,BC=!DC(function(){var s=!0;try{NT(".","d")}catch{s=!1}var e={},t="",i=s?"dgimsy":"gimsy",r=function(u,l){Object.defineProperty(e,u,{get:function(){return t+=l,!0}})},a={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};s&&(a.hasIndices="d");for(var n in a)r(n,a[n]);var o=Object.getOwnPropertyDescriptor(NT.prototype,"flags").get.call(e);return o!==i||t!==i});FT.exports={correct:BC}});var jT=b((jW,qT)=>{"use strict";var CC=Pt();qT.exports=function(){var s=CC(this),e="";return s.hasIndices&&(e+="d"),s.global&&(e+="g"),s.ignoreCase&&(e+="i"),s.multiline&&(e+="m"),s.dotAll&&(e+="s"),s.unicode&&(e+="u"),s.unicodeSets&&(e+="v"),s.sticky&&(e+="y"),e}});var QT=b((HW,zT)=>{"use strict";var VC=Ze(),_C=gt(),OC=Rs(),HT=UT(),NC=jT(),FC=RegExp.prototype;zT.exports=HT.correct?function(s){return s.flags}:function(s){return!HT.correct&&OC(FC,s)&&!_C(s,"flags")?VC(NC,s):s.flags}});var GT=b((zW,WT)=>{"use strict";var qd=ge(),UC=mr(),qC=Math.floor,Fd=qd("".charAt),jC=qd("".replace),Ud=qd("".slice),HC=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,zC=/\$([$&'`]|\d{1,2})/g;WT.exports=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=zC;return r!==void 0&&(r=UC(r),u=HC),jC(a,u,function(l,p){var c;switch(Fd(p,0)){case"$":return"$";case"&":return s;case"`":return Ud(e,0,t);case"'":return Ud(e,n);case"<":c=r[Ud(p,1,-1)];break;default:var d=+p;if(d===0)return l;if(d>o){var h=qC(d/10);return h===0?l:h<=o?i[h-1]===void 0?Fd(p,1):i[h-1]+Fd(p,1):l}c=i[d-1]}return c===void 0?"":c})}});var XT=b(()=>{"use strict";var QC=ue(),WC=Ze(),Hd=ge(),YT=ii(),GC=ae(),YC=ze(),KC=OT(),Kr=fa(),XC=Ms(),JC=QT(),ZC=GT(),eV=xe(),tV=bt(),iV=eV("replace"),rV=TypeError,jd=Hd("".indexOf),sV=Hd("".replace),KT=Hd("".slice),aV=Math.max;QC({target:"String",proto:!0},{replaceAll:function(e,t){var i=YT(this),r,a,n,o,u,l,p,c,d,h,f=0,m="";if(YC(e)){if(r=KC(e),r&&(a=Kr(YT(JC(e))),!~jd(a,"g")))throw new rV("`.replaceAll` does not allow non-global regexes");if(n=XC(e,iV),n)return WC(n,e,i,t);if(tV&&r)return sV(Kr(i),e,t)}for(o=Kr(i),u=Kr(e),l=GC(t),l||(t=Kr(t)),p=u.length,c=aV(1,p),d=jd(o,u);d!==-1;)h=l?Kr(t(u,d,o)):ZC(u,o,d,[],void 0,t),m+=KT(o,f,d)+h,f=d+p,d=d+c>o.length?-1:jd(o,u,d+c);return f<o.length&&(m+=KT(o,f)),m}})});var ZT=b((GW,JT)=>{"use strict";CT();VT();XT();var nV=ri();JT.exports=nV("String","replaceAll")});var tI=b((YW,eI)=>{"use strict";var oV=ZT();eI.exports=oV});var rI=b((KW,iI)=>{"use strict";var uV=tI();iI.exports=uV});var aI=b((XW,sI)=>{"use strict";var lV=Cs(),cV=fa(),dV=ii(),pV=RangeError;sI.exports=function(e){var t=cV(dV(this)),i="",r=lV(e);if(r<0||r===1/0)throw new pV("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var cI=b((JW,lI)=>{"use strict";var uI=ge(),hV=$l(),nI=fa(),fV=aI(),mV=ii(),bV=uI(fV),gV=uI("".slice),SV=Math.ceil,oI=function(s){return function(e,t,i){var r=nI(mV(e)),a=hV(t),n=r.length,o=i===void 0?" ":nI(i),u,l;return a<=n||o===""?r:(u=a-n,l=bV(o,SV(u/o.length)),l.length>u&&(l=gV(l,0,u)),s?r+l:l+r)}};lI.exports={start:oI(!1),end:oI(!0)}});var pI=b((ZW,dI)=>{"use strict";var vV=Mi();dI.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(vV)});var hI=b(()=>{"use strict";var yV=ue(),TV=cI().start,IV=pI();yV({target:"String",proto:!0,forced:IV},{padStart:function(e){return TV(this,e,arguments.length>1?arguments[1]:void 0)}})});var mI=b((iG,fI)=>{"use strict";hI();var EV=ri();fI.exports=EV("String","padStart")});var gI=b((rG,bI)=>{"use strict";var wV=mI();bI.exports=wV});var vI=b((sG,SI)=>{"use strict";var xV=gI();SI.exports=xV});var dh="2.0.149";var we=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(we||{}),Ct=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_FMP4="HLS_FMP4",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(Ct||{});var ws=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(ws||{}),Ju=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Ju||{});var Zu=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Zu||{}),Fn=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Fn||{});var uh=D(Di(),1),Vw=D(ke(),1);import{assertNever as Dm,assertNonNullable as UP,isNonNullable as Gn,ValueSubject as Vl,Subject as qP,Subscription as jP,merge as HP,observableFrom as zP,fromEvent as Rm,map as $m,tap as Mm,filterChanged as QP,isNullable as _l,ErrorCategory as Lm}from"@vkontakte/videoplayer-shared/es2024";var Am=s=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var Yn=class{constructor(e){this.connection$=new Vl(void 0);this.castState$=new Vl("NOT_AVAILABLE");this.errorEvent$=new qP;this.realCastState$=new Vl("NOT_AVAILABLE");this.subscription=new jP;this.isDestroyed=!1;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=Gn(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=a=>{delete window.__onGCastApiAvailable,a&&!this.isDestroyed&&this.initializeCastApi()},r||Am("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Lm.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(){Gn(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();_l(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();_l(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(Rm(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{switch(r.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 Dm(r.sessionState)}})).add(HP(Rm(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Mm(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),$m(r=>r.castState)),zP([i.getCastState()])).pipe(QP(),$m(WP),Mm(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let a=r==="CONNECTED",n=Gn(this.connection$.getValue());if(a&&!n){let o=i.getCurrentSession();UP(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;(_l(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!a&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?Gn(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}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(r){this.errorEvent$.next({id:"ChromecastInitializer",category:Lm.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},WP=s=>{switch(s){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 Dm(s)}};import{assertNonNullable as Fl,combine as Ul,debounce as ql,ErrorCategory as oA,filter as Er,filterChanged as zm,isNonNullable as jl,isNullable as Qm,map as uA,Subscription as lA,ValueSubject as Hl}from"@vkontakte/videoplayer-shared/es2024";import{assertNever as GP,assertNonNullable as Bi,ErrorCategory as YP,getHighestQuality as KP,isNonNullable as Cm}from"@vkontakte/videoplayer-shared/es2024";import{assertNever as Bm}from"@vkontakte/videoplayer-shared/es2024";var ne=(s,e=0,t=0)=>{switch(t){case 0:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return s;let i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(s);return!i.searchParams.get("offset_p")&&e===0?s:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:Bm(t)}return s},si=(s,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(s);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(s);return Number(t.searchParams.get("offset_p")??0)}default:Bm(e)}};var Xn=s=>{let{source:e,format:t,meta:i,output:r}=s,a,n,o;switch(t){case"MPEG":{let c=e[t];Bi(c);let d=KP(Object.keys(c));Bi(d);let h=c[d];Bi(h),a=h,n="video/mp4",o=Kn();break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let c=e[t];Bi(c),a=c.url,n="application/x-mpegurl",o=Kn();break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=e[t];Bi(c),a=c.url,n="application/dash+xml",o=Kn();break}case"DASH_LIVE_CMAF":{let c=e[t];Bi(c),a=c.url,n="application/dash+xml",o=Vm();break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=e[t];Bi(c),a=ne(c.url),n="application/x-mpegurl",o=Vm();break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw r.error$.next({id:"ChromecastProvider.createMediaInfo()",category:YP.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${t} is no longer supported`);default:return GP(t)}let u=XP(i.videoId??a,n);u.contentUrl=a,u.streamType=o,u.metadata=JP();let{title:l,subtitle:p}=i;return Cm(l)&&(u.metadata.title=l),Cm(p)&&(u.metadata.subtitle=p),u};function Kn(){return chrome.cast?.media?.StreamType?.BUFFERED??"BUFFERED"}function Vm(){return chrome.cast?.media?.StreamType?.LIVE??"LIVE"}function XP(s,e){return chrome.cast?.media?.MediaInfo?new chrome.cast.media.MediaInfo(s,e):{contentId:s,contentType:e,metadata:{title:"",subtitle:""},streamType:Kn()}}function JP(){return chrome.cast?.media?.GenericMediaMetadata?new chrome.cast.media.GenericMediaMetadata:{images:[],metadataType:0,releaseDate:"",subtitle:"",title:"",releaseYear:1970,type:0}}var P=(s,e,t=!1)=>{let i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};var Jn=class{constructor(e){this.interval=0;this.params=e}start(e=0){clearInterval(this.interval),this.startVideoPosition=e,this.startTs=Date.now(),this.interval=window.setInterval(()=>{let t=(Date.now()-this.startTs)/1e3,i=this.startVideoPosition+t;this.params.output.position$.next(i)},1e3)}pause(){clearInterval(this.interval)}destroy(){clearInterval(this.interval)}};import{assertNever as Hm}from"@vkontakte/videoplayer-shared/es2024";var _m=D(ke(),1);var Zn=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isChromiumBased(){return(0,_m.default)(["Chrome","Chromium","Opera","Yandex","Edge","SamsungBrowser"],this.current)}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,a=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||l||r||a||o||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],a=parseInt(r,10);if(!isNaN(a))return this._current_version=a,a}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var Om=D(ke(),1);var Ci=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var eo=class{constructor(e){this._highEntropyValues={};this._os={name:"Unknown",version:"Unknown",full:"Unknown"};this._details={vendor:"Unknown",model:"Unknown"};this._displayChecker=e}get current(){return this._current}get os(){return this._os}get details(){return this._details}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||this.os.name.toLowerCase().includes("ios")||(0,Om.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.os.name.toLowerCase().includes("mac")||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.os.name.toLowerCase().includes("android")||this.current==="Android"}get isWindows(){return this.os.name.toLowerCase().includes("windows")}get isLinux(){return this.os.name.toLowerCase().includes("linux")&&!this.isAndroid}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=Ci()}catch(t){console.error("DeviceChecker: calling isMobile error - ",t)}this.detectDevice(e),this.detectOS(e),this.detectDeviceDetails(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e?.getHighEntropyValues){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t,t.platform&&(this._os.name=this.normalizeOSName(t.platform),t.platformVersion&&(this._os.version=this.normalizeOSVersion(t.platformVersion),this._os.full=`${this._os.name} ${this._os.version}`)),t.model&&(this._details.model=t.model)}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,a=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||a||o||n||"Desktop"}catch(t){console.error("DeviceChecker: device detection error - ",t)}}detectOS(e){try{let t=[[/(windows nt) (6\.[23]); arm/i,["Windows RT"]],[/(windows nt) (6\.3); arm/i,["Windows RT 8.1"]],[/(windows (?:phone|mobile|iot))(?: os)?[/ ]?([\d.]+)/i,["Windows Mobile",2]],[/(windows)[/ ](xp|vista|7|8(\.1)?|10|11|2000|me)/i,[1,1]],[/windows nt ?([\d.]+)/i,["Windows",1]],[/(windows)[/ ](95|98|me|2000|xp|vista|7|8|8\.1|10|11)/i,[1,2]],[/(iphone os|cpu iphone os) ([\d_.]+)/i,["iOS",2]],[/(ipad os|cpu os) ([\d_.]+)/i,["iPadOS",2]],[/(ipod os|cpu ipod os) ([\d_.]+)/i,["iOS",2]],[/(?:ios|os) ([\d_.]+) like mac os x/i,["iOS",1]],[/cfnetwork\/.+darwin/i,["iOS"]],[/(mac os x) ?([\d_.]+)/i,["macOS",2]],[/(macintosh|mac os)/i,["macOS"]],[/(android) ([\d.]+)/i,[1,2]],[/(harmonyos)[/ ]?([\d.]*)/i,["HarmonyOS",2]],[/\b(ubuntu|debian|fedora|centos|arch|linux)(?:[-/ ]([\w.]+))?/i,[1,2]],[/(cros)\D*([\d.]+)/i,["Chrome OS",2]],[/(freebsd|openbsd|netbsd|dragonfly)[/ ]?([\w.]*)/i,[1,2]],[/(sunos|solaris)?([\d.]*)/i,["Solaris",2]],[/(aix)?([\d.]*)/i,["AIX",2]]];for(let[i,r]of t){let a=e.match(i);if(a){let n=r.length>0,o=r.length>1,u="Unknown",l="Unknown";if(n){let p=r[0];typeof p=="number"?p<a.length&&a[p]!==void 0&&(u=a[p]):u=p}if(o){let p=r[1];typeof p=="number"?p<a.length&&a[p]!==void 0&&(l=a[p]):p!==void 0&&(l=p)}else a[2]!==void 0?l=a[2]:a[1]!==void 0&&n&&typeof r[0]=="string"&&(l=a[1]);u=this.normalizeOSName(u),l=this.normalizeOSVersion(l,u),u==="iOS"&&/ipad/i.test(e)?u="iPadOS":u==="iPadOS"&&/ip(hone|od)/i.test(e)&&(u="iOS"),this._os={name:u,version:l||"Unknown",full:l&&l!=="Unknown"?`${u} ${l}`:u};break}}}catch(t){console.error("DeviceChecker: OS detection error - ",t)}}normalizeOSName(e){if(!e)return"Unknown";let t=e.toLowerCase();return t.includes("windows")?"Windows":t.includes("mac os")||t.includes("macintosh")?"macOS":t.includes("iphone")||t.includes("ios")?"iOS":t.includes("ipados")?"iPadOS":t.includes("android")?"Android":t.includes("harmonyos")?"HarmonyOS":t.includes("linux")?"Linux":t.includes("cros")?"Chrome OS":t.includes("freebsd")?"FreeBSD":t.includes("openbsd")?"OpenBSD":t.includes("solaris")||t.includes("sunos")?"Solaris":t.includes("aix")?"AIX":e}normalizeOSVersion(e,t){if(!e)return"Unknown";if(e!=="Unknown"&&(e=e.replace(/_/g,"."),t==="Windows")){let i=parseFloat(e);if(!isNaN(i)){if(i>=11)return"11";if(i>=10)return"10";if(i===6.3)return"8.1";if(i===6.2)return"8";if(i===6.1)return"7";if(i===6)return"Vista";if(i===5.1||i===5.2)return"XP";if(i===5)return"2000";if(i===4)return"NT 4.0"}}return e}detectDeviceDetails(e){try{let t=[[/(iphone)/i,["Apple","iPhone"]],[/(ipad)/i,["Apple","iPad"]],[/(ipod)/i,["Apple","iPod"]],[/(macintosh)/i,["Apple","Macintosh"]],[/(windows[\w\-_ ]*phone)/i,["Microsoft",0]],[/(windows nt|win64|win32|wow64)/i,["Microsoft","PC"]],[/\b(sch-i[89]0\d|shw-m380s|sm-[ptxs]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i,["Samsung",1]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?\d+a?|galaxy nexus)/i,["Samsung",1]],[/samsung[- ]((?!sm-[lr]|browser)[-\w]+)/i,["Samsung",1]],[/sec-(sgh\w+)/i,["Samsung",1]],[/smart-tv.+(samsung)/i,["Samsung","Smart TV"]],[/(samsung).*tizen/i,["Samsung","Smart TV"]],[/(pixel (?:c|tablet|[0-9a-z ]+))/i,["Google",1]],[/(pixelbook(?: go)?)/i,["Google",1]],[/nexus [0-9]/i,["Google",0]],[/(redmi[-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(mi[\w\-_ ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(poco[\w ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(hm[-_ ]?note?[\w ]*)(?: bui|\))/i,["Xiaomi",1]],[/\b(?:xiao)?mi[\w\-_ ]+pad/i,["Xiaomi",0]],[/(?:huawei|honor) ?([-\w ]+)[;)]/i,["Huawei",1]],[/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][\dc][adnt]?)\b(?!.+d\/s)/i,["Huawei",1]],[/\b((?:ag[rs][2356]?k?|bah[234]?|bg[2o]|bt[kv]|cmr|cpn|db[ry]2?|jdn2|got|kob2?k?|mon|pce|scm|sht?|[tw]gr|vrd)-[ad]?[lw][0125][09]b?)/i,["Huawei",1]],[/(?:one)?(?:plus)? ?([a\d0]\d\d\d?)(?: b|\))/i,["OnePlus",1]],[/droid.+; (cph2[3-6]\d[13579]|((?:gm|hd)19|(?:ac|be|in|kb)20|(?:d[en]|eb|le|mt)21|ne22)[0-2]\d)(?: bui|\))/i,["OnePlus",1]],[/(oneplus)[-_ ]?([-\w]*)/i,["OnePlus",2]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i,["Realme",1]],[/(realme)[-_ ]?([-\w]*)/i,["Realme",2]],[/; (\w+) bui.+ oppo/i,["OPPO",1]],[/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i,["OPPO",1]],[/\b(opd2(\d{3}a?))(?: bui|\))/i,["OPPO",1]],[/(oppo)[-_ ]?([-\w]*)/i,["OPPO",2]],[/; vivo (\w+)(?: bui|\))/i,["Vivo",1]],[/\b(v[12]\d{3}\w?[at])(?: bui|;)/i,["Vivo",1]],[/(vivo)[-_ ]?([-\w]*)/i,["Vivo",2]],[/\bmot(?:orola)?[- ]([\w\s]+)(\)| bui)/i,["Motorola",1]],[/((?:moto(?! 360)[-\w() ]+|xt\d{3,4}[cgkosw+]?[-\d]*|nexus 6)(?= bui|\)))/i,["Motorola",1]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b/i,["Motorola",0]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i,["Motorola",0]],[/droid.+; ([a-z]?\d[0-2]{2}[a-z]{2}|[c-g]\d{4}|so[-gl]\w+|xq-[a-z]{2}\d\d)(?= bui|\))/i,["Sony",1]],[/sony tablet [ps]/i,["Sony","Xperia Tablet"]],[/\b(?:sony)?sgp\w+(?: bui|\))/i,["Sony",0]],[/(sony)[-_ ]?([-\w]*)/i,["Sony",2]],[/\blg[-e;/ ]+(?!.*(?:browser|netcast|android tv|watch|webos))(\w+)/i,["LG",1]],[/\blg-?([\d\w]+) bui/i,["LG",1]],[/(lm(?:-?f100[nv]?|-[\w.]+)(?= bui|\))|nexus [45])/i,["LG",1]],[/((?=lg)?[vl]k-?\d{3}) bui/i,["LG",0]],[/(lg)[-_ ]?([-\w]*)/i,["LG",2]],[/(?:maemo|nokia).*(n900|lumia \d+|rm-\d+)/i,["Nokia",1]],[/nokia[-_ ]?(([-\w. ]*?))(?: bui|\)|;|\/)/i,["Nokia",1]],[/(nokia) (t[12][01])/i,["Nokia",2]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i,["ASUS",1]],[/(?:asus[-_ ])?(zenfone[\w\-_ ]*)/i,["ASUS",1]],[/(rog[\w\-_ ]*)/i,["ASUS",1]],[/(asus)[-_ ]?([-\w]*)/i,["ASUS",2]],[/lenovo[-_ ]?([-\w ]+?)(?: bui|\)|\/)/i,["Lenovo",1]],[/(ideatab[-\w ]+|602lv|d-42a|a101lv|a2109a|a3500-hv|s[56]000|pb-6505[my]|tb-?x?\d{3,4}(?:f[cu]|xu|[av])|yt\d?-[jx]?\d+[lfmx])(?: bui|;|\)|\/)/i,["Lenovo",1]],[/(thinkpad[\w\-_ ]*)/i,["Lenovo",0]],[/(kf[a-z]{2}[a-z]*)(?: bui|\))/i,["Amazon",1]],[/(alexa)webm/i,["Amazon","Echo"]],[/(fire[\w\-_ ]*)/i,["Amazon",0]],[/(amazon)[-_ ]?([-\w]*)/i,["Amazon",2]],[/(?:blackberry|\(bb10;) (\w+)/i,["BlackBerry",1]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,["BlackBerry",1]],[/(playbook);[-\w),; ]+(rim)/i,["BlackBerry",1]],[/(microsoft); (lumia[\w ]+)/i,["Microsoft",2]],[/(surface duo)/i,["Microsoft","Surface Duo"]],[/(surface[\w\-_ ]*)/i,["Microsoft",0]],[/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,["ZTE",2]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,["HTC",2]],[/(alcatel|tcl)[-_ ]?([-\w]*)/i,[1,2]],[/(meizu)[-_ ]?([-\w]*)/i,["Meizu",2]],[/(tecno)[-_ ]?([-\w]*)/i,["Tecno",2]],[/(infinix)[-_ ]?([-\w]*)/i,["Infinix",2]],[/(micromax)[-_ ]?([-\w]*)/i,["Micromax",2]],[/(lava)[-_ ]?([-\w]*)/i,["Lava",2]],[/(panasonic)[-_ ]?([-\w]*)/i,["Panasonic",2]],[/(sharp)\/?([-\w]*)/i,["Sharp",2]],[/(benq)[-_ ]?([-\w]*)/i,["BenQ",2]],[/(palm)[-_ ]?([-\w]*)/i,["Palm",2]],[/(vertu)[-_ ]?([-\w]*)/i,["Vertu",2]],[/(gionee)[-_ ]?([-\w]*)/i,["Gionee",2]],[/(doogee)[-_ ]?([-\w]*)/i,["Doogee",2]],[/(ulefone)[-_ ]?([-\w]*)/i,["Ulefone",2]],[/(blackview)[-_ ]?([-\w]*)/i,["Blackview",2]],[/(cubot)[-_ ]?([-\w]*)/i,["Cubot",2]],[/(umidigi)[-_ ]?([-\w]*)/i,["UMIDIGI",2]],[/(oukitel)[-_ ]?([-\w]*)/i,["Oukitel",2]],[/(fairphone)[-_ ]?([-\w]*)/i,["Fairphone",2]],[/(cat)[-_ ]?([-\w]*)/i,["Cat",2]],[/(energy)[-_ ]?([-\w]*)/i,["Energizer",2]],[/(land rover)[-_ ]?([-\w]*)/i,["Land Rover",2]],[/(shield[\w\-_ ]*)/i,["Nvidia",0]],[/(crkey)/i,["Google","Chromecast"]],[/(roku)[\dx]*/i,["Roku",0]],[/(apple)[-_ ]?tv/i,["Apple","TV"]],[/(amazon)[-_ ]?tv/i,["Amazon","Fire TV"]],[/(google)[-_ ]?tv/i,["Google","TV"]],[/(smart[\w\-_ ]*tv)/i,[0,"Smart TV"]],[/(playstation[\w\-_ ]*)/i,["Sony",0]],[/(nintendo[\w\-_ ]*)/i,["Nintendo",0]],[/(xbox[\w\-_ ]*)/i,["Microsoft",0]],[/(googlebot)/i,["Google","Bot"]],[/(bingbot)/i,["Microsoft","Bing Bot"]],[/(yandexbot)/i,["Yandex","Bot"]],[/(slackbot)/i,["Slack","Bot"]],[/(twitterbot)/i,["Twitter","Bot"]],[/(facebookbot)/i,["Facebook","Bot"]],[/(linkedinbot)/i,["LinkedIn","Bot"]],[/(tesla)[-_ ]?([-\w]*)/i,["Tesla",2]],[/(raspberry[\w\-_ ]*)/i,["Raspberry Pi",0]]];for(let[i,r]of t){let a=e.match(i);if(a){let n=r[0],o=r[1],u=typeof n=="number"?a[n]!==void 0?this.normalizeVendorName(a[n]):"Unknown":this.normalizeVendorName(n),l="Unknown";typeof o=="number"?l=a[o]!==void 0?a[o]:"Unknown":o!==void 0?l=o:a[1]!==void 0?l=a[1]:a[0]!==void 0&&(l=a[0]),l=this.normalizeModelName(l,u),this.details.vendor=u,this.details.model=l;break}}}catch(t){console.error("DeviceChecker: device details detection error - ",t)}}normalizeVendorName(e){if(!e)return"Unknown";let t=e.toLowerCase();return{apple:"Apple",samsung:"Samsung",google:"Google",xiaomi:"Xiaomi",huawei:"Huawei",oneplus:"OnePlus",oppo:"OPPO",vivo:"Vivo",realme:"Realme",motorola:"Motorola",sony:"Sony",lg:"LG",nokia:"Nokia",asus:"ASUS",lenovo:"Lenovo",amazon:"Amazon",blackberry:"BlackBerry",microsoft:"Microsoft",zte:"ZTE",htc:"HTC",alcatel:"Alcatel",tcl:"TCL",meizu:"Meizu",tecno:"Tecno",infinix:"Infinix",micromax:"Micromax",lava:"Lava",panasonic:"Panasonic",sharp:"Sharp",benq:"BenQ",palm:"Palm",honor:"Honor",nvidia:"NVIDIA",roku:"Roku"}[t]||e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}normalizeModelName(e,t){if(!e||e==="Unknown")return e;if(e==="0")return"Unknown";let i=e.replace(/^build\//i,"").replace(/\s+bui$/i,"").replace(/\)$/,"").replace(/[;,)]/g,"").replace(/\s*\(.*?\)\s*/g,"").trim(),r=t.toLowerCase();return r.includes("samsung")?i=i.replace(/^(sm-|gt-|sgh-|sch-)/i,""):r.includes("xiaomi")?i=i.replace(/^(mi[\s\-_]*|redmi[\s\-_]*)/i,""):r.includes("oneplus")?i=i.replace(/^oneplus[\s\-_]*/i,""):r.includes("google")&&(i=i.replace(/^(pixel[\s\-_]*|nexus[\s\-_]*)/i,"")),i=i.replace(/_/g," ").replace(/-/g," ").replace(/\s+/g," ").trim(),i?(i.length>0&&/^[a-z]/.test(i)&&(i=i.charAt(0).toUpperCase()+i.slice(1)),i):"Unknown"}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let t=this._highEntropyValues.platformVersion.split(".").slice(0,2).join(".");this._iosVersion=parseFloat(t);return}if(this._os.version!=="Unknown"){let t=this._os.version.split("."),i=t.length>=2?`${t[0]}.${t[1]}`:t[0];this._iosVersion=parseFloat(i);return}let e=navigator.userAgent.match(/OS (\d+(_\d+)?)/i);e?.[1]&&(this._iosVersion=parseFloat(e[1].replace(/_/g,".")))}catch(e){console.error("DeviceChecker: iOS version detection error - ",e)}}};var to=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e??0,this._isHdr=!!matchMedia("(dynamic-range: high)")?.matches,this._colorDepth=screen.colorDepth}catch(t){console.error(t)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(t){console.error(t)}}};var Ve=()=>window.ManagedMediaSource||window.MediaSource,ai=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Nm=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),Ir=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var ZP=document.createElement("video"),eA='video/mp4; codecs="avc1.42000a,mp4a.40.2"',tA='video/mp4; codecs="hev1.1.6.L93.B0"',Fm='video/webm; codecs="vp09.00.10.08"',Um='video/webm; codecs="av01.0.00M.08"',iA='audio/mp4; codecs="mp4a.40.2"',rA='audio/webm; codecs="opus"',qm,sA=async()=>{if(!window.navigator.mediaCapabilities)return;let s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:Um}}),window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:Fm}})]);qm={DASH_WEBM_AV1:e,DASH_WEBM:t}};sA().catch(s=>{console.log(ZP),console.error(s)});var io=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return qm}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){this._video=document.createElement("video");try{this._protocols={mms:ai(),mse:Nm(),hls:!!(this._video.canPlayType?.("application/x-mpegurl")||this._video.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!this._video.canPlayType?.("video/mp4"),webm:!!this._video.canPlayType?.("video/webm"),cmaf:!0};let e=!!Ve()?.isTypeSupported?.(eA),t=!!Ve()?.isTypeSupported?.(tA),i=!!Ve()?.isTypeSupported?.(iA);this._codecs={h264:e,h265:t,vp9:!!Ve()?.isTypeSupported?.(Fm),av1:!!Ve()?.isTypeSupported?.(Um),aac:i,opus:!!Ve()?.isTypeSupported?.(rA),mpeg:(e||t)&&i},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(e){console.error(e)}try{this.destroyVideoElement()}catch(e){console.error("Error destroying video element:",e)}}destroyVideoElement(){if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);this._video.parentNode?.replaceChild(e,this._video),this._video=null}};var jm="audio/mpeg",ro=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){this._audio=document.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(jm)},this._codecs={mp3:!!Ve()?.isTypeSupported?.(jm)}}catch(e){console.error(e)}try{this.destroyAudioElement()}catch(e){console.error("Error destroying audio element:",e)}}destroyAudioElement(){if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);this._audio.parentNode?.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as aA}from"@vkontakte/videoplayer-shared/es2024";var Ol=class{constructor(){this.isInited$=new aA(!1);this._displayChecker=new to,this._deviceChecker=new eo(this._displayChecker),this._browserChecker=new Zn,this._videoChecker=new io(this._deviceChecker,this._browserChecker),this._audioChecker=new ro,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}async detect(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},$=new Ol;var Nl=s=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=$.video,a=(i.h264||i.h265)&&i.aac,n=t.mse||t.mms;return s.filter(o=>{switch(o){case"DASH_SEP":return n&&e.mp4&&a;case"DASH_WEBM":return n&&e.webm&&i.vp9&&i.opus;case"DASH_WEBM_AV1":return n&&e.webm&&i.av1&&i.opus;case"DASH_STREAMS":return n&&(e.mp4&&a||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return n&&e.mp4&&a;case"DASH_LIVE_CMAF":return n&&e.mp4&&a&&e.cmaf;case"DASH_ONDEMAND":return n&&e.mp4&&a;case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":case"HLS_LIVE":case"HLS_LIVE_CMAF":return r;case"MPEG":return e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return t.webrtc&&t.ws&&i.h264&&(e.mp4||e.webm);default:return Hm(o)}})},_s=s=>{switch(s){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_FMP4":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 Hm(s)}},nA=s=>{let t=Object.keys(s).filter(i=>!_s(i));return Nl(t).length>0};var Os=class{constructor(e){this.subscription=new lA;this.sessionId$=new Hl(null);this.mediaSessionId$=new Hl(null);this.contentId$=new Hl(null);this.isMobile=Ci();this.mobileVolumeState={muted:!1,volume:0};this.media=null;this.lastRequestedVolume=null;this.syncMediaState=e=>{if(Qm(e))return;this.media=e,this.mediaSessionId$.next(e.mediaSessionId??null);let t=e.media?.contentId;t&&this.contentId$.next(t),this.syncPlaybackState(e);let i=e.media?.duration;jl(i)&&this.params.output.duration$.next(Math.max(0,i));let r=e.currentTime;if(jl(r)){this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.params.output.position$.next(r);let n=this.params.output.isLive$.getValue();e.playerState==="PLAYING"&&!n?this.progressTicker.start(r):this.progressTicker.pause()}};this.params=e,this.progressTicker=new Jn(e),this.log=this.params.dependencies.logger.createComponentLog("ChromecastPresentationApiProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(_s(e.format)),this.subscribe()}subscribe(){let e=r=>{this.params.output.error$.next({category:oA.WTF,id:"ChromecastPresentationApiProvider",message:r?.message??"Unknown error",thrown:r})};this.subscription.add(this.params.chromecastConnector.message$.pipe(Er(r=>!!r)).subscribe(r=>{this.handleMessage(r)},e)),this.subscription.add(this.sessionId$.pipe(Er(jl),zm(),ql(0)).subscribe(()=>{this.loadMedia()},e));let t=this.contentId$.pipe(zm(),uA(Boolean));this.subscription.add(Ul({seekState:this.params.desiredState.seekState.stateChangeEnded$,mediaLoaded:t}).pipe(Er(({mediaLoaded:r})=>r)).subscribe(()=>{let r=this.params.desiredState.seekState.getState();r.state==="requested"&&this.seek(r.position/1e3)},e));let i=Ul({playbackState:this.params.desiredState.playbackState.stateChangeStarted$,mediaLoaded:t});this.subscription.add(i.pipe(Er(({mediaLoaded:r})=>r),ql(0)).subscribe(()=>{this.syncPlayback()},e)),this.subscription.add(i.pipe(Er(({mediaLoaded:r,playbackState:{from:a,to:n}})=>!r&&a==="stopped"&&n==="playing")).subscribe(()=>{this.loadMedia()},e)),this.subscription.add(Ul({volumeState:this.params.desiredState.volume.stateChangeStarted$.pipe(ql(30)),mediaLoaded:t}).pipe(Er(({mediaLoaded:r})=>r)).subscribe(({volumeState:r})=>{let{muted:a,volume:n}=r.to;this.setVolume(n,a)},e))}handleMessage(e){switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId);let t=e.message?.media?.[0];this.syncMediaState(t);let i=e.message?.receiver.volume;this.syncVolumeState(i)}break;case"v2_message":{switch(e.message?.type){case"MEDIA_STATUS":{let t=e.message?.status?.[0];this.syncMediaState(t);break}}break}}}loadMedia(){let e=Xn(this.params),t=this.media?.currentTime,i=this.params.desiredState.seekState.getState(),r=t??(i.state!=="none"?i.position/1e3:0),n=this.params.desiredState.playbackState.getState()==="playing";this.params.chromecastConnector.sendV2Message({type:"LOAD",requestId:0,media:e,autoplay:n,currentTime:r,customData:null,activeTrackIds:null}),this.params.output.willSeekEvent$.next()}stop(){this.params.chromecastConnector.stopMedia()}play(){let e=this.mediaSessionId$.getValue();Fl(e,"play on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PLAY",mediaSessionId:e,customData:null})}pause(){let e=this.mediaSessionId$.getValue();Fl(e,"pause on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PAUSE",mediaSessionId:e,customData:null})}seek(e){let t=this.mediaSessionId$.getValue();Fl(t,"seek on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"SEEK",currentTime:e,mediaSessionId:t}),this.params.output.willSeekEvent$.next()}setVolume(e,t){let i=e,r=`[setVolume] volume: ${e}, muted: ${t}`;this.isMobile&&(i=this.mobileVolumeState.volume,r+=`, mobile next volume: ${i}`),this.log({message:r}),this.lastRequestedVolume={volume:i,muted:t},this.params.chromecastConnector.sendV2Message({type:"SET_VOLUME",requestId:0,volume:{level:t?0:i,muted:t?!0:null}})}syncPlaybackState({playerState:e,idleReason:t}){let i=this.params.output.isBuffering$.getValue(),r=e==="BUFFERING";switch(i!==r&&this.params.output.isBuffering$.next(r),e){case"PAUSED":P(this.params.desiredState.playbackState,"paused");break;case"PLAYING":P(this.params.desiredState.playbackState,"playing");break;case"IDLE":{t==="FINISHED"?(this.params.output.endedEvent$.next(),P(this.params.desiredState.playbackState,"stopped"),this.contentId$.next(null)):P(this.params.desiredState.playbackState,"ready");break}case"BUFFERING":break}}syncPlayback(){let e=this.params.desiredState.playbackState.getState();switch(this.log({message:`[syncPlayback] ${e}`}),e){case"ready":break;case"playing":this.play();break;case"paused":this.pause();break;case"stopped":this.stop();break}}syncVolumeState(e){if(Qm(e))return;let{level:t,muted:i}=e,r={muted:i??!1,volume:t??0};this.lastRequestedVolume&&(i&&(r.volume=this.lastRequestedVolume.volume),this.lastRequestedVolume.muted&&!t&&!i&&(r.volume=this.lastRequestedVolume.volume,r.muted=!0),this.lastRequestedVolume=null);let a=`[syncVolumeState] volume: ${r.volume}, muted: ${r.muted}`;this.isMobile&&(this.mobileVolumeState.volume=r.volume,this.mobileVolumeState.muted=r.muted,r.volume=this.params.output.volume$.getValue().volume,a+=`, volume passed to state machine: ${r.volume}`),this.log({message:a}),this.params.output.volume$.next(r)}destroy(){this.progressTicker.destroy(),this.subscription.unsubscribe()}};import{assertNonNullable as cA,ErrorCategory as zl,filter as dA,Subject as pA,Subscription as Ql,tap as hA,ValueSubject as wr,fromEvent as Ns}from"@vkontakte/videoplayer-shared/es2024";var Wm=s=>({castDevice:{friendlyName:s},remotePlayer:{},remotePlayerController:{},session:{}}),Gm=()=>String(Date.now())+String(Math.floor(Math.random()*1e5));var Fs=class{constructor(e){this.capabilities=["WEB"];this.presentationRequest$=new wr(null);this.sessionId$=new wr(null);this.broadcastChannel=new BroadcastChannel("vk_player_chromecast_events");this.subscription=new Ql;this.subscriptionEvents=new Ql;this.isDestroyed=!1;this.sequenceNumber=0;this.presentationAvailable$=new wr(!1);this.presentationConnection$=new wr(null);this.message$=new wr(null);this.friendlyName$=new wr(null);this.errorEvent$=new pA;this.clientId=this.getClientId(),this.params=e,this.log=e.logger.createComponentLog("ChromecastPresentationApiConnector"),this.log({message:"constructor"}),this.reinitPresentation(),this.subscribe()}destroy(){this.log({message:"destroy"}),this.subscription.unsubscribe(),this.subscriptionEvents.unsubscribe(),this.broadcastChannel.close(),this.isDestroyed=!0}disconnect(e=!0){this.log({message:"disconnect"}),e&&this.stopMedia(),this.presentationRequest$.next(null);let t=this.presentationConnection$.getValue();t&&t.close(),this.presentationConnection$.next(null),this.friendlyName$.next(null),this.resetSequenceNumber(),this.resetSubscriptionEvents()}stopMedia(){this.log({message:"stopMedia"}),this.sendV2Message({type:"STOP"})}reinitPresentation(e=!0){let t=this.createCastUrl(),i=new PresentationRequest(t);this.presentationRequest$.next(i),this.log({message:"PresentationRequest created"}),i.getAvailability().then(r=>{let a=()=>{this.log({message:`PresentationRequest presentation availability: ${r.value}`}),this.presentationAvailable$.next(r.value)};this.subscriptionEvents.add(Ns(r,"change").subscribe(()=>{a()})),a()}).catch(()=>{this.presentationAvailable$.next(!0)}),window.navigator.presentation.defaultRequest=i,e&&i.reconnect("auto-join").then(r=>{this.log({message:"PresentationRequest reconnect success"}),this.handleConnection(r)}).catch(()=>{this.log({message:"PresentationRequest reconnect failed"})})}async connect(){this.log({message:"connect"});try{this.presentationRequest$.getValue()||(this.log({message:"reinitPresentation"}),this.reinitPresentation(!1));let e=this.presentationRequest$.getValue();cA(e,"connect with null presentationRequest");let t=await e.start();this.handleConnection(t)}catch(e){switch(e?.name){case"AbortError":case"NotAllowedError":break;default:this.errorEvent$.next({category:zl.WTF,id:"ChromecastPresentationApiConnector",message:e?.message??"connect error",thrown:e});break}}}subscribe(){this.subscription.add(Ns(this.broadcastChannel,"message").subscribe(e=>{this.log({message:`broadcast connection data: ${e.data}`}),e.data==="connection"&&this.disconnect(!1)})),this.subscription.add(this.presentationAvailable$.subscribe(e=>{this.log({message:`presentationAvailable$: ${e}`})})),this.subscription.add(this.presentationConnection$.pipe(hA(e=>{this.log({message:`presentationConnection$: ${!!e}`})}),dA(e=>!!e)).subscribe(e=>{let t=Ns(e,"message").subscribe(a=>{let n=JSON.parse(a.data);n.clientId===this.clientId&&(this.log({message:`[onmessage] ${a.data}`}),this.handleMessage(n),this.message$.next(n))}),i=Ns(e,"connect").subscribe(()=>{this.send("client_connect")}),r=Ns(e,"close").subscribe(a=>{switch(a.reason){case"error":this.errorEvent$.next({category:zl.WTF,id:"ChromecastPresentationApiConnector",message:"Session error",thrown:a});break;case"closed":break}});this.subscriptionEvents.add(t),this.subscriptionEvents.add(i),this.subscriptionEvents.add(r)}))}send(e){switch(e){case"client_connect":{let t={type:"client_connect",message:this.clientId,sequenceNumber:-1,timeoutMillis:0,clientId:this.clientId};this.safeSend(JSON.stringify(t));break}}}sendV2Message(e){let t=this.sessionId$.getValue();if(t){let i={type:"v2_message",sequenceNumber:this.getSequenceNumber(),timeoutMillis:0,clientId:this.clientId,message:{...e,sessionId:t}};this.safeSend(JSON.stringify(i))}}safeSend(e){try{this.log({message:`[send] ${e}`});let t=this.presentationConnection$.getValue();t?.state==="connected"&&t?.send(e)}catch(t){this.errorEvent$.next({category:zl.WTF,id:"ChromecastPresentationApiConnector",message:"PresentationConnection send error",data:{message:e},thrown:t})}}handleMessage(e){switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId),this.friendlyName$.next(e.message.receiver.friendlyName||"Chromecast Device");break}case"receiver_action":e.message?.action==="stop"&&this.disconnect();break}}createCastUrl(){return`cast:${this.params.appId}?clientId=${this.clientId}&autoJoinPolicy=tab_and_origin_scoped&defaultActionPolicy=create_session&launchTimeout=60000&supportedAppTypes=${this.capabilities}&appParams=%7B%22launchCheckerParams%22%3A%7B%7D%7D`}getSequenceNumber(){let e=this.sequenceNumber;return this.sequenceNumber=(this.sequenceNumber+1)%Number.MAX_SAFE_INTEGER,e}resetSequenceNumber(){this.sequenceNumber=0}getClientId(){let e="__vk_player_chromecast_id";return window[e]=window[e]||Gm()}resetSubscriptionEvents(){this.subscriptionEvents.unsubscribe(),this.subscriptionEvents=new Ql}handleConnection(e){this.log({message:"connection available"}),this.isDestroyed?(this.log({message:"connected on already destroyed component"}),e.close()):(this.broadcastChannel.postMessage("connection"),this.presentationConnection$.next(e))}};import{ValueSubject as Ym,Subject as fA,map as mA,Subscription as bA,combine as gA,filterChanged as Km,assertNonNullable as SA}from"@vkontakte/videoplayer-shared/es2024";var _t=class s{constructor(e){this.subscription=new bA;this.connection$=new Ym(void 0);this.castState$=new Ym("NOT_AVAILABLE");this.errorEvent$=new fA;let t=s.isSupported();this.log=e.dependencies.logger.createComponentLog("ChromecastPresentationApiInitializer"),this.log({message:`[constructor] receiverApplicationId: ${e.receiverApplicationId}, isDisabled: ${e.isDisabled}, isSupported: ${t}`}),!(!t||e.isDisabled||!e.receiverApplicationId)&&(this.chromecastConnector=new Fs({appId:e.receiverApplicationId,logger:e.dependencies.logger}),this.subscribe())}static isSupported(){return"chrome"in window&&"presentation"in navigator&&"BroadcastChannel"in window}subscribe(){SA(this.chromecastConnector,"subscribe with null chromecastConnector"),this.subscription.add(this.chromecastConnector.errorEvent$.subscribe(this.errorEvent$));let e=gA({connection:this.chromecastConnector.presentationConnection$,available:this.chromecastConnector.presentationAvailable$,friendlyName:this.chromecastConnector.friendlyName$.pipe(Km())});this.subscription.add(e.pipe(mA(({connection:t,friendlyName:i})=>!!(t&&i)),Km()).subscribe(t=>{let i=this.chromecastConnector?.friendlyName$.getValue()??"";this.connection$.next(t?Wm(i):void 0)})).add(e.subscribe(({available:t,connection:i})=>{t?i?this.castState$.next("CONNECTED"):this.castState$.next("AVAILABLE"):this.castState$.next("NOT_AVAILABLE")}))}connect(){this.log({message:"connect"}),this.chromecastConnector?.connect()}disconnect(){this.log({message:"disconnect"}),this.chromecastConnector?.disconnect()}async stopMedia(){this.log({message:"stopMedia"}),this.chromecastConnector?.stopMedia()}toggleConnection(){let e=!!this.chromecastConnector?.presentationConnection$.getValue();this.log({message:`toggleConnection: isConnected - ${e}`}),e?this.disconnect():this.connect()}setVolume(e){}setMuted(e){}destroy(){this.log({message:"destroy"}),this.chromecastConnector?.destroy(),this.subscription.unsubscribe()}};var Jp=D(ke(),1),Zp=D(ni(),1),mw=D(fc(),1);var Dv=D(Ro(),1);import{isNonNullable as sD,Subject as $o,merge as Av}from"@vkontakte/videoplayer-shared/es2024";var O=class{constructor(e){this.transitionStarted$=new $o;this.transitionEnded$=new $o;this.transitionUpdated$=new $o;this.forceChanged$=new $o;this.stateChangeStarted$=Av(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Av(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||sD(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}};import{assertNever as Zs,debounce as Rv,ErrorCategory as aD,fromEvent as Ui,map as $v,merge as Mv,observableFrom as nD,Subject as oD,Subscription as ed,timeout as uD}from"@vkontakte/videoplayer-shared/es2024";var lD=5,cD=5,dD=500,Lv=7e3,ea=class{constructor(e){this.subscription=new ed;this.loadMediaTimeoutSubscription=new ed;this.videoState=new O("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=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(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&a.state==="requested"&&e!=="stopped"){this.seek(a.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:Zs(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:Zs(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:Zs(e)}break}default:Zs(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(_s(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 ed;this.subscription.add(e),this.subscription.add(Mv(this.videoState.stateChangeStarted$.pipe($v(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe($v(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new oD;e.add(r.pipe(Rv(dD)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(Ui(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-a)>lD)&&r.next(o),a=o})),e.add(Ui(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Ui(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Ui(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(Ui(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:a}=this.params.connection,n=r.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()&&a.duration-a.currentTime<cD&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),P(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Zs(n)}}),t(Ui(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(Ui(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Mv(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,nD(["init"])).pipe(Rv(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"),P(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),P(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=Xn(this.params),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),P(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&P(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),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()}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((r,a)=>{this.loadMediaTimeoutSubscription.add(uD(Lv).subscribe(()=>a(`timeout(${Lv})`)))});(0,Dv.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()},r=>{let a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:aD.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var vd=D(ke(),1);import{clearVideoElement as Cv}from"@vkontakte/videoplayer-shared/es2024";import{clearVideoElement as pD}from"@vkontakte/videoplayer-shared/es2024";var Bv=s=>{try{s.pause(),s.playbackRate=0,pD(s),s.remove()}catch(e){console.error(e)}};import{fromEvent as hD,Subscription as fD}from"@vkontakte/videoplayer-shared/es2024";var td=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)}},id=window.WeakMap?new WeakMap:new td,rd=window.WeakMap?new WeakMap:new Map,mD=(s,e=20)=>{let t=0;return hD(s,"ratechange").subscribe(i=>{t++,t>=e&&(s.currentTime=s.currentTime,t=0)})},Pe=(s,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=s.querySelector("video"),r=!!i;i?Cv(i):(i=document.createElement("video"),s.appendChild(i)),id.set(i,r);let a=new fD;return a.add(mD(i,e)),rd.set(i,a),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},Ae=s=>{rd.get(s)?.unsubscribe(),rd.delete(s);let t=id.get(s);id.delete(s),t?Cv(s):Bv(s)};var ad=D(Di(),1);import{assertNonNullable as ia,isNonNullable as At,isNullable as SD,fromEvent as Br,merge as Vv,observableFrom as _v,filterChanged as Ov,map as ra,Subject as Nv,Subscription as vD,ValueSubject as yD,ErrorCategory as TD}from"@vkontakte/videoplayer-shared/es2024";import{isNonNullable as sd,isNullable as bD,Subscription as gD}from"@vkontakte/videoplayer-shared/es2024";var Mo=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{let n=s.getState(),o=e(),u=bD(r),l=new gD;return r&&l.add(r.subscribe(p=>{let c=s.getState();i(p,c)&&s.setState(p)},a)),i(o,n)||(t(n),u&&s.setState(n)),l.add(s.stateChangeStarted$.subscribe(p=>{t(p.to),u&&s.setState(p.to)},a)),l},ot=(s,e,t)=>Mo(e,()=>s.loop,i=>{sd(i)&&(s.loop=i)},{onError:t}),Re=(s,e,t,i)=>Mo(e,()=>({muted:s.muted,volume:s.volume}),r=>{sd(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||r?.muted===a?.muted&&r?.volume===a?.volume,changed$:t,onError:i}),Qe=(s,e,t,i)=>Mo(e,()=>s.playbackRate,r=>{sd(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),ta=Mo;var ID=s=>["__",s.language,s.label].join("|"),ED=(s,e)=>{if(s.id===e)return!0;let[t,i,r]=e.split("|");return s.language===i&&s.label===r},nd=class s{constructor(e){this.available$=new Nv;this.current$=new yD(void 0);this.error$=new Nv;this.subscription=new vD;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=a=>{this.error$.next({id:"TextTracksManager",category:TD.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};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(ta(t.internalTextTracks,()=>(0,ad.default)(this.internalTracks),a=>{At(a)&&this.setInternal(a)},{equal:(a,n)=>At(a)&&At(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(ra(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(ta(t.externalTextTracks,()=>(0,ad.default)(this.externalTracks),a=>{At(a)&&this.setExternal(a)},{equal:(a,n)=>At(a)&&At(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(ra(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(ta(t.currentTextTrack,()=>{if(this.video)return;let a=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(ta(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){ia(this.video);let{textTracks:e}=this.video;this.subscription.add(Br(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(Vv(Br(e,"addtrack"),Br(e,"removetrack"),_v(["init"])).pipe(ra(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),Ov((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(Vv(Br(e,"change"),_v(["init"])).pipe(ra(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),ra(i=>i&&this.htmlTextTrackToITextTrack(i).id),Ov()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(Br(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=a=>{let n=a.target?.cues??null;n&&n.length&&(this.applyCueSettings(a.target?.cues??null),a.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add(Br(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 r=i;At(t.align)&&(r.align=t.align),At(t.position)&&(r.position=t.position),At(t.size)&&(r.size=t.size),At(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){ia(this.video);let t=[...this.video.textTracks];return e?t:t.filter(s.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:ID(e),a=this.externalTracks.has(r),n=(a?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??r.includes("auto");return a?{id:r,type:"external",isAuto:n,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:this.internalTracks.get(r)?.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:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){ia(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(SD(e)||!ED(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){ia(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):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){ia(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)}},We=nd;var qi=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 Fv=s=>{let e=s;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},od=s=>{let e=Fv(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},Uv=s=>{let e=Fv(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};import{fromEvent as _e,map as Rt,merge as Lo,filterChanged as jv,isNonNullable as Hv,Subject as xD,filter as ud,mapTo as ld,combine as kD,once as PD,shareReplay as Oe,throttle as AD,ErrorCategory as RD,ValueSubject as zv,Subscription as $D}from"@vkontakte/videoplayer-shared/es2024";var wD=3,qv=(s,e,t=wD)=>{let i=0,r=0;for(let a=0;a<s.length;a++){let n=s.start(a),o=s.end(a);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)s.end(u)+t>=i&&(i=s.start(u));for(let u=a+1;u<s.length;u++)s.start(u)-t<=r&&(r=s.end(u))}}return{from:i,to:r}};var $e=s=>{let e=k=>_e(s,k).pipe(ld(void 0),Oe(1)),t=new $D,i=()=>t.unsubscribe(),r=Lo(_e(s,"progress"),_e(s,"timeupdate")).pipe(Rt(()=>qv(s.buffered,s.currentTime)),Oe(1)),a=$.browser.isSafari?kD({play:e("play").pipe(PD()),playing:e("playing")}).pipe(ld(void 0),Oe(1)):e("playing"),n=_e(s,"volumechange").pipe(Rt(()=>({muted:s.muted,volume:s.volume})),Oe(1)),o=_e(s,"ratechange").pipe(Rt(()=>s.playbackRate),Oe(1)),u=_e(s,"error").pipe(ud(()=>!!(s.error||s.played.length)),Rt(()=>{let k=s.error;return{id:k?`MediaError#${k.code}`:"HtmlVideoError",category:RD.VIDEO_PIPELINE,message:k?k.message:"Error event from HTML video element",thrown:s.error??void 0}}),Oe(1)),l=_e(s,"timeupdate").pipe(Rt(()=>s.currentTime),Oe(1)),p=["waiting","seeking","seeked","timeupdate"],c=new xD,d=.3,h;t.add(Lo(...p.map(k=>_e(s,k))).subscribe(k=>{let F=s.currentTime;s.loop&&Hv(h)&&Hv(F)&&h>=s.duration-d&&F<=d&&c.next(h),h=F}));let f=e("pause").pipe(ud(()=>!s.error&&h!==s.duration),Oe(1)),m=_e(s,"enterpictureinpicture").pipe(Oe(1)),S=_e(s,"leavepictureinpicture").pipe(Oe(1)),g=new zv(Uv(s));t.add(m.subscribe(()=>g.next(!0))),t.add(S.subscribe(()=>g.next(!1)));let v=new zv(od(s)),T=_e(s,"fullscreenchange").pipe(Oe(1));t.add(T.pipe(Rt(()=>od(s))).subscribe(v));let y=.1,x=1e3,A=_e(s,"timeupdate").pipe(Rt(k=>s.duration-s.currentTime<y),jv(),Oe(1)),R=Lo(A.pipe(ud(k=>!s.loop&&k)),_e(s,"ended")).pipe(AD(x),ld(void 0),Oe(1)),B=Lo(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(k=>_e(s,k)),A.pipe(Rt(k=>({type:k?"ended":"unknown"})))).pipe(Rt(k=>$.browser.isFirefox&&k.type==="ended"?s.readyState<2:s.readyState<3),jv(),Oe(1));return{playing$:a,pause$:f,canplay$:e("canplay"),ended$:R,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$:_e(s,"durationchange").pipe(Rt(()=>s.duration),Oe(1)),isBuffering$:B,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v,enterPip$:m,leavePip$:S,destroy:i}};import{VideoQuality as ui}from"@vkontakte/videoplayer-shared/es2024";var $t=s=>{switch(s){case"mobile":return ui.Q_144P;case"lowest":return ui.Q_240P;case"low":return ui.Q_360P;case"sd":case"medium":return ui.Q_480P;case"hd":case"high":return ui.Q_720P;case"fullhd":case"full":return ui.Q_1080P;case"quadhd":case"quad":return ui.Q_1440P;case"ultrahd":case"ultra":return ui.Q_2160P}};var Fe=D(Ge(),1),dd=D(ke(),1),Hi=D(ni(),1);import{isNonNullable as K,isNullable as Vo,now as uy,isHigher as _o,isHigherOrEqual as ji,isInvariantQuality as Oo,isLowerOrEqual as Vr,videoSizeToQuality as ly,assertNotEmptyArray as No,assertNonNullable as cy}from"@vkontakte/videoplayer-shared/es2024";var cd=!1,Nt={},Jv=s=>{cd=s},Zv=()=>{Nt={}},ey=s=>{s(Nt)},sa=(s,e)=>{cd&&(Nt.meta=Nt.meta??{},Nt.meta[s]=e)},Ne=class{constructor(e){this.name=e}next(e){if(!cd)return;Nt.series=Nt.series??{};let t=Nt.series[this.name]??[];t.push([Date.now(),e]),Nt.series[this.name]=t}};import{isHigher as ND,isHigherOrEqual as fH,isLower as ty,isLowerOrEqual as mH,isNonNullable as Do,isNullable as FD,videoHeightToQuality as Bo}from"@vkontakte/videoplayer-shared/es2024";function iy(s,e,t){return!s.max&&s.min===e?"high_quality":!s.min&&s.max===t?"traffic_saving":"unknown"}function Cr(s,e,t){return FD(s)||Do(s.min)&&Do(s.max)&&ty(s.max,s.min)||Do(s.min)&&e&&ND(s.min,e)||Do(s.max)&&t&&ty(s.max,t)}function ry({limits:s,highestAvailableHeight:e,lowestAvailableHeight:t}){return Cr({max:s?.max?Bo(s.max):void 0,min:s?.min?Bo(s.min):void 0},e?Bo(e):void 0,t?Bo(t):void 0)}var dy=new Ne("best_bitrate"),Fo=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;var _r=s=>(e,t)=>s*(Number(e.bitrate)-Number(t.bitrate)),yt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=uy()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Uo='Assertion "ABR Tracks is empty array" failed',Co=new WeakMap,sy=new WeakMap,ay=new WeakMap,zi=(s,e,t,i)=>{let r=[...e].sort(_r(1)),a=[...t].sort(_r(1)),n=a.filter(u=>K(u.bitrate)&&K(s.bitrate)?s.bitrate/u.bitrate>i:!0),o=(0,Fe.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1)))??(0,Fe.default)(a,-1);return o&&(0,dd.default)(n,o)?o:n.length?(0,Fe.default)(n,-1):(0,Fe.default)(a,0)},Qi=(s,e,t,i)=>{let r=Co.get(e);r||(r=[...e].sort(_r(1)),Co.set(e,r));let a=Co.get(t);a||(a=[...t].sort(_r(1)),Co.set(t,a));let n=ay.get(s);n||(n=a.filter(u=>K(u.bitrate)&&K(s.bitrate)?s.bitrate/u.bitrate>i:!0),ay.set(s,n));let o=(0,Fe.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1)))??(0,Fe.default)(a,-1);return o&&(0,dd.default)(n,o)?o:n.length?(0,Fe.default)(n,-1):(0,Fe.default)(a,0)},ny=s=>"quality"in s,qo=(s,e,t,i)=>{let r=K(i?.last?.bitrate)&&K(t?.bitrate)&&i.last.bitrate<t.bitrate?s.trackCooldownIncreaseQuality:s.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&uy()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!a&&i.recordSelection(t),a&&i?.last){let n=i.last;i?.recordSwitch(n);let o=ny(n)?"video":"audio",u=ny(n)?n.quality:n.bitrate;return e({message:`
8
8
  [last ${o} selected] ${u}
9
9
  `}),n}return i?.recordSwitch(t),t},UD=(s,e)=>Math.log(e)/Math.log(s),py=({tuning:s,container:e,limits:t,panelSize:i})=>{let r=s.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(s.usePixelRatio&&$.display.pixelRatio){let a=$.display.pixelRatio;if(s.pixelRatioMultiplier)r*=s.pixelRatioMultiplier*(a-1)+1;else{let n=s.pixelRatioLogBase,[o=0,u=0,l=0]=s.pixelRatioLogCoefficients,p=UD(n,o*a+u)+l;Number.isFinite(p)&&(r*=p)}}return K(t?.min)&&ji(t.min,s.highQualityLimit)&&(r*=2),{containerSizeLimit:s.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},oy=new WeakMap,ut=(s,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:p,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:d,stallsPredictedThroughput:h,abrLogger:f,panelSize:m})=>{No(s,Uo);let{containerSizeFactor:S,containerSizeLimit:g}=py({container:e,tuning:i,limits:r,panelSize:m}),v=i.considerPlaybackRate&&K(o)?o:1,T=oy.get(s);T||(T=s.filter(E=>!Oo(E.quality)).sort((E,I)=>_o(E.quality,I.quality)?-1:1),oy.set(s,T));let y=(0,Fe.default)(T,-1)?.quality,x=(0,Fe.default)(T,0)?.quality,A=Cr(r,x,y),R=v*Fo(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),w={},B=null;for(let E of T){let I=!0;if(g)if(E.size)I=E.size.width<=g.width&&E.size.height<=g.height;else{let z=g&&ly(g);I=z?Vr(E.quality,z):!0}if(!I){w[E.quality]="FitsContainer";continue}let N=h||t,L=K(N)&&isFinite(N)&&K(E.bitrate)?N-a>=E.bitrate*R:!0,H=r?.min===E.quality;if(!L&&!H){w[E.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&K(i.minBufferToSwitchUp)&&u&&!Oo(u.quality)&&(n??0)<i.minBufferToSwitchUp&&_o(E.quality,u.quality)){w[E.quality]="Buffer";continue}if(!!c&&ji(E.quality,c)&&!H){w[E.quality]="DroppedFramesLimit";continue}if(!!d&&ji(E.quality,d)&&!H){w[E.quality]="StallsLimit";continue}let Te=A||(Vo(r?.max)||Vr(E.quality,r.max))&&(Vo(r?.min)||ji(E.quality,r.min)),Ie=K(p)&&!p?Vr(E.quality,i.backgroundVideoQualityLimit):!0;if(!Te||!Ie){w[E.quality]="FitsQualityLimits";continue}B||(B=E)}B&&B.bitrate&&dy.next(B.bitrate);let k=B??(0,Fe.default)(T,-1)??s[0],F=l?.last,C=qo(i,f,k,l);return K(l)&&C.quality!==F?.quality&&f({message:`
10
10
  [VIDEO TRACKS ABR]
@@ -168,14 +168,14 @@ void main(void) {
168
168
  // sample using new coordinates
169
169
  gl_FragColor = texture2D(u_texture, tc);
170
170
  }
171
- `;var di=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 r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new Go(this.params.fov,this.params.orientation),this.cameraRotationManager=new Yo(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"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=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(r,0),this.gl.uniform2f(a,-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(Cy,this.gl.VERTEX_SHADER),i=this.createShader(Vy,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,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/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,r=this.camera.fov.y/180/2,a=e-i,n=t-r,o=e+i,u=t-r,l=e+i,p=t+r,c=e-i,d=t+r;return[a,n,o,u,l,p,c,d]}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}};import{isNullable as IB,now as da,once as EB,Subscription as wB,ValueSubject as Ed,isNonNullable as xB,safeStorage as wd,filterChanged as kB}from"@vkontakte/videoplayer-shared/es2024";var Ft=(s,e,t)=>t*e+(1-t)*s,Id=(s,e)=>s.reduce((t,i)=>t+i,0)/e,_y=(s,e,t,i)=>{let r=0,a=t,n=Id(s,e),o=e<i?e:i;for(let u=0;u<o;u++)s[a]>n?r++:r--,a=(s.length+a-1)%s.length;return Math.abs(r)===o};var Ko="stalls_manager_metrics",xd="stalls_manager_abr_params",Oy="stalls_manager_default_tuning_abr_params",kd=class{constructor(){this.isSeeked$=new Ed(!1);this.isBuffering$=new Ed(!1);this.maxQualityLimit=void 0;this.currentStallsCount=0;this.sumStallsDuration=0;this.lastStallDuration=0;this.providerStartWatchingTimestamp=0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new wB;this.severeStallOccurred$=new Ed(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.duration=e.duration,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let t=(this.tuning.ignoreDynamicAbrForShortVideo?this.tuning.enabled&&this.duration>this.tuning.minTvtToBeCounted:this.tuning.enabled)?this.getStoredData(xd):{};return{...this.abrParams,...t}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=da(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(da()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(Oy)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===a&&i===n||(this.removeStoredData(xd),this.setStoredData(Oy,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Ko,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((a,n)=>a+n.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let n=t.reduce((o,u)=>o+u.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(n,i))}if(this.tuning.useAverageStallsDurationPerTvt){let a=t.reduce((n,o)=>n+o.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(a,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(a=>a.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(a=>a.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(a=>a.containerSizeFactor))};this.setStoredData(Ko,[]),this.setStoredData(xd,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:a,abrAdjustingSpeed:n,significantTvt:o}=this.tuning,u=n*Math.min(t/o,1),l=this.abrTuningParams;return e<i-r?l={bitrateFactorAtEmptyBuffer:Math.max(l.bitrateFactorAtEmptyBuffer-u,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(l.bitrateFactorAtFullBuffer-u,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(l.containerSizeFactor+u,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(l={bitrateFactorAtEmptyBuffer:Math.min(l.bitrateFactorAtEmptyBuffer+u,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(l.bitrateFactorAtFullBuffer+u,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(l.containerSizeFactor-u,this.abrParams.minContainerSizeFactor)}),e>a&&(l={bitrateFactorAtEmptyBuffer:Math.max(l.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(l.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(l.containerSizeFactor,this.abrParams.containerSizeFactor)}),l}getStoredData(e,t="{}"){return JSON.parse(wd.get(e)??t)}setStoredData(e,t){wd.set(e,JSON.stringify(t))}removeStoredData(e){wd.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(Ko,"[]"),r=t/e,a=i.length?Ft(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:a};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(Ko,i)}updateStallData(){this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&(this.sumStallsDuration+=Math.min(this.lastStallDuration,this.tuning.maxPossibleStallDuration),this.currentStallsCount++)}subscribe(e){this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(e.playing$.pipe(EB()).subscribe(t=>this.providerStartWatchingTimestamp=da())),this.subscription.add(this.currentStallDuration$.pipe(kB()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:a,ignoreStallsOnSeek:n}=this.tuning;if(IB(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),p=da(),c=r&&this.currentStallsCount>=r,d=i&&p-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&p-l>=i+o&&t>=i;(c||d)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,xB(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&da()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},a)),this.lastStallDuration=t}))}},qr=kd;import{combine as PB,map as AB,observeElementSize as RB,Subscription as $B,ValueSubject as Pd,noop as MB}from"@vkontakte/videoplayer-shared/es2024";var Xo=class{constructor(){this.subscription=new $B;this.pipSize$=new Pd(void 0);this.videoSize$=new Pd(void 0);this.elementSize$=new Pd(void 0);this.pictureInPictureWindowRemoveEventListener=MB}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(RB(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(PB({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(AB(({videoSize:r,inPip:a,pipSize:n})=>a?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};import{filter as Ny,map as LB,once as Fy}from"@vkontakte/videoplayer-shared/es2024";var pi=({subscription:s,desiredState:e,videoElement$:t,observableVideo:i})=>{if(!$.browser.isSafari)return;let r=0,a=!1;s.add(e.volume.stateChangeStarted$.pipe(LB(()=>{let n=e.volume.getTransition(),o=t.getValue();return!o||!n?!1:!n.to.muted&&o.muted}),Ny(n=>!!n),Fy()).subscribe(()=>{r=performance.now(),a=!0})),s.add(i.playbackRateState$.pipe(Ny(()=>a),Fy()).subscribe(()=>{let n=t.getValue(),o=e.playbackRate.getState();n&&o!==n.playbackRate&&performance.now()-r<1e3&&(n.playbackRate=o)}))};var pa=class{constructor(e){this.subscription=new NB;this.videoState=new O("stopped");this.observableVideo=null;this.droppedFramesManager=new li;this.stallsManager=new qr;this.elementSizeManager=new Xo;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new yt;this.audioTrackSwitchHistory=new yt;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),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.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&P(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return BB(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new di(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.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new We(e.source.url),this.params=e,this.video=Pe(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(ce(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=this.getPlayer(),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;OB(this.observableVideo)&&(this.observableVideo=$e(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:Uy.WTF,message:`${i} internal logic error`,thrown:n})},a=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:a}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Ad(c=>!!c.length),jy()).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($d(c=>c.to.state!=="none"),Rd());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentNativeBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.currentBuffer$,e.currentBuffer$),a(this.player.lastRequestFirstBytes$.pipe(Ad(qy),jy()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe($d(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),pi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(Re(this.video,t.volume,i.volumeState$,r)),this.subscription.add(Qe(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Ye(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),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(),h=this.player.getCodecs();if(CB(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let S of d.audio){m.push(Td(S));let g=[];for(let v of S.representations){let T=Dy(v);g.push(T),this.audioTracksMap.set(T,{stream:S,representation:v})}this.audioStreamsMap.set(S,g)}this.params.output.availableAudioStreams$.next(m)}let f=[];for(let m of d.video){f.push(Wo(m));let S=[];for(let g of m.representations){let v=Ly({...g,streamId:m.id});v&&(S.push(v),this.videoTracksMap.set(v,{stream:m,representation:g}))}this.videoStreamsMap.set(m,S)}this.params.output.availableVideoStreams$.next(f);for(let m of d.text)for(let S of m.representations){let g=By(m,S);this.textTracksMap.set(g,{stream:m,representation:S})}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),h?.video&&this.params.output.availableVideoCodecs$.next(h.video),h?.audio&&this.params.output.availableAudioCodecs$.next(h.audio),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())},r));let o=Jo(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,_B(this.video,"progress")).pipe(Ad(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe(FB(u))),this.subscription.add(o.subscribe(async()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition(),h=t.autoVideoTrackSwitching.getState();if(c!=="manifest_ready"&&c!=="running"||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let f=this.selectVideoAudioRepresentations();if(!f)return;let[m,S]=f,g=[...this.videoTracksMap.keys()].find(T=>this.videoTracksMap.get(T)?.representation.id===m.id);qy(g)&&(this.stallsManager.lastVideoTrackSelected=g);let v=this.params.desiredState.autoVideoTrackLimits.getTransition();v&&this.params.output.autoVideoTrackLimits$.next(v.to),c==="manifest_ready"?await this.player.initRepresentations(m.id,S?.id,this.params.sourceHls):(await this.player.switchRepresentation("video",m.id,h),S&&await this.player.switchRepresentation("audio",S.id,h))},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Rd()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:S}])=>S.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:f}]=d,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(Td(f))},r)),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)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe($d(({to:c})=>c==="ready"),Rd());this.subscription.add(Jo(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Md(["init"])).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(Jo(l,this.player.state$.stateChangeEnded$,Md(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let p=Jo(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Md(["init"])).pipe(VB(0));this.subscription.add(p.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Qi:zi,t=this.params.tuning.useNewAutoSelectVideoTrack?Fr:Nr,i=this.params.tuning.useNewAutoSelectVideoTrack?ut:Or,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,u=[...this.videoTracksMap.keys()].find(({id:w})=>w===o),l=a.currentVideoTrack$.getValue(),p=r.videoStream.getState()??(u&&this.videoTracksMap.get(u)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!p)return;let c=[...this.videoStreamsMap.keys()].find(({id:w})=>w===p.id),d=c&&this.videoStreamsMap.get(c);if(!d)return;let h=this.player.bufferLength$.getValue(),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(f,m||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),v=[...this.audioStreamsMap.keys()].find(({id:w})=>w===g?.id)??this.audioStreamsMap.keys().next().value,T=0;if(v){if(u&&!n){let w=e(u,d,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}if(l){let w=e(l,d,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}}let y=u;(n||!y)&&(y=i(d,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:T,forwardBufferHealth:S,current:l,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}));let x=v&&t(y,d,this.audioStreamsMap.get(v)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),A=this.videoTracksMap.get(y)?.representation,R=x&&this.audioTracksMap.get(x)?.representation;if(A&&R)return[A,R];if(A&&!R&&this.audioTracksMap.size===0)return[A,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Uy.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Ae(this.video),this.tracer.end()}};var lp=D(Wi(),1);var{NativeAbortSignal:DW,NativeAbortController:BW}=function(s){return{NativeAbortSignal:s.AbortSignal,NativeAbortController:s.AbortController}}(typeof self<"u"?self:global);function lT(s){let e;try{e=new Event("abort")}catch{typeof document<"u"?document.createEvent?(e=document.createEvent("Event"),e.initEvent("abort",!1,!1)):(e=document.createEventObject(),e.type="abort"):e={type:"abort",bubbles:!1,cancelable:!1}}return e.reason=s,e}function cT(s){if(s===void 0)if(typeof document>"u")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason"),Object.defineProperty(s,"name",{value:"AbortError"})}catch{s=new Error("This operation was aborted"),s.name="AbortError"}return s}var Zo=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 r=0,a=i.length;r<a;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,a=i.length;r<a;r++){let n=i[r];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}},jr=class extends Zo{constructor(){super(),this.listeners||Zo.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)}throwIfAborted(){let{aborted:e,reason:t="Aborted"}=this;if(e)throw t}static timeout(e){let t=new Gi;return setTimeout(()=>t.abort(new DOMException(`This signal is timeout in ${e}ms`,"TimeoutError")),e),t.signal}static any(e){let t=new Gi;function i(){t.abort(this.reason),r()}function r(){for(let a of e)a.removeEventListener("abort",i)}for(let a of e)if(a.aborted){t.abort(a.reason);break}else a.addEventListener("abort",i);return t.signal}},Gi=class{constructor(){Object.defineProperty(this,"signal",{value:new jr,writable:!0,configurable:!0})}abort(e){let t=cT(e),i=lT(t);this.signal.reason=t,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(Gi.prototype[Symbol.toStringTag]="AbortController",jr.prototype[Symbol.toStringTag]="AbortSignal");function eu(s){return s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof s.Request=="function"&&!s.Request.prototype.hasOwnProperty("signal")||!s.AbortController}function Dd(s){typeof s=="function"&&(s={fetch:s});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!eu({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(l,p){let c;p&&p.signal&&(c=p.signal,delete p.signal);let d=new t(l,p);return c&&Object.defineProperty(d,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),d},a.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let p=a&&a.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(p){let c;try{c=new DOMException("Aborted","AbortError")}catch{c=new Error("Aborted"),c.name="AbortError"}if(p.aborted)return Promise.reject(c);let d=new Promise((h,f)=>{p.addEventListener("abort",()=>f(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([d,n(u,l)])}return n(u,l)},Request:a}}var lC=()=>"fetch"in window,ha=lC()&&eu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),dT=ha?Dd({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ke=ha?dT.fetch:window.fetch,HW=ha?dT.Request:window.Request,j=ha?Gi:window.AbortController,zW=ha?jr:window.AbortSignal;var tE=D(ke(),1);var LT=D(MT(),1);import{ErrorCategory as ma}from"@vkontakte/videoplayer-shared/es2024";var Hr=s=>{if(!s)return{id:"EmptyResponse",category:ma.PARSER,message:"Empty response"};if(s.length<=2&&s.match(/^\d+$/))return{id:`UVError#${s}`,category:ma.NETWORK,message:`UV Error ${s}`};let e=(0,LT.default)(s).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:ma.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(s,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:ma.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:ma.PARSER,message:"Response is valid XML, but parser failed"}};import{abortable as JI,assertNonNullable as Ht,ErrorCategory as Xi,filter as ap,filterChanged as v0,flattenObject as cu,fromEvent as Ji,getTraceSubscriptionMethod as y0,interval as T0,isNonNullable as bi,isNullable as Ga,map as np,merge as Ya,now as I0,Subject as gi,Subscription as ZI,SubscriptionRemovable as E0,ValueSubject as Z}from"@vkontakte/videoplayer-shared/es2024";var Tt=s=>{let e=new URL(s);return e.searchParams.set("quic","1"),e.toString()};var zr=s=>{let e=s.get("X-Delivery-Type"),t=s.get("X-Reused"),i=e===null?"http1":e??void 0,r=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:r}};import{abortable as ba,assertNever as DT,ErrorCategory as ga,flattenObject as Wr,fromEvent as BT,merge as kC,now as Sa,Subject as Gr,Subscription as PC,ValueSubject as Od}from"@vkontakte/videoplayer-shared/es2024";var Le=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var Qr=s=>{let e=new URL(s);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var iu=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.manifestRequested=new Gr;this.manifestReceived=new Gr;this.firstBytesRequested=new Gr;this.firstBytesReceived=new Gr;this.lastConnectionType$=new Od(void 0);this.lastConnectionReused$=new Od(void 0);this.lastRequestFirstBytes$=new Od(void 0);this.recoverableError$=new Gr;this.error$=new Gr;this.abortAllController=new j;this.subscription=new PC;this.fetchManifest=ba(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Tt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Qr(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(tu);return r?(t.log("success",Wr({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Wr({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=ba(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:l=!1}={}){let p=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(p,location.href);E.searchParams.append("bytes",`${i.from}-${i.to}`),p=E.toString();break}default:DT(t)}this.requestQuic&&(p=Tt(p));let h=this.abortAllController.signal,f;if(n){let E=new j;if(f=kC(BT(this.abortAllController.signal,"abort"),BT(n,"abort")).subscribe(()=>{try{E.abort()}catch(I){tu(I)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{E.abort()}catch(I){tu(I)}h=E.signal}let m=0,S=Sa();d.log("startRequest",Wr({url:p,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:S})),this.firstBytesRequested.next();let g=yield this.doFetch(p,{priority:a,headers:c,signal:h}),v=Sa();if(!g)return d.error("error",{message:"No response in request"}),d.end(),f?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(v-S),!g.ok||!g.body){f?.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),!r&&!o){f?.unsubscribe();let E=Sa(),I={requestStartedAt:S,requestEndedAt:E,duration:E-S};return d.log("endRequest",Wr(I)),d.end(),g.arrayBuffer()}let T=g.body;if(o){let E;[T,E]=g.body.tee(),this.throughputEstimator?.trackStream(E,u)}let y=T.getReader(),x,A=parseInt(g.headers.get("content-length")??"",10);Number.isFinite(A)&&(x=A),!x&&i&&(x=i.to-i.from+1);let R=x?new Uint8Array(x):new Uint8Array(0),w=!1,B=E=>{f?.unsubscribe(),w=!0,tu(E)},k=ba(h,async function*({done:E,value:I}){if(m===0&&(this.lastRequestFirstBytes$.next(Sa()-S),this.firstBytesReceived.next()),h.aborted){f?.unsubscribe();return}if(!E&&I){if(l&&x)R.set(I,m),m+=I.byteLength;else{let N=new Uint8Array(R.length+I.length);N.set(R),N.set(I,R.length),R=N,m+=I.byteLength}r?.(new DataView(R.buffer),m),yield y?.read().then(k,B)}}.bind(this));yield y?.read().then(k,B),f?.unsubscribe();let F=Sa(),C={failed:w,requestStartedAt:S,requestEndedAt:F,duration:F-S};return w?(d.error("endRequest",Wr(C)),d.end(),null):(d.log("endRequest",Wr(C)),d.end(),R.buffer)}.bind(this));this.fetchByteRangeRepresentation=ba(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,p;e.indexRange&&(l=e.indexRange.from,p=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(p,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let d=new DataView(c,r-n,a-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),f=e.indexRange??t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(c,f.from-n,f.to-f.from+1);else{let g=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!g)return null;m=new DataView(g)}let S=t.parseSegments(m,h,f).map(g=>({networkStatus:"none",bufferStatus:"none",status:"none",time:g.time,byte:g.byte}));return{initMetadata:h,initDataView:new DataView(c),segments:S}}.bind(this));this.fetchTemplateRepresentation=ba(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});if(!r)return null;let a=e.segments.map(n=>({...n,networkStatus:"none",bufferStatus:"none",status:"none",size:void 0}));return{initMetadata:null,initDataView:new DataView(r),segments:a}}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=zr(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return this.fetchTemplateRepresentation(e,i)??null;default:DT(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await Ke(e,t);if(i.ok)return i;let r=await i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:ga.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:ga.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:ga.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:ga.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:ga.FATAL})}}},tu=s=>{if(!Le(s))throw s};var Qd=D(rI(),1),xI=D(ni(),1),kI=D(vI(),1),PI=D(Ge(),1),Wd=D(Di(),1);var yI=D(ke(),1),zd=s=>{let e=s.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,a,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,a,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[a,n]=r.toUpperCase(),o=a+n;return(0,yI.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as PV,isNullable as EI}from"@vkontakte/videoplayer-shared/es2024";var TI=s=>{if(s.includes("/")){let e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var II=s=>{try{let e=kV(),t=s.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let o=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(o||[]).forEach(u=>{r[u[0]]=u.slice(2)})}let a=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:r,variants:a};return Object.keys(n).forEach(o=>{let u=n[o];(typeof u>"u"||u==="")&&delete n[o]}),n}return null}catch{return null}};function kV(){let s="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",p=`^(?:(?<langtag>${`
171
+ `;var di=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 r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new Go(this.params.fov,this.params.orientation),this.cameraRotationManager=new Yo(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"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=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(r,0),this.gl.uniform2f(a,-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(Cy,this.gl.VERTEX_SHADER),i=this.createShader(Vy,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,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/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,r=this.camera.fov.y/180/2,a=e-i,n=t-r,o=e+i,u=t-r,l=e+i,p=t+r,c=e-i,d=t+r;return[a,n,o,u,l,p,c,d]}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}};import{isNullable as IB,now as da,once as EB,Subscription as wB,ValueSubject as Ed,isNonNullable as xB,safeStorage as wd,filterChanged as kB}from"@vkontakte/videoplayer-shared/es2024";var Ft=(s,e,t)=>t*e+(1-t)*s,Id=(s,e)=>s.reduce((t,i)=>t+i,0)/e,_y=(s,e,t,i)=>{let r=0,a=t,n=Id(s,e),o=e<i?e:i;for(let u=0;u<o;u++)s[a]>n?r++:r--,a=(s.length+a-1)%s.length;return Math.abs(r)===o};var Ko="stalls_manager_metrics",xd="stalls_manager_abr_params",Oy="stalls_manager_default_tuning_abr_params",kd=class{constructor(){this.isSeeked$=new Ed(!1);this.isBuffering$=new Ed(!1);this.maxQualityLimit=void 0;this.currentStallsCount=0;this.sumStallsDuration=0;this.lastStallDuration=0;this.providerStartWatchingTimestamp=0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new wB;this.severeStallOccurred$=new Ed(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.duration=e.duration,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let t=(this.tuning.ignoreDynamicAbrForShortVideo?this.tuning.enabled&&this.duration>this.tuning.minTvtToBeCounted:this.tuning.enabled)?this.getStoredData(xd):{};return{...this.abrParams,...t}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=da(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(da()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(Oy)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===a&&i===n||(this.removeStoredData(xd),this.setStoredData(Oy,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Ko,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((a,n)=>a+n.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let n=t.reduce((o,u)=>o+u.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(n,i))}if(this.tuning.useAverageStallsDurationPerTvt){let a=t.reduce((n,o)=>n+o.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(a,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(a=>a.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(a=>a.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(a=>a.containerSizeFactor))};this.setStoredData(Ko,[]),this.setStoredData(xd,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:a,abrAdjustingSpeed:n,significantTvt:o}=this.tuning,u=n*Math.min(t/o,1),l=this.abrTuningParams;return e<i-r?l={bitrateFactorAtEmptyBuffer:Math.max(l.bitrateFactorAtEmptyBuffer-u,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(l.bitrateFactorAtFullBuffer-u,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(l.containerSizeFactor+u,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(l={bitrateFactorAtEmptyBuffer:Math.min(l.bitrateFactorAtEmptyBuffer+u,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(l.bitrateFactorAtFullBuffer+u,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(l.containerSizeFactor-u,this.abrParams.minContainerSizeFactor)}),e>a&&(l={bitrateFactorAtEmptyBuffer:Math.max(l.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(l.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(l.containerSizeFactor,this.abrParams.containerSizeFactor)}),l}getStoredData(e,t="{}"){return JSON.parse(wd.get(e)??t)}setStoredData(e,t){wd.set(e,JSON.stringify(t))}removeStoredData(e){wd.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(Ko,"[]"),r=t/e,a=i.length?Ft(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:a};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(Ko,i)}updateStallData(){this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&(this.sumStallsDuration+=Math.min(this.lastStallDuration,this.tuning.maxPossibleStallDuration),this.currentStallsCount++)}subscribe(e){this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(e.playing$.pipe(EB()).subscribe(t=>this.providerStartWatchingTimestamp=da())),this.subscription.add(this.currentStallDuration$.pipe(kB()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:a,ignoreStallsOnSeek:n}=this.tuning;if(IB(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),p=da(),c=r&&this.currentStallsCount>=r,d=i&&p-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&p-l>=i+o&&t>=i;(c||d)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,xB(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&da()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},a)),this.lastStallDuration=t}))}},qr=kd;import{combine as PB,map as AB,observeElementSize as RB,Subscription as $B,ValueSubject as Pd,noop as MB}from"@vkontakte/videoplayer-shared/es2024";var Xo=class{constructor(){this.subscription=new $B;this.pipSize$=new Pd(void 0);this.videoSize$=new Pd(void 0);this.elementSize$=new Pd(void 0);this.pictureInPictureWindowRemoveEventListener=MB}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(RB(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(PB({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(AB(({videoSize:r,inPip:a,pipSize:n})=>a?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};import{filter as Ny,map as LB,once as Fy}from"@vkontakte/videoplayer-shared/es2024";var pi=({subscription:s,desiredState:e,videoElement$:t,observableVideo:i})=>{if(!$.browser.isSafari)return;let r=0,a=!1;s.add(e.volume.stateChangeStarted$.pipe(LB(()=>{let n=e.volume.getTransition(),o=t.getValue();return!o||!n?!1:!n.to.muted&&o.muted}),Ny(n=>!!n),Fy()).subscribe(()=>{r=performance.now(),a=!0})),s.add(i.playbackRateState$.pipe(Ny(()=>a),Fy()).subscribe(()=>{let n=t.getValue(),o=e.playbackRate.getState();n&&o!==n.playbackRate&&performance.now()-r<1e3&&(n.playbackRate=o)}))};var pa=class{constructor(e){this.subscription=new NB;this.videoState=new O("stopped");this.observableVideo=null;this.droppedFramesManager=new li;this.stallsManager=new qr;this.elementSizeManager=new Xo;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new yt;this.audioTrackSwitchHistory=new yt;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),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.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&P(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return BB(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new di(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.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new We(e.source.url),this.params=e,this.video=Pe(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(ce(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=this.getPlayer(),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;OB(this.observableVideo)&&(this.observableVideo=$e(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:Uy.WTF,message:`${i} internal logic error`,thrown:n})},a=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:a}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Ad(c=>!!c.length),jy()).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($d(c=>c.to.state!=="none"),Rd());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentNativeBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.currentBuffer$,e.currentBuffer$),a(this.player.lastRequestFirstBytes$.pipe(Ad(qy),jy()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe($d(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),pi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(Re(this.video,t.volume,i.volumeState$,r)),this.subscription.add(Qe(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Ye(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),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(),h=this.player.getCodecs();if(CB(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let S of d.audio){m.push(Td(S));let g=[];for(let v of S.representations){let T=Dy(v);g.push(T),this.audioTracksMap.set(T,{stream:S,representation:v})}this.audioStreamsMap.set(S,g)}this.params.output.availableAudioStreams$.next(m)}let f=[];for(let m of d.video){f.push(Wo(m));let S=[];for(let g of m.representations){let v=Ly({...g,streamId:m.id});v&&(S.push(v),this.videoTracksMap.set(v,{stream:m,representation:g}))}this.videoStreamsMap.set(m,S)}this.params.output.availableVideoStreams$.next(f);for(let m of d.text)for(let S of m.representations){let g=By(m,S);this.textTracksMap.set(g,{stream:m,representation:S})}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),h?.video&&this.params.output.availableVideoCodecs$.next(h.video),h?.audio&&this.params.output.availableAudioCodecs$.next(h.audio),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())},r));let o=Jo(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,_B(this.video,"progress")).pipe(Ad(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe(FB(u))),this.subscription.add(o.subscribe(async()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition(),h=t.autoVideoTrackSwitching.getState();if(c!=="manifest_ready"&&c!=="running"||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let f=this.selectVideoAudioRepresentations();if(!f)return;let[m,S]=f,g=[...this.videoTracksMap.keys()].find(T=>this.videoTracksMap.get(T)?.representation.id===m.id);qy(g)&&(this.stallsManager.lastVideoTrackSelected=g);let v=this.params.desiredState.autoVideoTrackLimits.getTransition();v&&this.params.output.autoVideoTrackLimits$.next(v.to),c==="manifest_ready"?await this.player.initRepresentations(m.id,S?.id,this.params.sourceHls):(await this.player.switchRepresentation("video",m.id,h),S&&await this.player.switchRepresentation("audio",S.id,h))},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Rd()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:S}])=>S.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:f}]=d,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(Td(f))},r)),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)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe($d(({to:c})=>c==="ready"),Rd());this.subscription.add(Jo(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Md(["init"])).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(Jo(l,this.player.state$.stateChangeEnded$,Md(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let p=Jo(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Md(["init"])).pipe(VB(0));this.subscription.add(p.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Qi:zi,t=this.params.tuning.useNewAutoSelectVideoTrack?Fr:Nr,i=this.params.tuning.useNewAutoSelectVideoTrack?ut:Or,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,u=[...this.videoTracksMap.keys()].find(({id:w})=>w===o),l=a.currentVideoTrack$.getValue(),p=r.videoStream.getState()??(u&&this.videoTracksMap.get(u)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!p)return;let c=[...this.videoStreamsMap.keys()].find(({id:w})=>w===p.id),d=c&&this.videoStreamsMap.get(c);if(!d)return;let h=this.player.bufferLength$.getValue(),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(f,m||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),v=[...this.audioStreamsMap.keys()].find(({id:w})=>w===g?.id)??this.audioStreamsMap.keys().next().value,T=0;if(v){if(u&&!n){let w=e(u,d,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}if(l){let w=e(l,d,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}}let y=u;(n||!y)&&(y=i(d,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:T,forwardBufferHealth:S,current:l,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}));let x=v&&t(y,d,this.audioStreamsMap.get(v)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),A=this.videoTracksMap.get(y)?.representation,R=x&&this.audioTracksMap.get(x)?.representation;if(A&&R)return[A,R];if(A&&!R&&this.audioTracksMap.size===0)return[A,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Uy.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Ae(this.video),this.tracer.end()}};var lp=D(Wi(),1);var{NativeAbortSignal:DQ,NativeAbortController:BQ}=function(s){return{NativeAbortSignal:s.AbortSignal,NativeAbortController:s.AbortController}}(typeof self<"u"?self:global);function lT(s){let e;try{e=new Event("abort")}catch{typeof document<"u"?document.createEvent?(e=document.createEvent("Event"),e.initEvent("abort",!1,!1)):(e=document.createEventObject(),e.type="abort"):e={type:"abort",bubbles:!1,cancelable:!1}}return e.reason=s,e}function cT(s){if(s===void 0)if(typeof document>"u")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason"),Object.defineProperty(s,"name",{value:"AbortError"})}catch{s=new Error("This operation was aborted"),s.name="AbortError"}return s}var Zo=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 r=0,a=i.length;r<a;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,a=i.length;r<a;r++){let n=i[r];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}},jr=class extends Zo{constructor(){super(),this.listeners||Zo.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)}throwIfAborted(){let{aborted:e,reason:t="Aborted"}=this;if(e)throw t}static timeout(e){let t=new Gi;return setTimeout(()=>t.abort(new DOMException(`This signal is timeout in ${e}ms`,"TimeoutError")),e),t.signal}static any(e){let t=new Gi;function i(){t.abort(this.reason),r()}function r(){for(let a of e)a.removeEventListener("abort",i)}for(let a of e)if(a.aborted){t.abort(a.reason);break}else a.addEventListener("abort",i);return t.signal}},Gi=class{constructor(){Object.defineProperty(this,"signal",{value:new jr,writable:!0,configurable:!0})}abort(e){let t=cT(e),i=lT(t);this.signal.reason=t,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(Gi.prototype[Symbol.toStringTag]="AbortController",jr.prototype[Symbol.toStringTag]="AbortSignal");function eu(s){return s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof s.Request=="function"&&!s.Request.prototype.hasOwnProperty("signal")||!s.AbortController}function Dd(s){typeof s=="function"&&(s={fetch:s});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!eu({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(l,p){let c;p&&p.signal&&(c=p.signal,delete p.signal);let d=new t(l,p);return c&&Object.defineProperty(d,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),d},a.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let p=a&&a.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(p){let c;try{c=new DOMException("Aborted","AbortError")}catch{c=new Error("Aborted"),c.name="AbortError"}if(p.aborted)return Promise.reject(c);let d=new Promise((h,f)=>{p.addEventListener("abort",()=>f(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([d,n(u,l)])}return n(u,l)},Request:a}}var lC=()=>"fetch"in window,ha=lC()&&eu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),dT=ha?Dd({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ke=ha?dT.fetch:window.fetch,HQ=ha?dT.Request:window.Request,j=ha?Gi:window.AbortController,zQ=ha?jr:window.AbortSignal;var tE=D(ke(),1);var LT=D(MT(),1);import{ErrorCategory as ma}from"@vkontakte/videoplayer-shared/es2024";var Hr=s=>{if(!s)return{id:"EmptyResponse",category:ma.PARSER,message:"Empty response"};if(s.length<=2&&s.match(/^\d+$/))return{id:`UVError#${s}`,category:ma.NETWORK,message:`UV Error ${s}`};let e=(0,LT.default)(s).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:ma.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(s,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:ma.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:ma.PARSER,message:"Response is valid XML, but parser failed"}};import{abortable as JI,assertNonNullable as Ht,ErrorCategory as Xi,filter as ap,filterChanged as v0,flattenObject as cu,fromEvent as Ji,getTraceSubscriptionMethod as y0,interval as T0,isNonNullable as bi,isNullable as Ga,map as np,merge as Ya,now as I0,Subject as gi,Subscription as ZI,SubscriptionRemovable as E0,ValueSubject as Z}from"@vkontakte/videoplayer-shared/es2024";var Tt=s=>{let e=new URL(s);return e.searchParams.set("quic","1"),e.toString()};var zr=s=>{let e=s.get("X-Delivery-Type"),t=s.get("X-Reused"),i=e===null?"http1":e??void 0,r=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:r}};import{abortable as ba,assertNever as DT,ErrorCategory as ga,flattenObject as Wr,fromEvent as BT,merge as kC,now as Sa,Subject as Gr,Subscription as PC,ValueSubject as Od}from"@vkontakte/videoplayer-shared/es2024";var Le=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var Qr=s=>{let e=new URL(s);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var iu=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.manifestRequested=new Gr;this.manifestReceived=new Gr;this.firstBytesRequested=new Gr;this.firstBytesReceived=new Gr;this.lastConnectionType$=new Od(void 0);this.lastConnectionReused$=new Od(void 0);this.lastRequestFirstBytes$=new Od(void 0);this.recoverableError$=new Gr;this.error$=new Gr;this.abortAllController=new j;this.subscription=new PC;this.fetchManifest=ba(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Tt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Qr(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(tu);return r?(t.log("success",Wr({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Wr({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=ba(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:l=!1}={}){let p=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(p,location.href);E.searchParams.append("bytes",`${i.from}-${i.to}`),p=E.toString();break}default:DT(t)}this.requestQuic&&(p=Tt(p));let h=this.abortAllController.signal,f;if(n){let E=new j;if(f=kC(BT(this.abortAllController.signal,"abort"),BT(n,"abort")).subscribe(()=>{try{E.abort()}catch(I){tu(I)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{E.abort()}catch(I){tu(I)}h=E.signal}let m=0,S=Sa();d.log("startRequest",Wr({url:p,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:S})),this.firstBytesRequested.next();let g=yield this.doFetch(p,{priority:a,headers:c,signal:h}),v=Sa();if(!g)return d.error("error",{message:"No response in request"}),d.end(),f?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(v-S),!g.ok||!g.body){f?.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),!r&&!o){f?.unsubscribe();let E=Sa(),I={requestStartedAt:S,requestEndedAt:E,duration:E-S};return d.log("endRequest",Wr(I)),d.end(),g.arrayBuffer()}let T=g.body;if(o){let E;[T,E]=g.body.tee(),this.throughputEstimator?.trackStream(E,u)}let y=T.getReader(),x,A=parseInt(g.headers.get("content-length")??"",10);Number.isFinite(A)&&(x=A),!x&&i&&(x=i.to-i.from+1);let R=x?new Uint8Array(x):new Uint8Array(0),w=!1,B=E=>{f?.unsubscribe(),w=!0,tu(E)},k=ba(h,async function*({done:E,value:I}){if(m===0&&(this.lastRequestFirstBytes$.next(Sa()-S),this.firstBytesReceived.next()),h.aborted){f?.unsubscribe();return}if(!E&&I){if(l&&x)R.set(I,m),m+=I.byteLength;else{let N=new Uint8Array(R.length+I.length);N.set(R),N.set(I,R.length),R=N,m+=I.byteLength}r?.(new DataView(R.buffer),m),yield y?.read().then(k,B)}}.bind(this));yield y?.read().then(k,B),f?.unsubscribe();let F=Sa(),C={failed:w,requestStartedAt:S,requestEndedAt:F,duration:F-S};return w?(d.error("endRequest",Wr(C)),d.end(),null):(d.log("endRequest",Wr(C)),d.end(),R.buffer)}.bind(this));this.fetchByteRangeRepresentation=ba(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,p;e.indexRange&&(l=e.indexRange.from,p=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(p,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let d=new DataView(c,r-n,a-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),f=e.indexRange??t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(c,f.from-n,f.to-f.from+1);else{let g=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!g)return null;m=new DataView(g)}let S=t.parseSegments(m,h,f).map(g=>({networkStatus:"none",bufferStatus:"none",status:"none",time:g.time,byte:g.byte}));return{initMetadata:h,initDataView:new DataView(c),segments:S}}.bind(this));this.fetchTemplateRepresentation=ba(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});if(!r)return null;let a=e.segments.map(n=>({...n,networkStatus:"none",bufferStatus:"none",status:"none",size:void 0}));return{initMetadata:null,initDataView:new DataView(r),segments:a}}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=zr(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return this.fetchTemplateRepresentation(e,i)??null;default:DT(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await Ke(e,t);if(i.ok)return i;let r=await i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:ga.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:ga.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:ga.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:ga.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:ga.FATAL})}}},tu=s=>{if(!Le(s))throw s};var Qd=D(rI(),1),xI=D(ni(),1),kI=D(vI(),1),PI=D(Ge(),1),Wd=D(Di(),1);var yI=D(ke(),1),zd=s=>{let e=s.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,a,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,a,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[a,n]=r.toUpperCase(),o=a+n;return(0,yI.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as PV,isNullable as EI}from"@vkontakte/videoplayer-shared/es2024";var TI=s=>{if(s.includes("/")){let e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var II=s=>{try{let e=kV(),t=s.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let o=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(o||[]).forEach(u=>{r[u[0]]=u.slice(2)})}let a=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:r,variants:a};return Object.keys(n).forEach(o=>{let u=n[o];(typeof u>"u"||u==="")&&delete n[o]}),n}return null}catch{return null}};function kV(){let s="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",p=`^(?:(?<langtag>${`
172
172
  (?<language>${`(?:[a-z]{2,3}(?:-${s})?|[a-z]{4}|[a-z]{5,8})`})
173
173
  (-(?<script>[a-z]{4}))?
174
174
  (-(?<region>(?:[a-z]{2}|[0-9]{3})))?
175
175
  (?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
176
176
  (?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
177
177
  (?:-(?<privateuse>(?:${e})))?
178
- `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(p,"i")}var wI=s=>{if(!s?.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(s),r=i?.[1]==="-"?-1:1,a={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},tt=(s,e)=>{let t=s;t=(0,Qd.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,xI.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Qd.default)(t,n,(o,u)=>EI(a)?o:EI(u)?a:(0,kI.default)(a,parseInt(u,10),"0"))}return t},Xr=(s,e)=>{let i=new DOMParser().parseFromString(s,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],n=Array.from(a.querySelectorAll("MPD > BaseURL").values()).map(B=>B.textContent?.trim()??""),o=(0,PI.default)(n,0)??"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),p=a.getAttribute("publishTime"),c=a.getElementsByTagName("vk:Attrs")[0],d=c?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=c?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=c?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=c?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,S;u&&(S={availabilityStartTime:l?new Date(l).getTime():0,publishTime:p?new Date(p).getTime():0,latestSegmentPublishTime:d?new Date(d).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:f==="yes"});let g,v=a.getAttribute("mediaPresentationDuration"),T=[...a.getElementsByTagName("Period")],y=T.reduce((B,k)=>({...B,[k.id]:k.children}),{}),x=T.reduce((B,k)=>({...B,[k.id]:k.getAttribute("duration")}),{});v?g=wI(v):(0,Wd.default)(x).filter(B=>B).length&&!u?g=(0,Wd.default)(x).reduce((B,k)=>B+(wI(k)??0),0):m&&(g=parseInt(m,10));let A=0,R=a.getAttribute("profiles")?.split(",")??[];for(let B of T.map(k=>k.id))for(let k of y[B]){let F=k.getAttribute("id")??"id"+(A++).toString(10),C=k.getAttribute("mimeType")??"",E=k.getAttribute("codecs")??"",I=k.getAttribute("contentType")??C?.split("/")[0],N=k.getAttribute("profiles")?.split(",")??[],L=II(k.getAttribute("lang")??"")??{},H=k.querySelector("Label")?.textContent?.trim()??void 0,X=k.querySelectorAll("Representation"),re=k.querySelector("SegmentTemplate"),le=k.querySelector("Role")?.getAttribute("value")??void 0,Te=I,Ie={id:F,language:L.language,isDefault:le==="main",label:H,codecs:E,hdr:Te==="video"&&zd(E),mime:C,representations:[]};for(let z of X){let q=z.getAttribute("lang")??void 0,Ee=H??k.getAttribute("label")??z.getAttribute("label")??void 0,Be=z.querySelector("BaseURL")?.textContent?.trim()??"",me=new URL(Be||o,e).toString(),at=z.getAttribute("mimeType")??C,Jt=z.getAttribute("codecs")??E??"",dt;if(I==="text"){let Xe=z.getAttribute("id")||"",Zt=L.privateuse?.includes("x-auto")||Xe.includes("_auto"),pt=z.querySelector("SegmentTemplate");if(pt){let ys={representationId:z.getAttribute("id")??void 0,bandwidth:z.getAttribute("bandwidth")??void 0},Ln=parseInt(z.getAttribute("bandwidth")??"",10)/1e3,Dn=parseInt(pt.getAttribute("startNumber")??"",10)??1,lr=parseInt(pt.getAttribute("timescale")??"",10),Ku=pt.querySelectorAll("SegmentTimeline S")??[],cr=pt.getAttribute("media");if(!cr)continue;let Bn=[],Cn=0,Vn="",dr=0,Ts=Dn,Ce=0;for(let ht of Ku){let xi=parseInt(ht.getAttribute("d")??"",10),nt=parseInt(ht.getAttribute("r")??"",10)||0,ei=parseInt(ht.getAttribute("t")??"",10);Ce=Number.isFinite(ei)?ei:Ce;let ki=xi/lr*1e3,pr=Ce/lr*1e3;for(let wt=0;wt<nt+1;wt++){let ti=tt(cr,{...ys,segmentNumber:Ts.toString(10),segmentTime:(Ce+wt*xi).toString(10)}),hr=(pr??0)+wt*ki,Es=hr+ki;Ts++,Bn.push({time:{from:hr,to:Es},url:ti})}Ce+=(nt+1)*xi,Cn+=(nt+1)*ki}dr=Ce/lr*1e3,Vn=tt(cr,{...ys,segmentNumber:Ts.toString(10),segmentTime:Ce.toString(10)});let Is={time:{from:dr,to:1/0},url:Vn},Bt={type:"template",baseUrl:me,segmentTemplateUrl:cr,initUrl:"",totalSegmentsDurationMs:Cn,segments:Bn,nextSegmentBeyondManifest:Is,timescale:lr};dt={id:Xe,kind:"text",segmentReference:Bt,profiles:[],duration:g,bitrate:Ln,mime:"",codecs:"",width:0,height:0,isAuto:Zt}}else dt={id:Xe,isAuto:Zt,kind:"text",url:me}}else{let Xe=z.getAttribute("contentType")??at?.split("/")[0]??I,Zt=k.getAttribute("profiles")?.split(",")??[],pt=parseInt(z.getAttribute("width")??"",10),ys=parseInt(z.getAttribute("height")??"",10),Ln=parseInt(z.getAttribute("bandwidth")??"",10)/1e3,Dn=z.getAttribute("frameRate")??"",lr=z.getAttribute("quality")??void 0,Ku=Dn?TI(Dn):void 0,cr=z.getAttribute("id")??"id"+(A++).toString(10),Bn=Xe==="video"?`${ys}p`:Xe==="audio"?`${Ln}Kbps`:Jt,Cn=`${cr}@${Bn}`,Vn=[...R,...N,...Zt],dr,Ts=z.querySelector("SegmentBase"),Ce=z.querySelector("SegmentTemplate")??re;if(Ts){let Bt=z.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[ht,xi]=Bt.split("-").map(ti=>parseInt(ti,10)),nt={from:ht,to:xi},ei=z.querySelector("SegmentBase")?.getAttribute("indexRange"),[ki,pr]=ei?ei.split("-").map(ti=>parseInt(ti,10)):[],wt=ei?{from:ki,to:pr}:void 0;dr={type:"byteRange",url:me,initRange:nt,indexRange:wt}}else if(Ce){let Bt={representationId:z.getAttribute("id")??void 0,bandwidth:z.getAttribute("bandwidth")??void 0},ht=parseInt(Ce.getAttribute("timescale")??"",10),xi=Ce.getAttribute("initialization")??"",nt=Ce.getAttribute("media"),ei=parseInt(Ce.getAttribute("startNumber")??"",10)??1,ki=tt(xi,Bt);if(!nt)throw new ReferenceError("No media attribute in SegmentTemplate");let pr=Ce.querySelectorAll("SegmentTimeline S")??[],wt=[],ti=0,hr="",Es=0;if(pr.length){let _n=ei,ft=0;for(let fr of pr){let xt=parseInt(fr.getAttribute("d")??"",10),Pi=parseInt(fr.getAttribute("r")??"",10)||0,On=parseInt(fr.getAttribute("t")??"",10);ft=Number.isFinite(On)?On:ft;let Xu=xt/ht*1e3,Ow=ft/ht*1e3;for(let Nn=0;Nn<Pi+1;Nn++){let Nw=tt(nt,{...Bt,segmentNumber:_n.toString(10),segmentTime:(ft+Nn*xt).toString(10)}),lh=(Ow??0)+Nn*Xu,Fw=lh+Xu;_n++,wt.push({time:{from:lh,to:Fw},url:Nw})}ft+=(Pi+1)*xt,ti+=(Pi+1)*Xu}Es=ft/ht*1e3,hr=tt(nt,{...Bt,segmentNumber:_n.toString(10),segmentTime:ft.toString(10)})}else if(PV(g)){let ft=parseInt(Ce.getAttribute("duration")??"",10)/ht*1e3,fr=Math.ceil(g/ft),xt=0;for(let Pi=1;Pi<fr;Pi++){let On=tt(nt,{...Bt,segmentNumber:Pi.toString(10),segmentTime:xt.toString(10)});wt.push({time:{from:xt,to:xt+ft},url:On}),xt+=ft}Es=xt,hr=tt(nt,{...Bt,segmentNumber:fr.toString(10),segmentTime:xt.toString(10)})}let _w={time:{from:Es,to:1/0},url:hr};dr={type:"template",baseUrl:me,segmentTemplateUrl:nt,initUrl:ki,totalSegmentsDurationMs:ti,segments:wt,nextSegmentBeyondManifest:_w,timescale:ht}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Xe||!at)continue;let Is={video:"video",audio:"audio",text:"text"}[Xe];if(!Is)continue;Te||=Is,dt={id:Cn,kind:Is,segmentReference:dr,profiles:Vn,duration:g,bitrate:Ln,mime:at,codecs:Jt,width:pt,height:ys,fps:Ku,quality:lr}}Ie.language||=q,Ie.label||=Ee,Ie.mime||=at,Ie.codecs||=Jt,Ie.hdr||=Te==="video"&&zd(Jt),Ie.representations.push(dt)}if(Te){let z=r[Te].find(q=>q.id===Ie.id);if(z&&Ie.representations.every(q=>q.segmentReference.type==="template"))for(let q of z.representations){let Ee=Ie.representations.find(at=>at.id===q.id);if(!Ee)continue;let Be=Ee.segmentReference,me=q.segmentReference;me.segments.push(...Be.segments),me.nextSegmentBeyondManifest=Be.nextSegmentBeyondManifest}else r[Te].push(Ie)}}return{duration:g,streams:r,baseUrls:n,live:S}};var au=D(Ge(),1),Gd=D(ke(),1);import{assertNever as nu}from"@vkontakte/videoplayer-shared/es2024";var su=s=>{let{webmDecodingInfo:e}=$.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(s){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:nu(s)}},AI=({webmCodec:s,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...su(s),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],a=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if($.device.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...a,"MPEG",...su(s),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...su(s),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...su(s),...a,"HLS","HLS_ONDEMAND"];default:nu(e)}if($.video.nativeHlsSupported)switch(t){case"hls":return[...r,"HLS","HLS_FMP4","HLS_ONDEMAND","MPEG"];case"hls_fmp4":return[...r,"HLS_FMP4","HLS","HLS_ONDEMAND","MPEG"];default:nu(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},RI=({androidPreferredFormat:s,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],a=[...i,...r],n=[...r,...i],o,u=$.device.isMac&&$.browser.isSafari;if($.device.isAndroid)switch(s){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=a;break}case"hls":case"mpeg":{o=n;break}default:nu(s)}else $.video.nativeHlsSupported&&!u&&!$.browser.isChromiumBased?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=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Yd=s=>s?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Jr=s=>{if(s.size===0)return;if(s.size===1){let t=s.values().next();return(0,au.default)(t.value.split("."),0)}for(let t of s){let i=(0,au.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=s.values().next();return(0,au.default)(e.value.split("."),0)},Zr=s=>{let e=s.map(i=>hi(i)),{codecs:t}=$.video;return MV().filter(i=>{if((0,Gd.default)(e,i))switch(i){case"av1":return t.av1;case"vp9":return t.vp9;case"avc1":return t.h264;case"hev1":return t.h265;default:return!1}else return!1})},es=s=>{let e=s.map(i=>hi(i)),{codecs:t}=$.video;return LV().filter(i=>{if((0,Gd.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},hi=s=>s.split(".")[0].replace("0",""),MV=()=>["av1","vp9","hev1","avc1"],LV=()=>["opus","mp4a"];var qI=D(Ge(),1);var DV=(s,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},BV=s=>window.clearTimeout(s),$I=s=>typeof s=="function"&&s?.toString().endsWith("{ [native code] }"),MI=!$I(window.requestIdleCallback)||!$I(window.cancelIdleCallback),Mt=MI?DV:window.requestIdleCallback,qe=MI?BV:window.cancelIdleCallback;import{abortable as tp,assertNonNullable as Lt,ErrorCategory as t0,fromEvent as i0,getExponentialDelay as r0,isHigher as s0,isNonNullable as oe,isNullable as ve,once as a0,Subject as n0,Subscription as o0,ValueSubject as za}from"@vkontakte/videoplayer-shared/es2024";var LI=D(Ge(),1);var ou=s=>s.valid,W=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,a;i===0?(this.size=void 0,this.valid=!1,a=void 0):i===1?(this.size=void 0,this.valid=!1,a=void 0):i>e.byteLength?(this.size=i,this.valid=!1,a=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,a=i-this.cursor),this.content=new DataView(e.buffer,r,a)}get id(){return this.type}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}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 ts=class extends W{};import{assertNever as CV}from"@vkontakte/videoplayer-shared/es2024";var va=class extends W{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readString(16),r=new DataView(this.content.buffer,this.content.byteOffset+16,this.content.byteLength-16);this.userData=this.parseData(i,r)}parseData(e,t){switch(e){case"ondemandlivejson":{let i=new TextDecoder("ascii").decode(t),r=JSON.parse(i);return{received:r["t-in"],prepared:r["t-out"]}}default:CV(e)}}};var ya=class extends W{constructor(e,t){if(super(e,t),!this.valid)return;this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8);for(let r=0;r<i.byteLength;r+=4){let a=this.readString(4);this.compatibleBrands.push(a)}}};var Ta=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var J=class extends W{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215,this.content=new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)}};var Ia=class extends J{constructor(e,t){super(e,t),this.valid&&(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 Ea=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var wa=class extends W{constructor(e,t){super(e,t),this.data=this.content}};var Yi=class extends J{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){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 r=this.readUint32(),a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}}};var xa=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ka=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Pa=class extends J{constructor(e,t){if(super(e,t),!this.valid)return;switch(this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Aa=class extends J{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var Ra=class extends J{constructor(e,t){super(e,t),this.valid&&(this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32())}};var $a=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ma=class extends J{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var La=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Da=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ba=class extends J{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var Ca=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Va=class extends J{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var _a=class extends J{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 Oa=class extends J{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 r=0;r<this.sampleCount;r++)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 Na=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Fa=class extends J{constructor(e,t){super(e,t),this.valid&&(this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)))}};var Ua=class extends W{constructor(e,t){super(e,t),this.valid&&(this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78)))}};var _V={ftyp:ya,moov:Ta,mvhd:Ia,moof:Ea,mdat:wa,sidx:Yi,trak:xa,mdia:$a,mfhd:Ba,tkhd:Ma,traf:Ca,tfhd:Va,tfdt:_a,trun:Oa,minf:La,sv3d:ka,st3d:Pa,prhd:Aa,proj:Da,equi:Ra,uuid:va,stbl:Na,stsd:Fa,avc1:Ua,unknown:ts},qt=class s{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n;try{n=this.createBox(a,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(o){if(!(o instanceof RangeError))throw o}if(!n||!ou(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=_V[e];return i?new i(t,new s):new ts(t,new s)}};var fi=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{ou(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 NV=new TextDecoder("ascii"),FV=s=>NV.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",UV=s=>{let e=new Yi(s,new qt),t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},qV=(s,e)=>{let i=new qt().parse(s),r=new fi(i),a=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&a.length))return null;let o=a[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(s.buffer,l,c)},jV=s=>{let t=new qt().parse(s),i=new fi(t),r={},a=i.findAll("uuid"),n=(0,LI.default)(a,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},HV=s=>{let t=new qt().parse(s);return new fi(t).find("sidx")?.timescale},zV=(s,e)=>{let i=new qt().parse(s),a=new fi(i).findAll("traf"),n=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,d)=>c+d,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},QV=s=>{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 qt().parse(s),r=new fi(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.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},DI={validateData:FV,parseInit:QV,getIndexRange:()=>{},parseSegments:UV,parseFeedableSegmentChunk:qV,getChunkEndTime:zV,getServerLatencyTimestamps:jV,getTimescaleFromIndex:HV};var ja=D(ke(),1);import{assertNonNullable as Kd,isNonNullable as _I,isNullable as GV}from"@vkontakte/videoplayer-shared/es2024";import{assertNever as WV}from"@vkontakte/videoplayer-shared/es2024";var BI={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"}},CI=s=>{let e=s.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=qa(s,t),r=i in BI,a=r?BI[i].type:"binary",n=s.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(s.buffer,s.byteOffset+t+1,o-1),l=n&255>>o,p=qa(u),c=l*2**((o-1)*8)+p,d=t+o,h;return d+c>s.byteLength?h=new DataView(s.buffer,s.byteOffset+d):h=new DataView(s.buffer,s.byteOffset+d,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:d,tagSize:d+c,value:h,valueSize:c}},qa=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{let t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},It=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return qa(s);case"float":return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case"string":return new TextDecoder("ascii").decode(s);case"utf8":return new TextDecoder("utf-8").decode(s);case"date":return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case"master":return s;case"binary":return s;default:WV(e)}},Ki=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=CI(i);if(!e(r))return;r.type==="master"&&Ki(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},VI=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=CI(s);return Ki(r.value,({tag:a,type:n,value:o})=>(a===17143?e=It(o,n):a===17026?t=It(o,n):a===17029&&(i=It(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var OI=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],YV=[231,22612,22743,167,171,163,160,175],KV=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,p=!1,c=0;return Ki(s,({tag:d,type:h,value:f,valueSize:m})=>{if(d===21419){let S=It(f,h);l=qa(S)}else d!==21420&&(l=void 0);return d===408125543?(e=f.byteOffset,t=f.byteOffset+m):d===357149030?a=!0:d===290298740?n=!0:d===2807729?i=It(f,h):d===17545?r=It(f,h):d===21420&&l===475249515?u=It(f,h):d===374648427?Ki(f,({tag:S,type:g,value:v})=>S===30321?(p=It(v,g)===1,!1):!0):a&&n&&(0,ja.default)(OI,d)&&(o=!0),!o}),Kd(e,"Failed to parse webm Segment start"),Kd(t,"Failed to parse webm Segment end"),Kd(r,"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(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:p,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},XV=s=>{if(GV(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},JV=(s,e)=>{let t=!1,i=!1,r=o=>_I(o.time)&&_I(o.position),a=[],n;return Ki(s,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=It(l,u));break;case 183:break;case 241:n&&(n.position=It(l,u));break;default:t&&(0,ja.default)(OI,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:l,position:p}=o,c=a[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+p,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},ZV=s=>{let e=0,t=!1;try{Ki(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,ja.default)(YV,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||=(0,ja.default)([163,160,175],i.tag)),!0):!1)}catch{}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},NI={validateData:VI,parseInit:KV,getIndexRange:XV,parseSegments:JV,parseFeedableSegmentChunk:ZV};var lt=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return NI;case"mp4":return DI}}throw new ReferenceError(`Unsupported mime type ${s}`)};var Xd=D(Ge(),1);import{videoSizeToQuality as e0}from"@vkontakte/videoplayer-shared/es2024";var mi=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{let o=(a?$t(a):void 0)??e0({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},Ha=({id:s,bitrate:e})=>({id:s,bitrate:e}),FI=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),UI=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Jd=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,Xd.default)(i.split("."),0),isDefault:r}),Zd=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,Xd.default)(r.split("."),0)}),ep=s=>"url"in s,it=s=>s.type==="template";var is=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,manifest:o}){this.error$=new n0;this.playingRepresentation$=new za(void 0);this.playingRepresentationInit$=new za(void 0);this.currentSegmentLength$=new za(0);this.onLastSegment$=new za(!1);this.fullyBuffered$=new za(!1);this.initData=new Map;this.initDataPromises=new Map;this.idleCallbacks=new Map;this.parsedInitData=new Map;this.segments=new Map;this.bufferPlaybackQueue=[];this.downloadingBufferItems=[];this.preloadOnly=!1;this.failedDownloads=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.currentVirtualBufferSize=0;this.baseUrls=[];this.baseUrlsIndex=0;this.maintainPlaybackBufferMutex=!1;this.maintainNativeBufferMutex=!1;this.bufferClearingMutex=!1;this.abortNativeBufferMutex=!1;this.switchMutex=!1;this.destroyAbortController=new j;this.downloadAbortController=new j;this.subscription=new o0;this.startWith=tp(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Lt(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.containerParser=lt(t.mime),this.nativeBufferManager.init(t.mime,t.codecs),yield this.loadInits(t);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);Lt(i,"No init buffer for starting representation"),Lt(r,"No segments for starting representation"),await this.nativeBufferManager.addInitSegment(i),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a)}.bind(this));this.switchTo=tp(this.destroyAbortController.signal,async function*(e,t=!0){if(ve(this.downloadingRepresentationId)||e===this.downloadingRepresentationId||e===this.switchingRepresentationId)return;this.switchMutex=!0,this.switchingRepresentationId=e;let i=this.representations.get(this.downloadingRepresentationId),r=this.representations.get(e);Lt(r,`No such representation ${e}`),Lt(i,`No such representation ${this.downloadingRepresentationId}`),yield this.loadInitIfNeeded(r,"high");let a=this.initData.get(r.id),n=this.segments.get(r.id);Lt(a,"No init buffer for switching representation"),Lt(n,"No segments for switching representation");let o=this.getCurrentPosition()??0,u=c=>c.segment.networkStatus!=="downloaded"||c.segment.time.to-o>this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment,l=c=>{let d=this.representations.get(c.representationId);return Lt(d,"No itemRepresentation for previous track before switch"),c.segment.networkStatus!=="downloaded"||this.forceSwitchCondition(d,r)},p=c=>t?u(c)&&l(c):u(c);this.bufferPlaybackQueue.filter(p).forEach(c=>c.segment.bufferStatus="none"),this.bufferPlaybackQueue=this.bufferPlaybackQueue.filter(c=>!p(c)),this.downloadingRepresentationId=e,this.switchingRepresentationId=null,this.bufferPlaybackQueue.length?(this.abortDownload(),yield this.maintain()):yield this.seek(o),this.switchMutex=!1}.bind(this));this.waitExponentialDownloadDelay=tp(this.downloadAbortController.signal,async function*(){let e=r0(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(t=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(t,e),this.subscription.add(i0(window,"online").pipe(a0()).subscribe(()=>{t(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}))})}.bind(this));this.kind=e,this.nativeBufferManager=t,this.fetcher=r,this.tuning=a,this.getCurrentPosition=n,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.baseUrls=o?.baseUrls??[],this.representations=new Map(i.map(u=>[u.id,u]))}async seek(e){await this.abort(),await this.clearBuffer(),await this.maintain(e)}async maintain(e=this.getCurrentPosition()){ve(e)||(await this.maintainPlaybackBuffer(e),await this.maintainNativeBuffer(),this.actualizeLastSegmentInfo(e))}getForwardPlaybackBufferDuration(e=this.getCurrentPosition()){let t=this.getPlaybackBufferState();return oe(t)&&oe(e)?t.to-e:0}getPlaybackBufferState(){if(!this.bufferPlaybackQueue.length)return null;let t=this.bufferPlaybackQueue[0].segment.time.from,i=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segment.time.to;return{from:t,to:i}}async abort(){this.abortDownload(),await this.abortNativeBuffer()}findSegmentStartTime(e){let t=this.downloadingRepresentationId??this.playingRepresentationId??"";return this.segments.get(t)?.find(a=>a.time.from<=e&&a.time.to>=e)?.time.from}getRepresentationInitialTime(){return ve(this.playingRepresentationId)?0:(this.segments.get(this.playingRepresentationId)?.[0].time.from??0)/1e3}calculateDurationFromSegments(){if(ve(this.playingRepresentationId))return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,qI.default)(e,-1)?.time.to:0)||0}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.initDataPromises.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.downloadAbortController.abort(),this.destroyAbortController.abort(),this.subscription.unsubscribe(),qe)for(let e of this.idleCallbacks.values())qe(e);this.idleCallbacks.clear(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}forceSwitchCondition(e,t){let i=!0;if(this.kind==="video"){let r=mi(e),a=mi(t);i=oe(r)&&oe(a)&&s0(a.quality,r.quality)}else if(this.kind==="audio"){let r=Ha(e),a=Ha(t);i=oe(r?.bitrate)&&oe(a?.bitrate)&&a.bitrate>r.bitrate}return i}async clearBuffer(){this.bufferClearingMutex=!0,await this.nativeBufferManager.clear(this.destroyAbortController.signal),this.bufferPlaybackQueue.forEach(e=>e.segment.bufferStatus="none"),this.bufferPlaybackQueue=[],this.bufferClearingMutex=!1}abortDownload(){this.downloadAbortController.abort(),this.downloadAbortController=new j,this.abortDownloadingItems(),this.maintainPlaybackBufferMutex=!1}abortDownloadingItems(){for(let e of this.downloadingBufferItems)e.segment.networkStatus==="downloading"&&(e.segment.networkStatus="none",e.segment.size=0,e.segment.loadedBytes=0,e.segment.feedingBytes=0,e.segment.fedBytes=0,e.segment.data=null);this.downloadingBufferItems=[]}async abortNativeBuffer(){this.abortNativeBufferMutex=!0;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0,i=await this.nativeBufferManager.abortBuffer(t);return this.abortNativeBufferMutex=!1,i}async loadInits(e){await this.loadInit(e,"high",!0);for(let[t,i]of this.representations)this.idleCallbacks.set(i.id,Mt(async r=>await this.loadInitIfNeeded(i,"low",!1)))}async loadInitIfNeeded(e,t="auto",i=!1){let r=this.initDataPromises.get(e.id),a;this.initData.has(e.id)&&this.segments.has(e.id)?a=Promise.resolve():oe(r)?a=r:a=this.loadInit(e,t,i),await a}async loadInit(e,t="auto",i=!1){try{let r=this.tuning.dash.useFetchPriorityHints?t:"auto",a=this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r);this.initDataPromises.set(e.id,a);let{initMetadata:n,initDataView:o,segments:u}=await a??{};if(this.initDataPromises.delete(e.id),ve(o)||ve(u))return;n&&this.parsedInitData.set(e.id,n);let l=o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength);this.initData.set(e.id,l),this.segments.set(e.id,u),this.failedDownloads=0}catch(r){i&&this.error$.next({id:"LoadInits",category:t0.WTF,message:"loadInit threw",thrown:r})}}async maintainNativeBuffer(){let e=this.getCurrentPosition();if(ve(e)||this.maintainNativeBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex||this.preloadOnly)return;this.maintainNativeBufferMutex=!0;let t=this.bufferPlaybackQueue.find(o=>this.withinInterval(e,o.segment.time)),i=this.bufferPlaybackQueue.find(o=>o.segment.bufferStatus!=="fed"),r=this.initData.get(i?.representationId??""),a=this.bufferPlaybackQueue[0],n=this.downloadAbortController.signal;oe(r)&&oe(i)&&oe(t)&&this.playingRepresentationId!==i.representationId&&this.withinAppendInterval(e,i.segment.time)&&(i===t||t.segment.bufferStatus==="fed")&&(await this.abortNativeBuffer(),await this.nativeBufferManager.addInitSegment(r,this.downloadAbortController.signal),this.playingRepresentationId=i.representationId,this.playingRepresentation$.next(this.playingRepresentationId)),oe(i)&&this.withinAppendInterval(e,i.segment.time)&&(i.segment.loadedBytes===i.segment.size&&i.segment.bufferStatus==="none"?await this.appendSegmentFully(i,n):await this.appendSegmentPartially(i,n)),oe(a)&&this.withinRemoveInterval(e,a.segment.time)&&await this.removeSegment(a,n),this.pruneVirtualBuffer(e),this.maintainNativeBufferMutex=!1}async maintainPlaybackBuffer(e){Lt(this.downloadingRepresentationId);let t=this.segments.get(this.downloadingRepresentationId),i=this.representations.get(this.downloadingRepresentationId);if(ve(t)||ve(i)||this.maintainPlaybackBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex)return;this.maintainPlaybackBufferMutex=!0;let r=t.find(n=>e>=n.time.from&&e<n.time.to);oe(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from),this.downloadingBufferItems.length||(this.downloadingBufferItems=this.selectDownloadingItems(e,t)),await this.processCachedItems();let a=this.selectItemsToLoad();await this.loadItems(a,i),this.maintainPlaybackBufferMutex=!1}actualizeLastSegmentInfo(e){let t=this.segments.get(this.downloadingRepresentationId??"");if(ve(t)||t.length===0)return;let i=t[t?.length-1];ve(i)||(this.fullyBuffered$.next(i.time.to-e-this.getForwardPlaybackBufferDuration(e)<this.tuning.dash.bufferTolerance),this.onLastSegment$.next(e-i.time.from>0))}selectDownloadingItems(e,t){Lt(this.downloadingRepresentationId);let i=this.getPlaybackBufferState(),r,a;oe(i)&&this.withinInterval(e,i)?(a=this.forwardBufferTarget-this.getForwardPlaybackBufferDuration(e),r=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segmentIndex+1):(a=this.forwardBufferTarget,r=t.findIndex(o=>this.withinInterval(e,o.time))),r=r===-1?0:r;let n=[];for(;r<t.length&&a>0;){n.push({representationId:this.downloadingRepresentationId,segmentIndex:r,segment:t[r]});let{from:o,to:u}=t[r].time;a-=u-o,r++}return n}async processCachedItems(){let e=[...this.downloadingBufferItems];for(;e.length&&e[0].segment.networkStatus==="downloaded";)await this.onDownloadItem(e[0]),e.shift()}withinInterval(e,{from:t,to:i},r=this.tuning.dash.bufferTolerance){return oe(e)?e+r>=t&&e<i:!1}withinAppendInterval(e,{from:t,to:i}){let{actionTimeShiftFromSegment:r}=this.tuning.dash;return oe(e)?e+r>=t&&e+r<i||this.withinInterval(e,{from:t,to:i}):!1}withinRemoveInterval(e,{to:t}){let{actionTimeShiftFromSegment:i}=this.tuning.dash;return oe(e)?e-i>t:!1}async appendSegmentFully(e,t){if(ve(e.segment.data))return;e.segment.feedingBytes=e.segment.size,await this.nativeBufferManager.append(e.segment.data,t)&&(e.segment.fedBytes=e.segment.size,this.onItemFullyAppended(e))}async appendSegmentPartially(e,t){if(ve(e.segment.data)||ve(e.segment.loadedBytes)||ve(e.segment.feedingBytes)||ve(e.segment.fedBytes)||ve(e.segment.size))return;let i=e.segment.data,r=new DataView(i.buffer,i.byteOffset+e.segment.feedingBytes,i.byteLength-e.segment.feedingBytes),a=e.segment.loadedBytes!==e.segment.size?this.parseFeedableSegmentChunk(r):r;a?.byteLength&&(e.segment.bufferStatus="partially_fed",e.segment.feedingBytes+=a.byteLength,await this.nativeBufferManager.append(a,t)&&(e.segment.fedBytes+=a.byteLength,e.segment.fedBytes===e.segment.size&&this.onItemFullyAppended(e)))}parseFeedableSegmentChunk(e){return this.containerParser.parseFeedableSegmentChunk(e,!1)}onItemFullyDownloaded(e){e.segment.networkStatus="downloaded"}onItemFullyAppended(e){e.segment.bufferStatus="fed"}async removeSegment(e,t){let{from:i,to:r}=e.segment.time,a=(r-i)/4;await this.nativeBufferManager.remove(0,r-a,t)&&(e.segment.fedBytes=0,e.segment.feedingBytes=0,e.segment.bufferStatus="none",this.bufferPlaybackQueue.shift())}async onDownloadItem(e){if(!this.downloadingBufferItems.find(i=>i===e))return;let t=this.getCurrentPosition();return this.downloadingBufferItems=this.downloadingBufferItems.filter(i=>i!==e||i.segment.networkStatus!=="downloaded"),(this.preloadOnly||oe(t)&&!this.withinRemoveInterval(t,e.segment.time))&&!this.bufferPlaybackQueue.find(i=>i===e)&&this.bufferPlaybackQueue.push(e),this.maintainNativeBuffer()}pruneVirtualBuffer(e){let{maxVirtualBufferSize:t,virtualBufferPruneSize:i,bufferPruningSafeZone:r}=this.tuning.dash;if(this.currentVirtualBufferSize<t)return;let a=this.currentVirtualBufferSize-t+i;for(let n of this.segments.values())for(let o of n)oe(o.size)&&a>0&&o.time.to<=e-r&&o.bufferStatus==="none"&&o.networkStatus==="downloaded"&&(o.data=null,o.networkStatus="none",this.currentVirtualBufferSize-=o.size,a-=o.size);for(let n of this.segments.values())for(let o of[...n].reverse())oe(o.size)&&a>0&&o.time.from>=e+r&&o.bufferStatus==="none"&&o.networkStatus==="downloaded"&&!this.bufferPlaybackQueue.find(u=>u.segment===o)&&!this.downloadingBufferItems.find(u=>u.segment===o)&&(o.data=null,o.networkStatus="none",this.currentVirtualBufferSize-=o.size,a-=o.size)}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())this.updateRepresentationBaseUrl(t,e)}};import{ErrorCategory as u0,isNonNullable as l0,isNullable as jI,now as HI}from"@vkontakte/videoplayer-shared/es2024";var uu=class extends is{constructor(e,t,i,r){super(e,t,i,r)}async loadItems(e,t,i="auto"){let{signal:r}=this.downloadAbortController;if(r.aborted||!e.length)return;let{url:a,...n}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),!r.aborted)try{await this.fetcher.fetch(a,{...n,priority:i}),this.lastDataObtainedTimestampMs=HI(),this.failedDownloads=0}catch(o){this.abortDownloadingItems(),Le(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=0,t=0,i=[],r=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,a=this.preloadOnly?this.forwardBufferTarget:0,n=0;for(;n<this.downloadingBufferItems.length&&this.downloadingBufferItems[n].segment.networkStatus==="none"&&(e<=r||t<=a);){let o=this.downloadingBufferItems[n].segment;o.networkStatus="downloading",o.size=1/0,o.loadedBytes=0,o.feedingBytes=0,o.fedBytes=0,i.push(this.downloadingBufferItems[n]),e+=o.byte.to+1-o.byte.from,t+=o.time.to+1-o.time.from,n++}return i}prepareFetchParams(e,t){if(Ue(t.segmentReference))throw new Error("Representation is not byte range type");let{signal:i}=this.downloadAbortController,r=t.segmentReference.url,a={from:e[0].segment.byte.from,to:e[e.length-1].segment.byte.to};return{url:r,range:a,onProgress:async(o,u)=>{if(!i.aborted)try{this.lastDataObtainedTimestampMs=HI(),await this.onSomeDataLoaded({downloadingItems:e,dataView:o,loaded:u,signal:i,globalFrom:a?a.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:u0.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}},signal:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}async onSomeDataLoaded({downloadingItems:e,dataView:t,representationId:i,globalFrom:r,loaded:a,signal:n}){let o=this.representations.get(i);if(!(!this.downloadingBufferItems.length||jI(o)||jI(r)||n.aborted))for(let u of e){let{segment:l}=u,p=l.byte.from-r,c=l.byte.to-r,d=c-p+1,h=p<a,f=c<=a;l.size=d,h&&(l.networkStatus==="downloading"&&l.bufferStatus==="none"&&f?(l.data=new DataView(t.buffer,t.byteOffset+p,d),this.currentVirtualBufferSize+=l.size,this.onItemFullyDownloaded(u),l.loadedBytes=Math.min(d,a-p),await this.onDownloadItem(u)):l0(l.feedingBytes)&&this.tuning.dash.enableSubSegmentBufferFeeding&&l.networkStatus==="downloading"&&(l.loadedBytes=Math.min(d,a-p),f&&(this.currentVirtualBufferSize+=l.size,this.onItemFullyDownloaded(u)),l.loadedBytes>l.feedingBytes&&(l.data=new DataView(t.buffer,t.byteOffset+p,l.loadedBytes),await this.onDownloadItem(u))))}}updateRepresentationBaseUrl(e,t){if(Ue(e.segmentReference))throw new Error("Representation is not byte range type");e.segmentReference.url=t}};import{ErrorCategory as c0,isNullable as ip,now as zI}from"@vkontakte/videoplayer-shared/es2024";var rs=class extends is{constructor(e,t,i,r){super(e,t,i,r)}async loadItems(e,t,i="auto"){let{signal:r}=this.downloadAbortController;if(r.aborted||!e.length)return;let{url:a,...n}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),!r.aborted)try{let o=await this.fetcher.fetch(a,{...n,priority:i});if(this.lastDataObtainedTimestampMs=zI(),ip(o))return;let u=e[0],l=new DataView(o);u.segment.size=l.byteLength,u.segment.loadedBytes=l.byteLength,u.segment.data=l,this.onItemFullyDownloaded(u),await this.onDownloadItem(u),this.failedDownloads=0}catch(o){this.abortDownloadingItems(),Le(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=[];for(let t of this.downloadingBufferItems){let i=t.segment;i.networkStatus="downloading",i.size=1/0,i.loadedBytes=0,i.feedingBytes=0,i.fedBytes=0,e.push(t)}return e}prepareFetchParams(e,t){let i=this.getFetchUrl(e,t).toString(),{signal:r}=this.downloadAbortController;return{url:i,onProgress:async(n,o)=>{if(!r.aborted)try{this.lastDataObtainedTimestampMs=zI(),await this.onSomeDataLoaded({downloadingItems:e,dataView:n,loaded:o,signal:r,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:c0.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}},signal:r,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}getFetchUrl(e,t){if(!Ue(t.segmentReference))throw new Error("Representation is not template type");return new URL(e[0].segment.url,t.segmentReference.baseUrl)}async onSomeDataLoaded({downloadingItems:e,dataView:t,representationId:i,loaded:r,signal:a}){let n=e[0],{segment:o}=n,u=this.representations.get(i);!this.downloadingBufferItems.length||ip(u)||ip(o.feedingBytes)||o.networkStatus!=="downloading"||a.aborted||(o.loadedBytes=r,o.loadedBytes>o.feedingBytes&&this.tuning.dash.enableSubSegmentBufferFeeding&&(o.data=new DataView(t.buffer,t.byteOffset,o.loadedBytes),await this.onDownloadItem(n)))}updateRepresentationBaseUrl(e,t){if(!Ue(e.segmentReference))throw new Error("Representation is not template type");e.segmentReference.baseUrl=t}};var rp=D(Wi(),1),WI=D(Ge(),1);import{assertNonNullable as d0,ErrorCategory as p0,isNullable as jt,ValueSubject as QI}from"@vkontakte/videoplayer-shared/es2024";var lu=class extends rs{constructor(t,i,r,a){super(t,i,r,a);this.currentLiveSegmentServerLatency$=new QI(0);this.currentLowLatencySegmentLength$=new QI(0);this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.isActiveLowLatency=a.isActiveLowLatency}updateManifest(t){if(!t||[...this.segments.values()].every(r=>!r.length))return;let i=(0,rp.default)(t.streams[this.kind],r=>r.representations);for(let r of i){if(jt(r)||!Ue(r.segmentReference))return;let a=r.segmentReference.segments.map(p=>({...p,networkStatus:"none",bufferStatus:"none",size:void 0})),n=100,o=this.segments.get(r.id)??[],u=(0,WI.default)(o,-1)?.time.to??0,l=a?.findIndex(p=>u>=p.time.from+n&&u<=p.time.to+n);if(l===-1){let p=this.getActualLiveStartingSegments(r.segmentReference);this.segments.set(r.id,p)}else{let p=a.slice(l+1);this.segments.set(r.id,[...o,...p])}this.representations.set(r.id,r)}}proceedLowLatencyLive(){let t=this.downloadingRepresentationId;d0(t);let i=this.segments.get(t);if(i?.length){let r={representationId:t,segmentIndex:i.length-1,segment:i[i.length-1]};this.updateLowLatencyLive(r)}}getLiveSegmentsToLoadState(t){let i=t?.streams[this.kind],r=(0,rp.default)(i,n=>n.representations).find(n=>n.id===this.downloadingRepresentationId);if(jt(r))return;let a=this.segments.get(r.id);if(a?.length)return{from:a[0].time.from,to:a[a.length-1].time.to}}getRepresentationInitialTime(){if(jt(this.playingRepresentationId))return 0;let t=this.representations.get(this.playingRepresentationId)?.segmentReference;return jt(t)||!Ue(t)?0:this.getActualLiveStartingSegments(t)[0].time.from+this.tuning.dash.bufferTolerance}prepareFetchParams(t,i){return{...super.prepareFetchParams(t,i),isLowLatency:this.isActiveLowLatency()}}async onSomeDataLoaded({downloadingItems:t,...i}){await super.onSomeDataLoaded({downloadingItems:t,...i}),this.isActiveLowLatency()&&this.updateLowLatencyItemTime(t[0])}onItemFullyDownloaded(t){if(super.onItemFullyDownloaded(t),jt(t.segment.data)||!this.isActiveLowLatency())return;let i=t.segment.data,r=this.containerParser,{serverDataReceivedTimestamp:a,serverDataPreparedTime:n}=r.getServerLatencyTimestamps(i);a&&n&&this.currentLiveSegmentServerLatency$.next(n-a),this.updateLowLatencyItemTime(t),this.updateLowLatencyLive(t)}updateLowLatencyItemTime(t){let i=t.segment.data,r=this.representations.get(t.representationId)?.segmentReference;if(jt(t.segment.data)||jt(r)||!Ue(r))return;let a=this.containerParser;if(t.segment.isCurrentLowLatency){let{timescale:n}=r;t.segment.time.to=a.getChunkEndTime(i,n)}}updateLowLatencyLive(t){let i=0;for(let r of this.representations.values()){let a=r.segmentReference;if(!Ue(a))return;let n=this.segments.get(r.id)??[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(t.segment.time.from));if(o?.isCurrentLowLatency&&(o.time.to=t.segment.time.to,i=o.time.to-o.time.from,o.isCurrentLowLatency=!1),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(t.segment.time.to))&&this.isActiveLowLatency()){let l=Math.round(t.segment.time.to*a.timescale/1e3).toString(10),p=tt(a.segmentTemplateUrl,{segmentTime:l});n.push({networkStatus:"none",bufferStatus:"none",time:{from:t.segment.time.to,to:t.segment.time.to+this.tuning.dash.bufferTolerance},url:p,isCurrentLowLatency:!0})}}this.currentLowLatencySegmentLength$.next(i)}parseFeedableSegmentChunk(t){return this.containerParser.parseFeedableSegmentChunk(t,!0)}getFetchUrl(t,i){let r=super.getFetchUrl(t,i);return this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes"),r}async loadInit(t,i="auto",r=!1){try{let a=this.tuning.dash.useFetchPriorityHints?i:"auto",n=this.fetcher.fetchRepresentation(t.segmentReference,this.containerParser,a);this.initDataPromises.set(t.id,n);let{initMetadata:o,initDataView:u,segments:l}=await n??{};if(this.initDataPromises.delete(t.id),jt(u)||jt(l))return;o&&this.parsedInitData.set(t.id,o);let p=this.getActualLiveStartingSegments(t.segmentReference);this.segments.has(t.id)||this.segments.set(t.id,p);let c=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(t.id,c),this.failedDownloads=0}catch(a){r&&this.error$.next({id:"LoadInits",category:p0.WTF,message:"loadInit threw",thrown:a})}}getActualLiveStartingSegments(t){let i=t.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,a=[],n=0,o=i.length-1;do a.unshift(i[o]),n+=i[o].time.to-i[o].time.from,o--;while(n<r&&o>=0);return this.liveInitialAdditionalOffset=n-r,this.isActiveLowLatency()?[a[0]]:a}};var Qa=class{static getBufferManager(e,t,i,r){return r.manifest?.live?new lu(e,t,i,r):Ue(i[0].segmentReference)?new rs(e,t,i,r):new uu(e,t,i,r)}};import{ErrorCategory as m0,fromEvent as b0,isNullable as ss,Subject as g0,Subscription as S0}from"@vkontakte/videoplayer-shared/es2024";import{assertNever as h0,ErrorCategory as GI,Subject as YI}from"@vkontakte/videoplayer-shared/es2024";var f0=18,KI=!1;try{KI=$.browser.isSafari&&!!$.browser.safariVersion&&$.browser.safariVersion<=f0}catch(s){console.error(s)}var sp=class{constructor(e){this.bufferFull$=new YI;this.error$=new YI;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null,this.queue.shift()}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:GI.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 r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};KI&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,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)&&!this.abortRequested)return;let e=this.queue[0];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(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:GI.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),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:h0(t)}}},XI=sp;var de=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){let r=s.start(i)*1e3,a=s.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};var Wa=class{constructor(e){this.error$=new g0;this.subscription=new S0;this.mediaSource=e}init(e,t){this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e}; codecs="${t}"`),this.sourceBufferTaskQueue=new XI(this.sourceBuffer),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(i=>this.error$.next(i))),this.subscription.add(b0(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:m0.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"})))}addInitSegment(e,t){return this.sourceBufferTaskQueue.append(e,t)}append(e,t){return this.sourceBufferTaskQueue.append(e,t)}remove(e,t,i){return this.sourceBufferTaskQueue.remove(e,t,i)}async clear(e){let t=this.getBufferState();if(ss(t))return Promise.resolve(!1);let i=!0;await this.sourceBufferTaskQueue.abort();for(let r of t)i&&=await this.sourceBufferTaskQueue.remove(r.from,r.to,e);return i}warmUpMediaSource(){!ss(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}getBufferState(){if(ss(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length)return null;let e=[];for(let t=0;t<this.sourceBuffer.buffered.length;t++)e.push({from:this.sourceBuffer.buffered.start(t)*1e3,to:this.sourceBuffer.buffered.end(t)*1e3});return e}getForwardBufferDuration(e){return ss(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ss(e)?0:de(this.sourceBuffer.buffered,e)}async abortBuffer(e){return ss(this.sourceBuffer)?!1:this.sourceBufferTaskQueue.abort(e)}destroy(){if(this.subscription.unsubscribe(),this.sourceBufferTaskQueue?.destroy(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null}};var w0=["timeupdate","progress","play","seeked","stalled","waiting"],eE=["timeupdate","progress","loadeddata","playing","seeked"],du=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.nativeBufferManagers=[];this.subscription=new ZI;this.subscriptionRemovable=new E0;this.representationSubscription=new ZI;this.forceEnded$=new gi;this.destroyController=new j;this.state$=new O("none");this.currentVideoRepresentation$=new Z(void 0);this.currentVideoRepresentationInit$=new Z(void 0);this.currentAudioRepresentation$=new Z(void 0);this.currentVideoSegmentLength$=new Z(0);this.currentAudioSegmentLength$=new Z(0);this.error$=new gi;this.manifestRequested=new gi;this.manifestReceived=new gi;this.firstBytesRequested=new gi;this.firstBytesReceived=new gi;this.lastConnectionType$=new Z(void 0);this.lastConnectionReused$=new Z(void 0);this.lastRequestFirstBytes$=new Z(void 0);this.currentLiveTextRepresentation$=new Z(null);this.isLive$=new Z(!1);this.isActiveLive$=new Z(!1);this.isLowLatency$=new Z(!1);this.liveDuration$=new Z(0);this.liveSeekableDuration$=new Z(0);this.liveAvailabilityStartTime$=new Z(0);this.liveStreamStatus$=new Z(void 0);this.currentBuffer$=new Z({from:0,to:0});this.bufferLength$=new Z(0);this.nativeBufferLength$=new Z(0);this.liveLatency$=new Z(void 0);this.liveLoadBufferLength$=new Z(0);this.livePositionFromPlayer$=new Z(0);this.currentStallDuration$=new Z(0);this.videoLastDataObtainedTimestamp$=new Z(0);this.fetcherRecoverableError$=new gi;this.fetcherError$=new gi;this.initRepresentations=JI(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",cu({initialVideo:e,initialAudio:t,sourceHls:i})),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest};this.createBuffers(r,e,t,i),this.initRepresentationSubscriptions(),yield this.waitStreamToOpen(),this.setSourceDuration(),Ht(this.videoBufferManager),yield Promise.all([this.videoBufferManager.startWith(e),t?this.audioBufferManager?.startWith(t):Promise.resolve()]),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.fetchManifest=JI(this.destroyController.signal,async function*(){try{return yield this.fetcher.fetchManifest(this.manifestUrlString)}catch(e){Ga(this.manifest)&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Xi.NETWORK,message:"Failed to load manifest",thrown:e})}}.bind(this));this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new iu({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.initTracerSubscription()}async initManifest(e,t,i){this.tracer.log("initManifest"),this.state$.startTransitionTo("manifest_ready"),this.element=e,this.manifestUrlString=this.prepareManifestUrlString(t,i),this.manifest=await this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Xi.PARSER,message:"No playable video representations"})}initBuffer(){Ht(this.element),this.state$.setState("running"),this.subscription.add(Ya(...w0.map(t=>Ji(this.element,t)),Ji(window,"online")).subscribe(()=>this.tick(),t=>this.error$.next({id:"DashVKPlayer",category:Xi.WTF,message:"Internal logic error",thrown:t})));let e=[...this.source?.activeSourceBuffers??[]];this.subscription.add(Ya(...e.map(t=>Ji(t,"updateend"))).subscribe(t=>this.reinitDecoderIfNeeded())),this.subscription.add(Ji(this.element,"waiting").subscribe(t=>{this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=T0(this.tuning.dash.stallWatchdogInterval).subscribe(()=>this.stallWatchdogIntervalCallback(),i=>this.error$.next({id:"StallWatchdogCallback",category:Xi.NETWORK,message:"Can't restore DASH after stall.",thrown:i})),this.subscriptionRemovable.add(this.stallWatchdogSubscription)}))}async switchRepresentation(e,t,i=!1){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,i)}async seek(e,t=!1){Ht(this.element),Ht(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),this.warmUpMediaSourceIfNeeded(i),this.element.currentTime=i/1e3,await this.videoBufferManager.seek(i),await this.audioBufferManager?.seek(i),this.tracer.log("seek",cu({requestedPosition:e,forcePrecise:t,position:i}))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){bi(this.element)&&bi(this.source)&&bi(e)&&this.isStreamEnded&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.nativeBufferManagers.forEach(t=>t.warmUpMediaSource())}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}get isStreamEnded(){return this.source?.readyState==="ended"}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setBufferTarget(e){this.bufferManagers.forEach(t=>t.setTarget(e))}setPreloadOnly(e){this.bufferManagers.forEach(t=>t.setPreloadOnly(e))}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.nativeBufferManagers.forEach(e=>e.destroy()),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),bi(this.source)&&this.isStreamNotOpen&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}get isStreamNotOpen(){return this.source?.readyState!=="open"}async reinitDecoderIfNeeded(e=!1){let t=this.videoNativeBufferManager?.getBufferState()??[];if(Ga(this.element)||!t.length)return;let i=this.element.currentTime*1e3;this.element.readyState<3&&t.some(r=>i>=r.from&&i<=r.to)&&(e?await this.seek(i):this.element.currentTime=this.element.currentTime)}async stallWatchdogIntervalCallback(){Ht(this.element),Ht(this.source);let{stallWatchdogInterval:e}=this.tuning.dash;if(this.isStreamNotOpen)return;let t=this.currentStallDuration$.getValue()+e;this.currentStallDuration$.next(t);let i={timeInWaiting:t};if(await this.reinitDecoderIfNeeded(t%1e3===0),this.isStallExceeded(t))throw new Error(`Stall timeout exceeded: ${t} ms`);await this.restoreAfterDeepStall(i),this.tracer.log("stallIntervalCallback",cu(i))}isStallExceeded(e){let{crashOnStallTimeout:t,crashOnStallTWithoutDataTimeout:i}=this.tuning.dash,r=I0(),a=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardPlaybackBufferDuration()??0,l=this.audioBufferManager?.getForwardPlaybackBufferDuration()??0,p=bi(this.videoBufferManager)&&u<a&&r-n>i,c=bi(this.audioBufferManager)&&l<a&&r-o>i;return(p||c)&&e>i||e>=t}async updateManifest(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=await this.fetchManifest();if(Ga(e))return null;let t=this.parseManifest(e);if(!t)return null;let i=this.getResultManifest(t);return this.tracer.log("updateManifestEnd",cu(i)),i}parseManifest(e){try{return Xr(e??"",this.manifestUrlString)}catch(t){let i=Hr(e)??{id:"ManifestParsing",category:Xi.PARSER,message:"Failed to parse MPD manifest",thrown:t};this.error$.next(i)}}getResultManifest(e){let t={text:e.streams.text,video:[],audio:[]},i=(o,u,l)=>!!(this.element?.canPlayType?.(u)&&Ve()?.isTypeSupported?.(`${u}; codecs="${l}"`)||o==="text"),r,a;for(let o of["video","audio"]){let l=e.streams[o].filter(({mime:c,codecs:d})=>i(o,c,d));t[o]=l;let p;if(this.tuning.dash.codecsPrioritizeEnabled){let c=l.map(({codecs:d})=>d);o==="audio"&&(a=es(c),p=a[0]),o==="video"&&(r=Zr(c),this.forceVideoCodec&&(0,tE.default)(r,this.forceVideoCodec)?p=this.forceVideoCodec:p=r[0]),p&&(t[o]=l.filter(({codecs:d})=>hi(d)===p))}else{let c=new Set(l.map(({codecs:d})=>d));p=Jr(c),p&&(t[o]=l.filter(({codecs:d})=>d.startsWith(p)))}if(o==="video"){let c=this.tuning.preferHDR,d=t.video.some(f=>f.hdr),h=t.video.some(f=>!f.hdr);$.display.isHDR&&c&&d?t.video=t.video.filter(f=>f.hdr):h&&(t.video=t.video.filter(f=>!f.hdr))}}let n={...e,streams:t};return this.tuning.dash.codecsPrioritizeEnabled&&(n.codecs={video:r,audio:a}),n}stopStallWatchdogSubscription(){this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)}createBuffers(e,t,i,r){Ht(this.manifest),Ht(this.element);let a=u=>{this.representationSubscription.add(Ji(u,"error").pipe(ap(l=>!!this.element?.played.length)).subscribe(l=>{this.error$.next({id:"VideoSource",category:Xi.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:l})}))};this.source=Ir();let n=document.createElement("source");if(a(n),n.src=URL.createObjectURL(this.source),this.element.appendChild(n),ai())if(r){let u=document.createElement("source");a(u),u.type="application/x-mpegurl",u.src=r.url,this.element.appendChild(u)}else this.element.disableRemotePlayback=!0;let o=this.manifest.streams.video.reduce((u,l)=>[...u,...l.representations],[]);if(this.videoNativeBufferManager=new Wa(this.source),this.videoBufferManager=Qa.getBufferManager("video",this.videoNativeBufferManager,o,e),this.bufferManagers=[this.videoBufferManager],this.nativeBufferManagers=[this.videoNativeBufferManager],bi(i)){this.audioNativeBufferManager=new Wa(this.source);let u=this.manifest.streams.audio.reduce((l,p)=>[...l,...p.representations],[]);this.audioBufferManager=Qa.getBufferManager("audio",this.audioNativeBufferManager,u,e),this.bufferManagers.push(this.audioBufferManager),this.nativeBufferManagers.push(this.audioNativeBufferManager)}}async waitStreamToOpen(){if(this.isStreamNotOpen){let e=this.tuning.dash.sourceOpenTimeout>=0;await new Promise(t=>{e&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.isStreamNotOpen){t();return}this.error$.next({id:"OpenOfStream",category:Xi.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),t()},{once:!0})})}}initRepresentationSubscriptions(){this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),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(Ya(...this.bufferManagers.map(e=>e.error$)).subscribe(this.error$)),Ht(this.videoBufferManager),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.initBufferLengthSubscription()}initBufferLengthSubscription(){this.representationSubscription.add(Ya(...eE.map(e=>Ji(this.element,e))).pipe(np(e=>this.videoBufferManager?.getPlaybackBufferState()),ap(bi),np(({from:e,to:t})=>({from:e/1e3,to:t/1e3}))).subscribe(this.currentBuffer$)),this.representationSubscription.add(Ya(...eE.map(e=>Ji(this.element,e))).pipe(np(e=>Math.max(this.videoBufferManager?.getForwardPlaybackBufferDuration()??0,this.audioBufferManager?.getForwardPlaybackBufferDuration()??0)),v0()).subscribe(this.bufferLength$)),this.representationSubscription.add(this.nativeBufferLength$.pipe(ap(e=>e>this.tuning.dash.bufferEmptinessTolerance)).subscribe(e=>this.stopStallWatchdogSubscription()))}initTracerSubscription(){let e=y0(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}async tick(){if(Ga(this.element)||Ga(this.videoBufferManager)||this.isStreamNotOpen)return;let e=this.element.currentTime*1e3,i=(this.videoNativeBufferManager?.getBufferState()??[]).find(r=>e>=r.from&&e<=r.to);this.nativeBufferLength$.next(i?i.to-e:0),await this.videoBufferManager.maintain(e),await this.audioBufferManager?.maintain(e)}};import{assertNonNullable as pu,combine as x0,ErrorCategory as k0,filter as op,filterChanged as P0,fromEvent as A0,isNonNullable as R0,map as up,merge as Ka}from"@vkontakte/videoplayer-shared/es2024";var hu=class extends du{constructor(e){super(e)}prepareManifestUrlString(e,t){return e}initRepresentationSubscriptions(){super.initRepresentationSubscriptions(),this.initDisableStallWatchdogSubscription(),this.initEndOfVideoSubscription()}setSourceDuration(){pu(this.manifest),pu(this.source);let e=[this.manifest.duration??0,...(0,lp.default)((0,lp.default)([...this.manifest.streams.audio,...this.manifest.streams.video],t=>t.representations),t=>{let i=[];return t.duration&&i.push(t.duration),Ue(t.segmentReference)&&t.segmentReference.totalSegmentsDurationMs&&i.push(t.segmentReference.totalSegmentsDurationMs),i})];this.source.duration=Math.max(...e)/1e3}async restoreAfterDeepStall(e){pu(this.element);let t=this.element.currentTime*1e3;await Promise.all([this.videoBufferManager?.maintain(t),this.audioBufferManager?.maintain(t)]),e.position=t}initDisableStallWatchdogSubscription(){pu(this.element);let e=Ka(A0(this.element,"ended"),this.forceEnded$),t=this.nativeBufferLength$.pipe(op(i=>i>this.tuning.dash.bufferEmptinessTolerance));this.representationSubscription.add(Ka(e,t).subscribe(i=>this.stopStallWatchdogSubscription()))}initEndOfVideoSubscription(){let e=Ka(...this.bufferManagers.map(a=>a.fullyBuffered$)).pipe(up(()=>this.bufferManagers.every(a=>a.fullyBuffered$.getValue()))),t=Ka(...this.bufferManagers.map(a=>a.onLastSegment$)).pipe(up(()=>this.bufferManagers.some(a=>a.onLastSegment$.getValue()))),i=x0({allBuffersFull:e,someBufferEnded:t}).pipe(P0(),up(({allBuffersFull:a,someBufferEnded:n})=>a&&n),op(a=>a)),r=()=>{try{this.source?.endOfStream()}catch(a){this.error$.next({id:"EndOfStream",category:k0.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:a})}};this.representationSubscription.add(Ka(this.forceEnded$,i).pipe(op(a=>R0(this.source)&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(n=>!n.updating))).subscribe(r))}};var as=class extends pa{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i,genericErrorListener:r}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$),this.subscription.add(this.player.currentVideoRepresentation$.pipe($0()).subscribe(a=>{let n=[...this.videoTracksMap.entries()].find(([,{representation:c}])=>c.id===a);if(!n){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[o,{stream:u}]=n,l=this.params.desiredState.videoStream.getTransition();l&&l.to&&l.to.id===u.id&&this.params.desiredState.videoStream.setState(l.to),e.currentVideoTrack$.next(o),e.currentVideoStream$.next(Wo(u));let p=this.player.calculateDurationFromSegments();p&&this.params.output.duration$.next(p/1e3)},r))}getPlayer(){return new hu({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec})}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{assertNever as t_,assertNonNullable as i_,combine as r_,debounce as s_,ErrorCategory as fE,filter as vp,filterChanged as nn,fromEvent as a_,isNonNullable as mE,isNullable as n_,map as on,merge as un,observableFrom as xu,once as bE,Subscription as o_,throttle as u_}from"@vkontakte/videoplayer-shared/es2024";var hE=D(ke(),1),gp=D(Wi(),1);var De=(s,e,t=0)=>{for(let i=0;i<s.length;i++)if(s.start(i)*1e3-t<=e&&s.end(i)*1e3+t>e)return!0;return!1};import{abortable as fp,assertNonNullable as cs,combine as ds,ErrorCategory as ct,filter as Iu,filterChanged as rn,flattenObject as sn,fromEvent as Wt,getTraceSubscriptionMethod as j0,interval as mp,isNonNullable as an,isNullable as cE,map as ps,merge as tr,now as bp,Subject as Gt,Subscription as dE,SubscriptionRemovable as H0,tap as z0,throttle as Q0,ValueSubject as ee}from"@vkontakte/videoplayer-shared/es2024";var mu=D(ke(),1),er=D(Ge(),1),bu=D(Wi(),1);var nE=D(Ro(),1);import{assertNever as M0,ErrorCategory as iE,Subject as rE}from"@vkontakte/videoplayer-shared/es2024";var L0=18,sE=!1;try{sE=$.browser.isSafari&&!!$.browser.safariVersion&&$.browser.safariVersion<=L0}catch(s){console.error(s)}var cp=class{constructor(e,t=!1){this.bufferFull$=new rE;this.error$=new rE;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:iE.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};sE&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,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)&&!this.abortRequested)return;let e=this.isAbortFixEnabled?this.queue[0]: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(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:iE.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),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:M0(t)}}},aE=cp;var ns=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};import{abortable as Si,assertNonNullable as je,ErrorCategory as zt,fromEvent as dp,getExponentialDelay as pp,isHigher as D0,isNonNullable as vi,isNullable as pe,now as fu,once as B0,Subject as C0,Subscription as V0,ValueSubject as Zi}from"@vkontakte/videoplayer-shared/es2024";var Xa=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Zi(0);this.currentLowLatencySegmentLength$=new Zi(0);this.currentSegmentLength$=new Zi(0);this.onLastSegment$=new Zi(!1);this.fullyBuffered$=new Zi(!1);this.playingRepresentation$=new Zi(void 0);this.playingRepresentationInit$=new Zi(void 0);this.error$=new C0;this.gaps=[];this.subscription=new V0;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new j;this.switchAbortController=new j;this.destroyAbortController=new j;this.useSmartRepresentationSwitch=!1;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=Si(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);je(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new aE(this.sourceBuffer,this.tuning.dash.useAbortMSEFix),this.subscription.add(dp(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:zt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:zt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add(dp(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:zt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!V(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,ns(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<p).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),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),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);je(i,"No init buffer for starting representation"),je(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))}.bind(this));this.switchTo=Si(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);je(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(pe(a)||pe(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),je(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();vi(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Si(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);je(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(pe(a)||pe(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),je(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();vi(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=Si(this.destroyAbortController.signal,async function*(e){let t=(0,bu.default)(e,u=>u.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let u of this.representations.keys()){let l=t.find(d=>d.id===u);l&&this.representations.set(u,l);let p=this.representations.get(u);if(!p||!it(p.segmentReference)){this.isSeekingLive=!1;return}let c=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);je(r,`Representation not found by id ${i}`);let a=this.segments.get(i);je(a,"No segments for starting representation");let n=this.initData.get(i);if(je(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(p=>[p.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(p=>[p.id,p])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new j,Si(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);je(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(pe(o)||pe(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),je(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();vi(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))}warmUpMediaSource(){!pe(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new j,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(pe(e)||pe(this.downloadingRepresentationId)||pe(this.playingRepresentationId)||pe(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||vi(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),a=this.segments.get(this.playingRepresentationId);if(je(t,`No such representation ${this.downloadingRepresentationId}`),je(i,`No such representation ${this.playingRepresentationId}`),pe(r)||pe(a))return;let n=r.find(d=>e>=d.time.from&&e<d.time.to);vi(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next(n?.time.to-n.time.from);let o=e,u=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=this.getForwardBufferDuration(e),h=mi(i),f=mi(t),m=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&vi(h)&&vi(f)&&D0(h.quality,f.quality),S=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(m||S?o+=Math.min(d,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=n.time.to-e+u&&(o=n?n.time.to+u:-1/0),this.tuning.dash.useNewRepresentationSwitch){let v=[...this.segments.entries()].map(([T,y])=>{let x=y.find(A=>e>=A.time.from&&e<A.time.to);return{representationId:T,status:x?.status}}).find(T=>T.status==="fed")?.representationId;v&&(this.playingRepresentationId=v,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&ns(this.sourceBuffer.buffered)>=this.bufferLimit){let d=this.getForwardBufferDuration(e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let p=[];if(!this.activeSegments.size&&(p=this.selectForwardBufferSegments(r,t.segmentReference.type,o),p.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,mu.default)(p,n))d="high";else{let h=(0,er.default)(p,0);h&&h.time.from-n.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(p,t,d).catch(h=>{this.handleAsyncError(h,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!p.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let c=(0,er.default)(r,-1);!this.isLive&&c&&(this.fullyBuffered$.next(c.time.to-e-this.getForwardBufferDuration(e)<u),this.onLastSegment$.next(e-c.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r,persistent:!0}),i=a.time.to;vi(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind];if(!t)return;let i=(0,bu.default)(t,a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){if(!e||[...this.segments.values()].every(i=>!i.length))return;let t=(0,bu.default)(e.streams[this.kind],i=>i.representations);for(let i of t){if(!i||!it(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),a=100,n=this.segments.get(i.id)??[],o=(0,er.default)(n,-1)?.time.to??0,u=r?.findIndex(l=>o>=l.time.from+a&&o<=l.time.to+a);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(u+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;je(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,er.default)(e,-1)?.time.to:0)||0}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!it(r))return;let a=this.segments.get(i.id)??[],n=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=tt(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(a=>a.time.from<=e&&a.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&&qe&&qe(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&qe&&qe(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)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(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),a=e.findIndex(({status:d,time:{from:h,to:f}},m)=>{let S=h<=i&&f>=i,g=h>i||S||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&h<=i+v||r<v&&f-h>=v||f<=i+v;return(d==="none"||d==="partially_ejected"&&g&&T&&this.sourceBuffer&&V(this.mediaSource,this.sourceBuffer)&&!(De(this.sourceBuffer.buffered,h)&&De(this.sourceBuffer.buffered,f)))&&g&&T});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,l=[],p=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<n.length&&(o<=p||u<=c);d++){let h=n[d];if(o+=h.byte.to+1-h.byte.from,u+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){it(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 r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Si(o,async function*(){let p=pp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,p))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let p=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=fu(),!p)return;let c=new DataView(p),d=lt(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(c,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=d.getServerLatencyTimestamps(c);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(p){this.abortActiveSegments([e]),Le(p)||(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())it(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:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Si(n,async function*(){let u=pp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),dp(window,"online").pipe(B0()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=fu(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Le(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(it(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,er.default)(e,0).byte.from,to:(0,er.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:async(o,u)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=fu(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:zt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!it(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 r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,p)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=fu();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:p,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:zt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,mu.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!V(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),p=lt(n.mime).parseFeedableSegmentChunk(l,this.isLive);p?.byteLength&&(u.status="partially_fed",o.feedingBytes+=p.byteLength,await this.sourceBufferTaskQueue.append(p),o.fedBytes+=p.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!V(this.mediaSource,this.sourceBuffer))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(a.aborted){await n();continue}let p=l.byte.from-i,c=l.byte.to-i,d=c-p+1,h=p<r,f=c<=r;if(!h)continue;let m=lt(o.mime);if(l.status==="downloading"&&f){l.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+p,d);await this.sourceBufferTaskQueue.append(S,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(d,r-p),u.loadedBytes>u.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+p+u.feedingBytes,u.loadedBytes-u.feedingBytes),g=u.loadedBytes===d?S:m.parseFeedableSegmentChunk(S);g?.byteLength&&(l.status="partially_fed",u.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,a)&&!a.aborted?(u.fedBytes+=g.byteLength,u.fedBytes===d&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){if(!(pe(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer))){!this.isLive&&$.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(De(this.sourceBuffer.buffered,e.segment.time.from,100)&&De(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:zt.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.tuning.dash.useNewRepresentationSwitch||(this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))),e.segment.status="fed",ep(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&Math.round(r.time.from)===Math.round(e.segment.time.from)&&Math.round(r.time.to)===Math.round(e.segment.time.to)&&(r.status="none");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[r,a]of this.initData.entries()){let n=a instanceof Promise;t||=n,a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Mt(()=>(0,nE.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",a=!i&&this.tuning.dash.ignoreNetworkErrorsOnLoadInit,o=(!i&&this.failedDownloads>0?Si(this.destroyAbortController.signal,async function*(){let u=pp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,lt(e.mime),{priority:r,ignoreNetworkErrors:a})).then(async u=>{if(!u)return;let{init:l,dataView:p,segments:c}=u,d=p.buffer.slice(p.byteOffset,p.byteOffset+p.byteLength);this.initData.set(e.id,d);let h=c;this.isLive&&it(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),l&&this.parsedInitData.set(e.id,l)}).then(()=>this.failedDownloads=0,u=>{a||this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:zt.WTF,message:"loadInit threw",thrown:u})});return this.initData.set(e.id,o),o}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||!V(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||pe(e))return!1;let r=[],a=0,n=u=>{u.sort((p,c)=>p.from-c.from);let l=[u[0]];for(let p=1;p<u.length;p++){let{from:c,to:d}=u[p],h=l[l.length-1];h.to>=c?h.to=Math.max(h.to,d):l.push(u[p])}return l},o=u=>{if(a>=t)return r;r.push({...u.time}),r=n(r);let l=ep(u)?u.size??0:u.byte.to-u.byte.from;a+=l};for(let u of this.segments.values())for(let l of u){let p=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(p||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,p=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let d of this.segments.values())for(let h of d)(0,mu.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(p)&&c++;if(c===this.segments.size){let d={time:{from:l,to:p},url:"",status:"none"};o(d)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let p of l)p.time.from>=e+u&&p.status==="fed"&&o(p)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,p)=>l||p,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||pe(e)?0:de(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)))for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to,persistent:!1},{buffered:a}=this.sourceBuffer;for(let n=0;n<a.length;n++){let o=a.start(n)*1e3,u=a.end(n)*1e3;if(!(u<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&u>=i.time.to){r=void 0;break}u>i.time.from&&u<i.time.to&&(r.from=u),o<i.time.to&&o>i.time.from&&(r.to=o)}}r&&r.to-r.from>1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,{usePersistentGaps:r}=this.tuning.dash;this.gaps=this.gaps.filter(a=>{if(r&&a.persistent)return!0;let n=Math.round(a.from),o=Math.round(a.to);for(let u=0;u<i.length;u++)if(n>=Math.round(i.start(u)*1e3)&&o<=Math.round(i.end(u)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=Mt(()=>{try{this.detectGaps(e,t)}catch(a){this.error$.next({id:"GapDetection",category:zt.WTF,message:"detectGaps threw",thrown:a})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(pe(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||pe(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),a=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(p=>p.from-t<=n&&p.to+t>=o),l=e.filter(p=>n>=p.from&&n<p.to-t||o>p.from+t&&o<=p.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(p=>p.from===r.time.from||p.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:zt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};import{abortable as Ja,assertNever as oE,fromEvent as uE,merge as _0,now as Za,Subject as os,ValueSubject as hp,flattenObject as us,ErrorCategory as en,SubscriptionRemovable as O0}from"@vkontakte/videoplayer-shared/es2024";var Su=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.manifestRequested$=new os;this.firstBytesManifest$=new os;this.firstBytesRequested$=new os;this.firstBytesReceived$=new os;this.lastConnectionType$=new hp(void 0);this.lastConnectionReused$=new hp(void 0);this.lastRequestFirstBytes$=new hp(void 0);this.recoverableError$=new os;this.error$=new os;this.abortAllController=new j;this.subscription=new O0;this.fetchManifest=Ja(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Tt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Qr(i)),this.manifestRequested$.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(gu);return r?(t.log("success",us({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),this.firstBytesManifest$.next(),r.text()):(t.error("error",us({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Ja(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:l=!1,ignoreNetworkErrors:p=!1}={}){let c=e,d=new Headers,h=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let I=new URL(c,location.href);I.searchParams.append("bytes",`${i.from}-${i.to}`),c=I.toString();break}default:oE(t)}this.requestQuic&&(c=Tt(c));let f=this.abortAllController.signal,m;if(n){let I=new j;if(m=_0(uE(this.abortAllController.signal,"abort"),uE(n,"abort")).subscribe(()=>{try{I.abort()}catch(N){gu(N)}}),this.subscription.add(m),this.abortAllController.signal.aborted||n.aborted)try{I.abort()}catch(N){gu(N)}f=I.signal}let S=0,g=Za();h.log("startRequest",us({url:c,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:g})),this.firstBytesRequested$.next();let v=yield this.doFetch(c,{priority:a,headers:d,signal:f},{ignoreNetworkErrors:p}),T=Za();if(!v)return h.error("error",{message:"No response in request"}),h.end(),this.unsubscribeAbortSubscription(m),null;if(this.throughputEstimator?.addRawRtt(T-g),!v.ok||!v.body){this.unsubscribeAbortSubscription(m);let I=`Fetch error ${v.status}: ${v.statusText}`;return h.error("error",{message:I}),h.end(),Promise.reject(new Error(`Fetch error ${v.status}: ${v.statusText}`))}if(this.onHeadersReceived(v.headers),!r&&!o){this.unsubscribeAbortSubscription(m);let I=Za(),N={requestStartedAt:g,requestEndedAt:I,duration:I-g};return h.log("endRequest",us(N)),h.end(),v.arrayBuffer()}let y=v.body;if(o){let I;[y,I]=v.body.tee(),this.throughputEstimator?.trackStream(I,u)}let x=y.getReader(),A,R=parseInt(v.headers.get("content-length")??"",10);Number.isFinite(R)&&(A=R),!A&&i&&(A=i.to-i.from+1);let w=A?new Uint8Array(A):new Uint8Array(0),B=!1,k=I=>{this.unsubscribeAbortSubscription(m),B=!0,gu(I)},F=Ja(f,async function*({done:I,value:N}){if(S===0&&(this.lastRequestFirstBytes$.next(Za()-g),this.firstBytesReceived$.next()),f.aborted){this.unsubscribeAbortSubscription(m);return}if(!I&&N){if(l&&A)w.set(N,S),S+=N.byteLength;else{let L=new Uint8Array(w.length+N.length);L.set(w),L.set(N,w.length),w=L,S+=N.byteLength}r?.(new DataView(w.buffer),S),yield x?.read().then(F,k)}}.bind(this));yield x?.read().then(F,k),this.unsubscribeAbortSubscription(m);let C=Za(),E={failed:B,requestStartedAt:g,requestEndedAt:C,duration:C-g};return B?(h.error("endRequest",us(E)),h.end(),null):(h.log("endRequest",us(E)),h.end(),w.buffer)}.bind(this));this.fetchByteRangeRepresentation=Ja(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,p;e.indexRange&&(l=e.indexRange.from,p=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(p,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},measureThroughput:!1,...i});if(!c)return null;let d=new DataView(c,r-n,a-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),f=e.indexRange??t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(c,f.from-n,f.to-f.from+1);else{let g=yield this.fetch(e.url,{range:f,measureThroughput:!1});if(!g)return null;m=new DataView(g)}let S=t.parseSegments(m,h,f);return{init:h,dataView:new DataView(c),segments:S}}.bind(this));this.fetchTemplateRepresentation=Ja(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{measureThroughput:!1,...t});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=zr(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:oE(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t,i){let r=await Ke(e,t);if(r.ok)return r;if(i?.ignoreNetworkErrors)return;let a=await r.text(),n=parseInt(a);if(!isNaN(n))switch(n){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:en.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:en.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:en.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:en.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${n})`,category:en.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},gu=s=>{if(!Le(s))throw s};import{isNullable as N0,ValueSubject as lE}from"@vkontakte/videoplayer-shared/es2024";var yi=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 lE(e.initial),this.debounced$=new lE(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ne(`raw_${t}`),this.smoothedSeries$=new Ne(`smoothed_${t}`),this.reportedSeries$=new Ne(`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 r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;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>a||this.smoothed<n)&&(N0(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 vu=class extends yi{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Ft(this.slow,e,this.params.emaAlphaSlow),this.fast=Ft(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var yu=class extends yi{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Id(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ft(this.emaSmoothed,e,this.params.emaAlpha);let i=_y(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Tu=class extends yi{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?Ft(this.smoothed,t,this.params.emaAlpha):t}};var Qt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new vu({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new yu({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new Tu({initial:e,label:"liveEdgeDelay",...t})}};var ls=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)};import{isNullable as F0,ValueSubject as U0}from"@vkontakte/videoplayer-shared/es2024";var tn=class s{constructor(e,t){this.currentRepresentation$=new U0(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(!F0(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,a=r.segments.length,n=r.segments[0].time.from,o=r.segments[a-1].time.to;if(e<n||e>o)continue;let u=r.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,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=s.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=>s.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&it(t.segmentReference))}};var W0=["timeupdate","progress","play","seeked","stalled","waiting"],G0=["timeupdate","progress","loadeddata","playing","seeked"];var Eu=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new dE;this.subscriptionRemovable=new H0;this.representationSubscription=new dE;this.state$=new O("none");this.currentVideoRepresentation$=new ee(void 0);this.currentVideoRepresentationInit$=new ee(void 0);this.currentAudioRepresentation$=new ee(void 0);this.currentVideoSegmentLength$=new ee(0);this.currentAudioSegmentLength$=new ee(0);this.error$=new Gt;this.manifestRequested$=new Gt;this.firstBytesManifest$=new Gt;this.manifestReceived$=new Gt;this.firstBytesRequested$=new Gt;this.firstBytesReceived$=new Gt;this.lastConnectionType$=new ee(void 0);this.lastConnectionReused$=new ee(void 0);this.lastRequestFirstBytes$=new ee(void 0);this.currentLiveTextRepresentation$=new ee(null);this.isLive$=new ee(!1);this.isActiveLive$=new ee(!1);this.isLowLatency$=new ee(!1);this.liveDuration$=new ee(0);this.liveSeekableDuration$=new ee(0);this.liveAvailabilityStartTime$=new ee(0);this.liveStreamStatus$=new ee(void 0);this.bufferLength$=new ee(0);this.liveLatency$=new ee(void 0);this.liveLoadBufferLength$=new ee(0);this.livePositionFromPlayer$=new ee(0);this.currentStallDuration$=new ee(0);this.videoLastDataObtainedTimestamp$=new ee(0);this.fetcherRecoverableError$=new Gt;this.fetcherError$=new Gt;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Gt;this.gapWatchdogActive=!1;this.liveWasInterrupted=!1;this.destroyController=new j;this.initManifest=fp(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ne(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:ct.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=fp(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ct.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Xr(e??"",this.manifestUrlString),this.manifestReceived$.next()}catch(u){let l=Hr(e)??{id:"ManifestParsing",category:ct.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,p)=>!!(this.element?.canPlayType?.(l)&&Ve()?.isTypeSupported?.(`${l}; codecs="${p}"`)||u==="text");if(t.live){this.isLive$.next(!0);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:p,streamIsAlive:c}=t.live,d=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*d),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";if(c||(h=p?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h),c&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let f=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(f).catch(m=>{this.error$.next({id:"updateManifest",category:ct.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:m})})}}let r={text:t.streams.text,video:[],audio:[]},a,n;for(let u of["video","audio"]){let p=t.streams[u].filter(({mime:d,codecs:h})=>i(u,d,h));r[u]=p;let c;if(this.tuning.dash.codecsPrioritizeEnabled){let d=p.map(({codecs:h})=>h);u==="audio"&&(n=es(d),c=n[0]),u==="video"&&(a=Zr(d),this.forceVideoCodec&&(0,hE.default)(a,this.forceVideoCodec)?c=this.forceVideoCodec:c=a[0]),c&&(r[u]=p.filter(({codecs:h})=>hi(h)===c))}else{let d=new Set(p.map(({codecs:h})=>h));c=Jr(d),c&&(r[u]=p.filter(({codecs:h})=>h.startsWith(c)))}if(u==="video"){let d=this.tuning.preferHDR,h=r.video.some(m=>m.hdr),f=r.video.some(m=>!m.hdr);$.display.isHDR&&d&&h?r.video=r.video.filter(m=>m.hdr):f&&(r.video=r.video.filter(m=>!m.hdr))}}let o={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:a,audio:n}),this.tracer.log("updateManifestEnd",sn(o)),o}.bind(this));this.initRepresentations=fp(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",sn({initialVideo:e,initialAudio:t,sourceHls:i})),cs(this.manifest),cs(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=c=>{this.representationSubscription.add(Wt(c,"error").pipe(Iu(d=>!!this.element?.played.length)).subscribe(d=>{this.error$.next({id:"VideoSource",category:ct.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:d})}))};this.source=Ir();let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),ai())if(i){let c=document.createElement("source");r(c),c.type="application/x-mpegurl",c.src=i.url,this.element.appendChild(c)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((c,d)=>[...c,...d.representations],[]);if(this.videoBufferManager=new Xa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],an(t)){let c=this.manifest.streams.audio.reduce((d,h)=>[...d,...h.representations],[]);this.audioBufferManager=new Xa("audio",this.source,c,n),this.bufferManagers.push(this.audioBufferManager)}if(tn.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new tn(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(tr(...G0.map(c=>Wt(this.element,c))).pipe(ps(c=>this.element?de(this.element.buffered,this.element.currentTime*1e3):0),rn(),z0(c=>{c>this.tuning.dash.bufferEmptinessTolerance&&this.stopStallWatchdogSubscription()})).subscribe(this.bufferLength$)),this.representationSubscription.add(tr(Wt(this.element,"ended"),this.forceEnded$).subscribe(()=>{this.stopStallWatchdogSubscription()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(rn()).subscribe(d=>this.liveStreamEndTimestamp=bp())),this.subscription.add(Wt(this.element,"pause").subscribe(()=>{let{liveUpdateInterval:d}=this.tuning.dash;this.livePauseWatchdogSubscription=mp(d).subscribe(h=>{let f=si(this.manifestUrlString,2);this.manifestUrlString=ne(this.manifestUrlString,f+d,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Wt(this.element,"play").subscribe(d=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(ds({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ps(({isActiveLive:d,isLowLatency:h})=>d&&h),rn()).subscribe(d=>{this.isManualDecreasePlaybackInLive()||ls(this.element,1)})),this.representationSubscription.add(ds({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Iu(({bufferLength:d,isActiveLive:h,isLowLatency:f})=>h&&f&&!!d)).subscribe(({bufferLength:d})=>this.liveBuffer.next(d))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(d=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!d)return;let h=this.liveSeekableDuration$.getValue()-d/1e3;this.liveSeekableDuration$.next(Math.max(h,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+d/1e3)})),this.representationSubscription.add(ds({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Iu(({isLive:d})=>d),rn((d,h)=>h.bufferLength<d.bufferLength),ps(({rtt:d,bufferLength:h,segmentServerLatency:f})=>{let m=si(this.manifestUrlString,2);return(d/2+h+f+m)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(ds({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:d,isActiveLive:h,isLowLatency:f})=>{if(!f||!h)return;let m=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,g=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,v=d-m;if(this.isManualDecreasePlaybackInLive())return;let T=1;Math.abs(v)>S&&(T=1+Math.sign(v)*g),ls(this.element,T)})),this.representationSubscription.add(this.bufferLength$.subscribe(d=>{let h=0;if(d){let f=(this.element?.currentTime??0)*1e3;h=Math.min(...this.bufferManagers.map(S=>S.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==h&&this.liveLoadBufferLength$.next(h)}));let c=0;this.representationSubscription.add(ds({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Q0(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:d,bufferLength:h})=>{if(!this.element||this.isUpdatingLive)return;let f=this.element.playbackRate,m=si(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,g=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),v=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,T=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,y=isFinite(d)?d:h,x=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),A=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(A);let R="none";if(x?R="active_low_latency":this.isLowLatency$.getValue()&&A?(this.bufferManagers.forEach(w=>w.proceedLowLatencyLive()),R="active_low_latency"):m!==0&&y<g?R="live_forward_buffering":y<g+T&&(R="live_with_target_offset"),isFinite(d)&&(c=d>c?d:c),R==="live_forward_buffering"||R==="live_with_target_offset"){let w=c-(g+v),B=this.normalizeLiveOffset(Math.trunc(m+w/f)),k=Math.abs(B-m),F=0;!d||k<=this.tuning.dashCmafLive.offsetCalculationError?F=m:B>0&&k>this.tuning.dashCmafLive.offsetCalculationError&&(F=B),this.manifestUrlString=ne(this.manifestUrlString,F,2)}(R==="live_with_target_offset"||R==="live_forward_buffering")&&(c=0,await this.updateLive())},d=>{this.error$.next({id:"updateLive",category:ct.VIDEO_PIPELINE,thrown:d,message:"Failed to update live with subscription"})}))}let u=tr(...this.bufferManagers.map(c=>c.fullyBuffered$)).pipe(ps(()=>this.bufferManagers.every(c=>c.fullyBuffered$.getValue()))),l=tr(...this.bufferManagers.map(c=>c.onLastSegment$)).pipe(ps(()=>this.bufferManagers.some(c=>c.onLastSegment$.getValue()))),p=ds({allBuffersFull:u,someBufferEnded:l}).pipe(rn(),ps(({allBuffersFull:c,someBufferEnded:d})=>c&&d),Iu(c=>c));if(this.representationSubscription.add(tr(this.forceEnded$,p).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(c=>!c.updating))try{this.source?.endOfStream()}catch(c){this.error$.next({id:"EndOfStream",category:ct.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:c})}})),this.representationSubscription.add(tr(...this.bufferManagers.map(c=>c.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"){let c=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(d=>{c&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){d();return}this.error$.next({id:"OpenOfStream",category:ct.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),d()},{once:!0})})}if(!this.isLive$.getValue()){let c=[this.manifest.duration??0,...(0,gp.default)((0,gp.default)([...this.manifest.streams.audio,...this.manifest.streams.video],d=>d.representations),d=>{let h=[];return d.duration&&h.push(d.duration),it(d.segmentReference)&&d.segmentReference.totalSegmentsDurationMs&&h.push(d.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...c)/1e3}this.audioBufferManager&&an(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||this.source?.readyState!=="open")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=mp(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:ct.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new Su({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.firstBytesRequested$.subscribe(this.firstBytesRequested$)),this.subscription.add(this.fetcher.firstBytesReceived$.subscribe(this.firstBytesReceived$)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.liveBuffer=Qt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){cs(this.element),this.updateManifestUrlWithTimeOffset(e),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.updateLiveBuffersFromManifest(this.manifest))}updateManifestUrlWithTimeOffset(e){let t=this.liveStreamStatus$.getValue()!=="active"?bp()-this.liveStreamEndTimestamp:0,i=this.normalizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ne(this.manifestUrlString,i,2)}async updateLiveBuffersFromManifest(e){await this.videoBufferManager?.seekLive(e.streams.video),await this.audioBufferManager?.seekLive(e.streams.audio),this.liveTextManager?.seekLive(e.streams.text)}stopStallWatchdogSubscription(){this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)}initBuffer(){cs(this.element),this.state$.setState("running"),this.subscription.add(tr(...W0.map(e=>Wt(this.element,e)),Wt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ct.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Wt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Wt(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===2&&!this.element.seeking&&De(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{let{keepSilentStallWatchdogWhenNotActive:t}=this.tuning.dashCmafLive,{crashOnStallTimeout:i,crashOnStallTWithoutDataTimeout:r,liveStallReinitInterval:a,stallWatchdogInterval:n}=this.tuning.dash,o=this.isLive$.getValue(),l=this.liveStreamStatus$.getValue()==="active";if(!this.element||this.source?.readyState!=="open")return;let p=this.currentStallDuration$.getValue();p+=n,this.currentStallDuration$.next(p);let c={timeInWaiting:p},d=bp(),h=100,f=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(f);let m=this.audioBufferManager?.lastDataObtainedTimestamp??0,S=this.videoBufferManager?.getForwardBufferDuration()??0,g=this.audioBufferManager?.getForwardBufferDuration()??0,v=S<h&&d-f>r,T=this.audioBufferManager&&g<h&&d-m>r;if((!t||l)&&((v||T)&&p>r||p>=i))throw new Error(`Stall timeout exceeded: ${p} ms`);if(o&&p%a===0){let y=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);!l&&t?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(y),this.updateManifest()):this.seekLive(y).catch(x=>{this.error$.next({id:"stallIntervalCallback",category:ct.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:x})}),c.liveLastOffset=y}else{let y=this.element.currentTime*1e3;this.videoBufferManager?.maintain(y),this.audioBufferManager?.maintain(y),c.position=y}this.tracer.log("stallIntervalCallback",sn(c))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=mp(this.tuning.dash.stallWatchdogInterval).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:ct.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){cs(this.element),cs(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),this.warmUpMediaSourceIfNeeded(i),De(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(cE(this.element)||cE(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",sn({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){an(this.element)&&an(this.source)&&an(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),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}getCodecs(){return this.manifest?.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),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=j0(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normalizeLiveOffset(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=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime},{usePersistentGaps:r}=this.tuning.dash;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let a=this.element.currentTime*1e3,n=[],o=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(r&&l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=a&&l.to+o>a&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n.push(1/0):n.push(l.to));if(n.length){let u=Math.max(...n)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,i={...i,gapEnds:n,jumpTo:u,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",sn(i)))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};import{combine as Y0,map as K0,observeElementSize as X0,Subscription as J0,ValueSubject as Sp,noop as Z0}from"@vkontakte/videoplayer-shared/es2024";var wu=class{constructor(){this.subscription=new J0;this.pipSize$=new Sp(void 0);this.videoSize$=new Sp(void 0);this.elementSize$=new Sp(void 0);this.pictureInPictureWindowRemoveEventListener=Z0}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(X0(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(Y0({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(K0(({videoSize:r,inPip:a,pipSize:n})=>a?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var ir=class{constructor(e){this.subscription=new o_;this.videoState=new O("stopped");this.observableVideo=null;this.droppedFramesManager=new li;this.stallsManager=new qr;this.elementSizeManager=new wu;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new yt;this.audioTrackSwitchHistory=new yt;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),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.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&P(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return t_(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new di(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.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new We(e.source.url),this.params=e,this.video=Pe(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(ce(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 Eu({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;n_(this.observableVideo)&&(this.observableVideo=$e(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:fE.WTF,message:`${i} internal logic error`,thrown:n})},a=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:a}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(vp(c=>!!c.length),bE()).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(on(c=>c.to.state!=="none"),nn());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.currentBuffer$,e.currentNativeBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.manifestRequested$,e.manifestRequested$),a(this.player.firstBytesManifest$,e.firstBytesManifest$),a(this.player.manifestReceived$,e.manifestReceived$),a(this.player.firstBytesRequested$,e.firstBytesRequested$),a(this.player.firstBytesReceived$,e.firstBytesReceived$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(vp(mE),bE()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(on(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),pi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(Re(this.video,t.volume,i.volumeState$,r)),this.subscription.add(Qe(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Ye(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")})),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(),h=this.player.getCodecs();if(i_(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let S of d.audio){m.push(Jd(S));let g=[];for(let v of S.representations){let T=Ha(v);g.push(T),this.audioTracksMap.set(T,{stream:S,representation:v})}this.audioStreamsMap.set(S,g)}this.params.output.availableAudioStreams$.next(m)}let f=[];for(let m of d.video){f.push(Zd(m));let S=[];for(let g of m.representations){let v=mi({...g,streamId:m.id});v&&(S.push(v),this.videoTracksMap.set(v,{stream:m,representation:g}))}this.videoStreamsMap.set(m,S)}this.params.output.availableVideoStreams$.next(f);for(let m of d.text)for(let S of m.representations){let g=FI(m,S);this.textTracksMap.set(g,{stream:m,representation:S})}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),h?.video&&this.params.output.availableVideoCodecs$.next(h.video),h?.audio&&this.params.output.availableAudioCodecs$.next(h.audio),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())},r));let o=un(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,a_(this.video,"progress")).pipe(vp(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe(u_(u))),this.subscription.add(o.subscribe(async()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[f,m]=h,S=[...this.videoTracksMap.keys()].find(v=>this.videoTracksMap.get(v)?.representation.id===f.id);mE(S)&&(this.stallsManager.lastVideoTrackSelected=S);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")await this.player.initRepresentations(f.id,m?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",f.id),m){let v=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",m.id,v)}},r)),this.subscription.add(r_({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:un(xu([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(on(c=>c.to)))}).pipe(on(({videoState:c,autoVideoTrackState:d})=>c.to!=="stopped"&&d),nn()).subscribe(c=>this.player.setSmartRepresentationSwitch(c))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(nn()).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:f}]=d,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Zd(f));let S=this.player.calculateDurationFromSegments();S&&this.params.output.duration$.next(S/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(nn()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:S}])=>S.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:f}]=d,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(Jd(f))},r)),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)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(on(({to:c})=>c==="ready"),nn());this.subscription.add(un(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,xu(["init"])).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(un(l,this.player.state$.stateChangeEnded$,xu(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let p=un(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,xu(["init"])).pipe(s_(0));this.subscription.add(p.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Qi:zi,t=this.params.tuning.useNewAutoSelectVideoTrack?Fr:Nr,i=this.params.tuning.useNewAutoSelectVideoTrack?ut:Or,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,u=[...this.videoTracksMap.keys()].find(({id:w})=>w===o),l=a.currentVideoTrack$.getValue(),p=r.videoStream.getState()??(u&&this.videoTracksMap.get(u)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!p)return;let c=[...this.videoStreamsMap.keys()].find(({id:w})=>w===p.id),d=c&&this.videoStreamsMap.get(c);if(!d)return;let h=de(this.video.buffered,this.video.currentTime*1e3),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(f,m||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),v=[...this.audioStreamsMap.keys()].find(({id:w})=>w===g?.id)??this.audioStreamsMap.keys().next().value,T=0;if(v){if(u&&!n){let w=e(u,d,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}if(l){let w=e(l,d,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}}let y=u;(n||!y)&&(y=i(d,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:T,forwardBufferHealth:S,current:l,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}));let x=v&&t(y,d,this.audioStreamsMap.get(v)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),A=this.videoTracksMap.get(y)?.representation,R=x&&this.audioTracksMap.get(x)?.representation;if(A&&R)return[A,R];if(A&&!R&&this.audioTracksMap.size===0)return[A,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:fE.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Ae(this.video),this.tracer.end()}};var ln=class extends ir{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)}};import{combine as yp,merge as gE,filter as SE,filterChanged as vE,isNullable as Tp,map as yE,ValueSubject as Ip,isNonNullable as l_}from"@vkontakte/videoplayer-shared/es2024";var cn=class extends ir{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:a,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let o=new Ip(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(vE()).subscribe(u=>{let l=i.position$.getValue(),p=i.volume$.getValue(),c=!p.volume||p.muted;!u&&!l&&c?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(a.isLowLatency.stateChangeEnded$.pipe(yE(u=>u.to)).subscribe(this.player.isLowLatency$)).add(yp({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(yE(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u*1e3+l+t:void 0)).subscribe(i.liveTime$)).add(yp({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:gE(r.playbackRateState$,new Ip(1))}).pipe(SE(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let p=i.liveBufferTime$.getValue(),c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||l<1-d||this.video.paused||Tp(p)||(t=u-p)})).add(yp({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:gE(r.playbackRateState$,new Ip(1))}).pipe(vE((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:p})=>{let c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&p>=1-d||Tp(u)||Tp(l))return;let h=-1*(l-u-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let l=UI(u);this.params.output.availableTextTracks$.next([l])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe(SE(u=>l_(u))).subscribe(u=>i.isLiveEnded$.next(u==="unpublished"&&i.position$.getValue()===0)))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as __,assertNonNullable as O_,combine as N_,debounce as F_,ErrorCategory as _E,filter as Op,filterChanged as yn,fromEvent as U_,isNonNullable as OE,isNullable as q_,map as Tn,merge as In,observableFrom as Vu,once as NE,Subscription as j_}from"@vkontakte/videoplayer-shared/es2024";var VE=D(ke(),1),Vp=D(Wi(),1);import{abortable as Lp,assertNonNullable as ms,combine as bs,ErrorCategory as Et,filter as Du,filterChanged as gn,flattenObject as Sn,fromEvent as Dt,getTraceSubscriptionMethod as k_,interval as Dp,isNonNullable as vn,isNullable as BE,map as gs,merge as or,now as Bp,Subject as Yt,Subscription as Cp,SubscriptionRemovable as P_,tap as A_,throttle as CE,ValueSubject as te}from"@vkontakte/videoplayer-shared/es2024";var Ru=D(ke(),1),nr=D(Ge(),1),$u=D(Wi(),1);var $E=D(Ro(),1);import{assertNever as c_,ErrorCategory as TE,Subject as IE}from"@vkontakte/videoplayer-shared/es2024";var d_=18,EE=!1;try{EE=$.browser.isSafari&&!!$.browser.safariVersion&&$.browser.safariVersion<=d_}catch(s){console.error(s)}var Ep=class{constructor(e,t=!1){this.bufferFull$=new IE;this.error$=new IE;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:TE.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};EE&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,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)&&!this.abortRequested)return;let e=this.isAbortFixEnabled?this.queue[0]: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(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:TE.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),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:c_(t)}}},wE=Ep;import{abortable as Ti,assertNonNullable as He,ErrorCategory as sr,fromEvent as Ap,getExponentialDelay as Rp,isHigher as b_,isNonNullable as Ii,isNullable as he,now as Au,once as g_,Subject as S_,Subscription as v_,ValueSubject as ar}from"@vkontakte/videoplayer-shared/es2024";var wp=D(Ge(),1);import{videoSizeToQuality as p_,throttleFn as h_}from"@vkontakte/videoplayer-shared/es2024";var dn=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{let o=(a?$t(a):void 0)??p_({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},xE=({id:s,bitrate:e})=>({id:s,bitrate:e}),kE=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),PE=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),xp=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,wp.default)(i.split("."),0),isDefault:r}),kp=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,wp.default)(r.split("."),0)}),Pp=s=>"url"in s,rt=s=>s.type==="template";var AE=s=>{s.sort((t,i)=>t.from-i.from);let e=[s[0]];for(let t=1;t<s.length;t++){let{from:i,to:r}=s[t],a=e[e.length-1];a.to>=i?a.to=Math.max(a.to,r):e.push(s[t])}return e},rr=(s,e)=>{for(let t of s)if(e(t))return t;return null},RE=s=>{let e=!1,t=h_(()=>{e=!0},s);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as f_,Subscription as m_}from"@vkontakte/videoplayer-shared/es2024";var ku=s=>{let e=[];for(let t=0;t<s.length;t++){let i=Math.floor(s.start(t)*1e3),r=Math.ceil(s.end(t)*1e3);e.push(i,r)}return e};var Pu=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new m_;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(f_(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!V(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=ku(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],a=e[i+1],n=t[i],o=t[i+1];if(n>r||o<a)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var pn=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new ar(0);this.currentLowLatencySegmentLength$=new ar(0);this.currentSegmentLength$=new ar(0);this.onLastSegment$=new ar(!1);this.fullyBuffered$=new ar(!1);this.playingRepresentation$=new ar(void 0);this.playingRepresentationInit$=new ar(void 0);this.error$=new S_;this.gaps=[];this.subscription=new v_;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new j;this.switchAbortController=new j;this.destroyAbortController=new j;this.useSmartRepresentationSwitch=!1;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.sourceBufferBufferedDiff=null;this.startWith=Ti(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);He(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new wE(this.sourceBuffer,this.tuning.dash.useAbortMSEFix),this.sourceBufferBufferedDiff=new Pu(this.mediaSource,this.sourceBuffer),this.subscription.add(Ap(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(Ap(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:sr.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!V(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,ns(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=de(this.sourceBuffer.buffered,o),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<p).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),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),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);He(i,"No init buffer for starting representation"),He(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))}.bind(this));this.switchTo=Ti(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);He(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(he(a)||he(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),He(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();Ii(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Ti(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);He(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(he(a)||he(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),He(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();Ii(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=Ti(this.destroyAbortController.signal,async function*(e){let t=(0,$u.default)(e,u=>u.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let u of this.representations.keys()){let l=t.find(d=>d.id===u);l&&this.representations.set(u,l);let p=this.representations.get(u);if(!p||!rt(p.segmentReference)){this.isSeekingLive=!1;return}let c=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);He(r,`Representation not found by id ${i}`);let a=this.segments.get(i);He(a,"No segments for starting representation");let n=this.initData.get(i);if(He(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(p=>[p.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(p=>[p.id,p])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new j,Ti(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);He(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(he(o)||he(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),He(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();Ii(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))}warmUpMediaSource(){!he(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new j,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(he(e)||he(this.downloadingRepresentationId)||he(this.playingRepresentationId)||he(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||Ii(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),a=this.segments.get(this.playingRepresentationId);if(He(t,`No such representation ${this.downloadingRepresentationId}`),He(i,`No such representation ${this.playingRepresentationId}`),he(r)||he(a))return;let n=r.find(d=>e>=d.time.from&&e<d.time.to);Ii(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next(n?.time.to-n.time.from);let o=e,u=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=this.getForwardBufferDuration(e),h=dn(i),f=dn(t),m=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&Ii(h)&&Ii(f)&&b_(h.quality,f.quality),S=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(m||S?o+=Math.min(d,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=n.time.to-e+u&&(o=n?n.time.to+u:-1/0),this.tuning.dash.useNewRepresentationSwitch){let v=[...this.segments.entries()].map(([T,y])=>{let x=y.find(A=>e>=A.time.from&&e<A.time.to);return{representationId:T,status:x?.status}}).find(T=>T.status==="fed")?.representationId;v&&(this.playingRepresentationId=v,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&ns(this.sourceBuffer.buffered)>=this.bufferLimit){let d=de(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let p=null;if(!this.activeSegments.size&&(p=this.selectForwardBufferSegments(r,t.segmentReference.type,o),p?.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,Ru.default)(p,n))d="high";else{let h=(0,nr.default)(p,0);h&&h.time.from-n.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(p,t,d).catch(h=>{this.handleAsyncError(h,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!p?.length&&de(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let c=(0,nr.default)(r,-1);!this.isLive&&c&&(this.fullyBuffered$.next(c.time.to-e-de(this.sourceBuffer.buffered,e)<u),this.onLastSegment$.next(e-c.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r,persistent:!0}),i=a.time.to;Ii(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind];if(!t)return;let i=(0,$u.default)(t,a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){if(!e||[...this.segments.values()].every(i=>!i.length))return;let t=(0,$u.default)(e.streams[this.kind],i=>i.representations)??[];for(let i of t){if(!i||!rt(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),a=100,n=this.segments.get(i.id)??[],o=(0,nr.default)(n,-1)?.time.to??0,u=r?.findIndex(l=>o>=l.time.from+a&&o<=l.time.to+a);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(u+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;He(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!rt(r))return;let a=this.segments.get(i.id);if(!a)continue;let n=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=tt(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(a=>a.time.from<=e&&a.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.sourceBufferBufferedDiff?.destroy(),this.gapDetectionIdleCallback&&qe&&qe(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&qe&&qe(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)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.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),a=e.findIndex(({status:d,time:{from:h,to:f}},m)=>{let S=h<=i&&f>=i,g=h>i||S||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&h<=i+v||r<v&&f-h>=v||f<=i+v;return(d==="none"||d==="partially_ejected"&&g&&T&&this.sourceBuffer&&V(this.mediaSource,this.sourceBuffer)&&!(De(this.sourceBuffer.buffered,h)&&De(this.sourceBuffer.buffered,f)))&&g&&T});if(a===-1)return null;if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,l=[],p=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<n.length&&(o<=p||u<=c);d++){let h=n[d];if(o+=h.byte.to+1-h.byte.from,u+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){rt(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 r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Ti(o,async function*(){let p=Rp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,p))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let p=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=Au(),!p)return;let c=new DataView(p),d=lt(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(c,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=d.getServerLatencyTimestamps(c);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(p){this.abortActiveSegments([e]),Le(p)||(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())rt(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:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Ti(n,async function*(){let u=Rp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Ap(window,"online").pipe(g_()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=Au(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Le(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(rt(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,nr.default)(e,0).byte.from,to:(0,nr.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:async(o,u)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=Au(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:sr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!rt(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 r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,p)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=Au();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:p,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:sr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Ru.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!V(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),p=lt(n.mime).parseFeedableSegmentChunk(l,this.isLive);p?.byteLength&&(u.status="partially_fed",o.feedingBytes+=p.byteLength,await this.sourceBufferTaskQueue.append(p),o.fedBytes+=p.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!V(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){if(u.representationId!==t)continue;if(a.aborted){await n();continue}let{segment:l}=u,p=l.byte.from-i,c=l.byte.to-i,d=c-p+1,h=p<r,f=c<=r;if(h){if(l.status==="downloading"&&f){l.status="downloaded";let m=new DataView(e.buffer,e.byteOffset+p,d);await this.sourceBufferTaskQueue.append(m,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(d,r-p),u.loadedBytes>u.feedingBytes)){let m=new DataView(e.buffer,e.byteOffset+p+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===d?m:lt(o.mime).parseFeedableSegmentChunk(m);S?.byteLength&&(l.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,a)&&!a.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===d&&this.onSegmentFullyAppended(u,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!(he(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer))){!this.isLive&&$.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(De(this.sourceBuffer.buffered,e.segment.time.from,100)&&De(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:sr.VIDEO_PIPELINE,message:"Browser 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",Pp(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let a of r)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")}this.isActiveLowLatency()&&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[r,a]of this.initData.entries()){let n=a instanceof Promise;t||=n,a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Mt(()=>(0,$E.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Ti(this.destroyAbortController.signal,async function*(){let o=Rp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,lt(e.mime),r)).then(o=>{if(!o)return;let{init:u,dataView:l,segments:p}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let d=p;this.isLive&&rt(e.segmentReference)&&(d=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,d),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:sr.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||!V(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||he(e))return!1;this.checkEjectedSegments();let r=[],a=0,n=o=>{if(a>=t)return;r.push({...o.time});let u=Pp(o)?o.size??0:o.byte.to-o.byte.from;a+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,p=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||p)&&u.status==="fed"&&n(u)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let u=this.sourceBuffer.buffered.start(o)*1e3,l=this.sourceBuffer.buffered.end(o)*1e3,p=0;for(let c of this.segments.values())for(let d of c)(0,Ru.default)(["none","partially_ejected"],d.status)&&Math.round(d.time.from)<=Math.round(u)&&Math.round(d.time.to)>=Math.round(l)&&p++;if(p===this.segments.size){let c={time:{from:u,to:l},url:"",status:"none"};n(c)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let l of u)l.time.from>=e+o&&l.status==="fed"&&n(l)}return r.length?(r=AE(r),(await Promise.all(r.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,l)=>u||l,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getBufferedTo(){return!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||he(e)?0:de(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let a=0;a<i.length;a++){let n=i.start(a)*1e3,o=i.end(a)*1e3;if(!(o<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&o>=t.time.to){r=void 0;break}o>t.time.from&&o<t.time.to&&(r.from=o),n<t.time.to&&n>t.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.gaps=this.gaps.filter(r=>{if(r.persistent)return!0;let a=Math.round(r.from),n=Math.round(r.to);for(let o=0;o<i.length;o++)if(a>=Math.round(i.start(o)*1e3)&&n<=Math.round(i.end(o)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=Mt(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:sr.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(he(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||he(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=ku(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=!1,l=0;for(let p=0;p<e.length;p+=2){let c=e[p],d=e[p+1];u||(u=c-t<=n&&d+t>=o),(n>=c&&n<d-t||o>c+t&&o<=d)&&(l+=1)}u||(l===1?r.status="partially_ejected":this.gaps.some(p=>p.from===r.time.from||p.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:sr.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,nr.default)(e,-1)?.time.to:0)||0}};import{abortable as hn,assertNever as ME,fromEvent as LE,merge as y_,now as fn,Subject as hs,ValueSubject as $p,flattenObject as fs,ErrorCategory as mn,SubscriptionRemovable as T_}from"@vkontakte/videoplayer-shared/es2024";var Lu=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.manifestRequested$=new hs;this.firstBytesManifest$=new hs;this.firstBytesRequested$=new hs;this.firstBytesReceived$=new hs;this.lastConnectionType$=new $p(void 0);this.lastConnectionReused$=new $p(void 0);this.lastRequestFirstBytes$=new $p(void 0);this.recoverableError$=new hs;this.error$=new hs;this.abortAllController=new j;this.subscription=new T_;this.fetchManifest=hn(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Tt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Qr(i)),this.manifestRequested$.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Mu);return r?(t.log("success",fs({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),this.firstBytesManifest$.next(),r.text()):(t.error("error",fs({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=hn(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:l=!1}={}){let p=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(p,location.href);E.searchParams.append("bytes",`${i.from}-${i.to}`),p=E.toString();break}default:ME(t)}this.requestQuic&&(p=Tt(p));let h=this.abortAllController.signal,f;if(n){let E=new j;if(f=y_(LE(this.abortAllController.signal,"abort"),LE(n,"abort")).subscribe(()=>{try{E.abort()}catch(I){Mu(I)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{E.abort()}catch(I){Mu(I)}h=E.signal}let m=0,S=fn();d.log("startRequest",fs({url:p,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:S})),this.firstBytesRequested$.next();let g=yield this.doFetch(p,{priority:a,headers:c,signal:h}),v=fn();if(!g)return d.error("error",{message:"No response in request"}),d.end(),this.unsubscribeAbortSubscription(f),null;if(this.throughputEstimator?.addRawRtt(v-S),!g.ok||!g.body){this.unsubscribeAbortSubscription(f);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),!r&&!o){this.unsubscribeAbortSubscription(f);let E=fn(),I={requestStartedAt:S,requestEndedAt:E,duration:E-S};return d.log("endRequest",fs(I)),d.end(),g.arrayBuffer()}let T=g.body;if(o){let E;[T,E]=g.body.tee(),this.throughputEstimator?.trackStream(E,u)}let y=T.getReader(),x,A=parseInt(g.headers.get("content-length")??"",10);Number.isFinite(A)&&(x=A),!x&&i&&(x=i.to-i.from+1);let R=x?new Uint8Array(x):new Uint8Array(0),w=!1,B=E=>{this.unsubscribeAbortSubscription(f),w=!0,Mu(E)},k=hn(h,async function*({done:E,value:I}){if(m===0&&(this.lastRequestFirstBytes$.next(fn()-S),this.firstBytesReceived$.next()),h.aborted){this.unsubscribeAbortSubscription(f);return}if(!E&&I){if(l&&x)R.set(I,m),m+=I.byteLength;else{let N=new Uint8Array(R.length+I.length);N.set(R),N.set(I,R.length),R=N,m+=I.byteLength}r?.(new DataView(R.buffer),m),yield y?.read().then(k,B)}}.bind(this));yield y?.read().then(k,B),this.unsubscribeAbortSubscription(f);let F=fn(),C={failed:w,requestStartedAt:S,requestEndedAt:F,duration:F-S};return w?(d.error("endRequest",fs(C)),d.end(),null):(d.log("endRequest",fs(C)),d.end(),R.buffer)}.bind(this));this.fetchByteRangeRepresentation=hn(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,p;e.indexRange&&(l=e.indexRange.from,p=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(p,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let d=new DataView(c,r-n,a-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),f=e.indexRange??t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(c,f.from-n,f.to-f.from+1);else{let g=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!g)return null;m=new DataView(g)}let S=t.parseSegments(m,h,f);return{init:h,dataView:new DataView(c),segments:S}}.bind(this));this.fetchTemplateRepresentation=hn(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=zr(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:ME(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await Ke(e,t);if(i.ok)return i;let r=await i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:mn.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:mn.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:mn.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:mn.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:mn.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Mu=s=>{if(!Le(s))throw s};import{isNullable as I_,ValueSubject as E_}from"@vkontakte/videoplayer-shared/es2024";var bn=class s{constructor(e,t){this.currentRepresentation$=new E_(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(!I_(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,a=r.segments.length,n=r.segments[0].time.from,o=r.segments[a-1].time.to;if(e<n||e>o)continue;let u=r.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,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=s.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=>s.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&rt(t.segmentReference))}};var R_=["progress","play","seeked","stalled","waiting"],$_=["timeupdate","progress","loadeddata","playing","seeked"];var Bu=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new Cp;this.subscriptionRemovable=new P_;this.representationSubscription=new Cp;this.state$=new O("none");this.currentVideoRepresentation$=new te(void 0);this.currentVideoRepresentationInit$=new te(void 0);this.currentAudioRepresentation$=new te(void 0);this.currentVideoSegmentLength$=new te(0);this.currentAudioSegmentLength$=new te(0);this.error$=new Yt;this.manifestRequested$=new Yt;this.firstBytesManifest$=new Yt;this.manifestReceived$=new Yt;this.firstBytesRequested$=new Yt;this.firstBytesReceived$=new Yt;this.lastConnectionType$=new te(void 0);this.lastConnectionReused$=new te(void 0);this.lastRequestFirstBytes$=new te(void 0);this.currentLiveTextRepresentation$=new te(null);this.isLive$=new te(!1);this.isActiveLive$=new te(!1);this.isLowLatency$=new te(!1);this.liveDuration$=new te(0);this.liveSeekableDuration$=new te(0);this.liveAvailabilityStartTime$=new te(0);this.liveStreamStatus$=new te(void 0);this.bufferLength$=new te(0);this.liveLatency$=new te(void 0);this.liveLoadBufferLength$=new te(0);this.livePositionFromPlayer$=new te(0);this.currentStallDuration$=new te(0);this.videoLastDataObtainedTimestamp$=new te(0);this.fetcherRecoverableError$=new Yt;this.fetcherError$=new Yt;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Yt;this.gapWatchdogActive=!1;this.destroyController=new j;this.initManifest=Lp(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ne(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:Et.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Lp(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Et.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Xr(e??"",this.manifestUrlString),this.manifestReceived$.next()}catch(u){let l=Hr(e)??{id:"ManifestParsing",category:Et.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,p)=>!!(this.element?.canPlayType?.(l)&&Ve()?.isTypeSupported?.(`${l}; codecs="${p}"`)||u==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:p,streamIsAlive:c}=t.live,d=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*d),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";c||(h=p?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h)}let r={text:t.streams.text,video:[],audio:[]},a,n;for(let u of["video","audio"]){let p=t.streams[u].filter(({mime:d,codecs:h})=>i(u,d,h));r[u]=p;let c;if(this.tuning.dash.codecsPrioritizeEnabled){let d=p.map(({codecs:h})=>h);u==="audio"&&(n=es(d),c=n[0]),u==="video"&&(a=Zr(d),this.forceVideoCodec&&(0,VE.default)(a,this.forceVideoCodec)?c=this.forceVideoCodec:c=a[0]),c&&(r[u]=p.filter(({codecs:h})=>hi(h)===c))}else{let d=new Set(p.map(({codecs:h})=>h));c=Jr(d),c&&(r[u]=p.filter(({codecs:h})=>h.startsWith(c)))}if(u==="video"){let d=this.tuning.preferHDR,h=r.video.some(m=>m.hdr),f=r.video.some(m=>!m.hdr);$.display.isHDR&&d&&h?r.video=r.video.filter(m=>m.hdr):f&&(r.video=r.video.filter(m=>!m.hdr))}}let o={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:a,audio:n}),this.tracer.log("updateManifestEnd",Sn(o)),o}.bind(this));this.initRepresentations=Lp(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",Sn({initialVideo:e,initialAudio:t,sourceHls:i})),ms(this.manifest),ms(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new Cp,this.state$.startTransitionTo("representations_ready");let r=d=>{this.representationSubscription.add(Dt(d,"error").pipe(Du(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:Et.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=Ir();let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),ai())if(i){let d=document.createElement("source");r(d),d.type="application/x-mpegurl",d.src=i.url,this.element.appendChild(d)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((d,h)=>[...d,...h.representations],[]);if(this.videoBufferManager=new pn("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],vn(t)){let d=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new pn("audio",this.source,d,n),this.bufferManagers.push(this.audioBufferManager)}bn.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new bn(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(or(...$_.map(d=>Dt(this.element,d))).pipe(gs(d=>this.element?de(this.element.buffered,this.element.currentTime*1e3):0),gn(),A_(d=>{d>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(or(Dt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(gn()).subscribe(h=>this.liveStreamEndTimestamp=Bp())),this.subscription.add(Dt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Dp(1e3).subscribe(h=>{let f=si(this.manifestUrlString,2);this.manifestUrlString=ne(this.manifestUrlString,f+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Dt(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(bs({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(gs(({isActiveLive:h,isLowLatency:f})=>h&&f),gn()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||ls(this.element,1)})),this.representationSubscription.add(bs({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Du(({bufferLength:h,isActiveLive:f,isLowLatency:m})=>f&&m&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let f=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(f,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(bs({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Du(({isLive:h})=>h),gn((h,f)=>f.bufferLength<h.bufferLength),gs(({rtt:h,bufferLength:f,segmentServerLatency:m})=>{let S=si(this.manifestUrlString,2);return(h/2+f+m+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(bs({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:f,isLowLatency:m})=>{if(!m||!f)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=h-S;if(this.isManualDecreasePlaybackInLive())return;let y=1;Math.abs(T)>g&&(y=1+Math.sign(T)*v),ls(this.element,y)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let f=0;if(h){let m=(this.element?.currentTime??0)*1e3;f=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??m))-m}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let d=0;this.representationSubscription.add(bs({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(CE(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(!this.element||this.isUpdatingLive)return;let m=this.element.playbackRate,S=si(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*m),T=this.tuning.dashCmafLive.normalizedActualBufferOffset*m,y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*m,x=isFinite(h)?h:f,A=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),R=g<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(R);let w="none";if(A?w="active_low_latency":this.isLowLatency$.getValue()&&R?(this.bufferManagers.forEach(B=>B.proceedLowLatencyLive()),w="active_low_latency"):S!==0&&x<v?w="live_forward_buffering":x<v+y&&(w="live_with_target_offset"),isFinite(h)&&(d=h>d?h:d),w==="live_forward_buffering"||w==="live_with_target_offset"){let B=d-(v+T),k=this.normolizeLiveOffset(Math.trunc(S+B/m)),F=Math.abs(k-S),C=0;!h||F<=this.tuning.dashCmafLive.offsetCalculationError?C=S:k>0&&F>this.tuning.dashCmafLive.offsetCalculationError&&(C=k),this.manifestUrlString=ne(this.manifestUrlString,C,2)}(w==="live_with_target_offset"||w==="live_forward_buffering")&&(d=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:Et.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=or(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe(gs(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),p=or(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe(gs(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue()))),c=bs({allBuffersFull:l,someBufferEnded:p}).pipe(gn(),gs(({allBuffersFull:d,someBufferEnded:h})=>d&&h),Du(d=>d));if(this.representationSubscription.add(or(this.forceEnded$,c).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{this.source?.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:Et.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add(or(...this.bufferManagers.map(d=>d.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"){let d=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{d&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.error$.next({id:"OpenOfStream",category:Et.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let d=[this.manifest.duration??0,...(0,Vp.default)((0,Vp.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),rt(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...d)/1e3}this.audioBufferManager&&vn(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||this.source?.readyState!=="open")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=Dp(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Et.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.forceVideoCodec=e.forceVideoCodec,this.fetcher=new Lu({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.firstBytesRequested$.subscribe(this.firstBytesRequested$)),this.subscription.add(this.fetcher.firstBytesReceived$.subscribe(this.firstBytesReceived$)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.liveBuffer=Qt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){ms(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Bp()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ne(this.manifestUrlString,i,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(){ms(this.element),this.state$.setState("running");let e=Dt(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(CE(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(or(...R_.map(t=>Dt(this.element,t)),Dt(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:Et.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(Dt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Dt(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&De(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{if(!this.element||this.source?.readyState!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},a=Bp(),n=100,o=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(o);let u=this.audioBufferManager?.lastDataObtainedTimestamp??0,l=this.videoBufferManager?.getForwardBufferDuration()??0,p=this.audioBufferManager?.getForwardBufferDuration()??0,c=l<n&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&p<n&&a-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||d)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let h=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(h).catch(f=>{this.error$.next({id:"stallIntervalCallback",category:Et.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:f})}),r.liveLastOffset=h}else{let h=this.element.currentTime*1e3;this.videoBufferManager?.maintain(h),this.audioBufferManager?.maintain(h),r.position=h}this.tracer.log("stallIntervalCallback",Sn(r))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=Dp(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:Et.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){ms(this.element),ms(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),this.warmUpMediaSourceIfNeeded(i),De(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(BE(this.element)||BE(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Sn({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){vn(this.element)&&vn(this.source)&&vn(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),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}getCodecs(){return this.manifest?.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),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=k_(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}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.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let a=this.element.currentTime*1e3,n=null,o=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=a&&l.to+o>a&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n=1/0:(n===null||l.to>n)&&(n=l.to));if(n!==null){let u=n+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,this.tracer.log("jumpGap",Sn({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};import{combine as M_,map as L_,observeElementSize as D_,Subscription as B_,ValueSubject as _p,noop as C_}from"@vkontakte/videoplayer-shared/es2024";var Cu=class{constructor(){this.subscription=new B_;this.pipSize$=new _p(void 0);this.videoSize$=new _p(void 0);this.elementSize$=new _p(void 0);this.pictureInPictureWindowRemoveEventListener=C_}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(D_(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(M_({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(L_(({videoSize:r,inPip:a,pipSize:n})=>a?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var ur=class{constructor(e){this.subscription=new j_;this.videoState=new O("stopped");this.observableVideo=null;this.droppedFramesManager=new li;this.stallsManager=new qr;this.elementSizeManager=new Cu;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new yt;this.audioTrackSwitchHistory=new yt;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),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.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&P(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return __(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new di(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.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new We(e.source.url),this.params=e,this.video=Pe(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(ce(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 Bu({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;q_(this.observableVideo)&&(this.observableVideo=$e(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:_E.WTF,message:`${i} internal logic error`,thrown:n})},a=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:a}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Op(c=>!!c.length),NE()).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(Tn(c=>c.to.state!=="none"),yn());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.currentBuffer$,e.currentNativeBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.manifestRequested$,e.manifestRequested$),a(this.player.firstBytesManifest$,e.firstBytesManifest$),a(this.player.manifestReceived$,e.manifestReceived$),a(this.player.firstBytesRequested$,e.firstBytesRequested$),a(this.player.firstBytesReceived$,e.firstBytesReceived$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(Op(OE),NE()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(Tn(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(Re(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Qe(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Ye(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")})),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(),h=this.player.getCodecs();if(O_(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let S of d.audio){m.push(xp(S));let g=[];for(let v of S.representations){let T=xE(v);g.push(T),this.audioTracksMap.set(T,{stream:S,representation:v})}this.audioStreamsMap.set(S,g)}this.params.output.availableAudioStreams$.next(m)}let f=[];for(let m of d.video){f.push(kp(m));let S=[];for(let g of m.representations){let v=dn({...g,streamId:m.id});v&&(S.push(v),this.videoTracksMap.set(v,{stream:m,representation:g}))}this.videoStreamsMap.set(m,S)}this.params.output.availableVideoStreams$.next(f);for(let m of d.text)for(let S of m.representations){let g=kE(m,S);this.textTracksMap.set(g,{stream:m,representation:S})}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),h?.video&&this.params.output.availableVideoCodecs$.next(h.video),h?.audio&&this.params.output.availableAudioCodecs$.next(h.audio),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())},r));let{vktvAbrThrottle:o}=this.params.tuning.dash,u=o&&RE(o)||null;this.subscription.add(In(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,U_(this.video,"progress")).pipe(Op(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||d||c==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:h,audio:f}=this.selectedRepresentations;if(!h)return;let m=rr(this.videoTracksMap.keys(),g=>this.videoTracksMap.get(g)?.representation.id===h.id);OE(m)&&(this.stallsManager.lastVideoTrackSelected=m);let S=this.params.desiredState.autoVideoTrackLimits.getTransition();if(S&&this.params.output.autoVideoTrackLimits$.next(S.to),c==="manifest_ready")await this.player.initRepresentations(h.id,f?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",h.id),f){let g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",f.id,g)}},r)),this.subscription.add(N_({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:In(Vu([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(Tn(c=>c.to)))}).pipe(Tn(({videoState:c,autoVideoTrackState:d})=>c.to!=="stopped"&&d),yn()).subscribe(c=>this.player.setSmartRepresentationSwitch(c))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(yn()).subscribe(c=>{let d=rr(this.videoTracksMap.entries(),([,{representation:g}])=>g.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:f}]=d,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(kp(f));let S=this.player.calculateDurationFromSegments();S&&this.params.output.duration$.next(S/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(yn()).subscribe(c=>{let d=rr(this.audioTracksMap.entries(),([,{representation:S}])=>S.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:f}]=d,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(xp(f))},r)),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)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(Tn(({to:c})=>c==="ready"),yn());this.subscription.add(In(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Vu(["init"])).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(In(l,this.player.state$.stateChangeEnded$,Vu(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let p=In(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Vu(["init"])).pipe(F_(0));this.subscription.add(p.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Qi:zi,t=this.params.tuning.useNewAutoSelectVideoTrack?Fr:Nr,i=this.params.tuning.useNewAutoSelectVideoTrack?ut:Or,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,u=rr(this.videoTracksMap.keys(),w=>w.id===o),l=a.currentVideoTrack$.getValue(),p=r.videoStream.getState()??(u&&this.videoTracksMap.get(u)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!p)return;let c=rr(this.videoStreamsMap.keys(),w=>w.id===p.id),d=c&&this.videoStreamsMap.get(c);if(!d)return;let h=de(this.video.buffered,this.video.currentTime*1e3),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(f,m||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),v=g?.id&&rr(this.audioStreamsMap.keys(),w=>w.id===g.id)||this.audioStreamsMap.keys().next().value,T=0;if(v){if(u&&!n){let w=e(u,d,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}if(l){let w=e(l,d,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}}let y=u;(n||!y)&&(y=i(d,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:T,forwardBufferHealth:S,current:l,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}));let x=v&&t(y,d,this.audioStreamsMap.get(v)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),A=this.videoTracksMap.get(y)?.representation,R=x&&this.audioTracksMap.get(x)?.representation;A&&R?(this.selectedRepresentations.video=A,this.selectedRepresentations.audio=R):A&&!R&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=A,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_E.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Ae(this.video),this.tracer.end()}};var En=class extends ur{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)}};import{combine as Np,merge as FE,filter as UE,filterChanged as qE,isNullable as Fp,map as jE,ValueSubject as Up,isNonNullable as H_}from"@vkontakte/videoplayer-shared/es2024";var wn=class extends ur{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:a,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let o=new Up(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(qE()).subscribe(u=>{let l=i.position$.getValue(),p=i.volume$.getValue(),c=!p.volume||p.muted;!u&&!l&&c?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(a.isLowLatency.stateChangeEnded$.pipe(jE(u=>u.to)).subscribe(this.player.isLowLatency$)).add(Np({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(jE(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(UE(u=>H_(u))).subscribe(u=>i.isLiveEnded$.next(u!=="active"&&i.position$.getValue()===0))).add(Np({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:FE(r.playbackRateState$,new Up(1))}).pipe(UE(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let p=i.liveBufferTime$.getValue(),c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||l<1-d||this.video.paused||Fp(p)||(t=u-p)})).add(Np({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:FE(r.playbackRateState$,new Up(1))}).pipe(qE((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:p})=>{let c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&p>=1-d||Fp(u)||Fp(l))return;let h=-1*(l-u-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let l=PE(u);this.params.output.availableTextTracks$.next([l])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var HE="X-Playback-Duration",qp=async s=>{let e=await Ke(s),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(HE)?parseInt(e.headers.get(HE),10):void 0};import{assertNever as tO,combine as iO,debounce as rO,ErrorCategory as Nu,filter as sO,filterChanged as aO,isNonNullable as WE,isNullable as Fu,map as GE,merge as nO,observableFrom as oO,Subscription as uO,ValueSubject as zp,VideoQuality as lO}from"@vkontakte/videoplayer-shared/es2024";var Hp=D(fc(),1);import{videoSizeToQuality as z_,getExponentialDelay as Q_}from"@vkontakte/videoplayer-shared/es2024";var W_=s=>{let e=null;if(s.QUALITY&&(e=$t(s.QUALITY)),!e&&s.RESOLUTION){let[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=z_({width:t,height:i})}return e??null},G_=(s,e)=>{let t=s.split(`
178
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(p,"i")}var wI=s=>{if(!s?.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(s),r=i?.[1]==="-"?-1:1,a={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},tt=(s,e)=>{let t=s;t=(0,Qd.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,xI.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Qd.default)(t,n,(o,u)=>EI(a)?o:EI(u)?a:(0,kI.default)(a,parseInt(u,10),"0"))}return t},Xr=(s,e)=>{let i=new DOMParser().parseFromString(s,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],n=Array.from(a.querySelectorAll("MPD > BaseURL").values()).map(B=>B.textContent?.trim()??""),o=(0,PI.default)(n,0)??"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),p=a.getAttribute("publishTime"),c=a.getElementsByTagName("vk:Attrs")[0],d=c?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=c?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=c?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=c?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,S;u&&(S={availabilityStartTime:l?new Date(l).getTime():0,publishTime:p?new Date(p).getTime():0,latestSegmentPublishTime:d?new Date(d).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:f==="yes"});let g,v=a.getAttribute("mediaPresentationDuration"),T=[...a.getElementsByTagName("Period")],y=T.reduce((B,k)=>({...B,[k.id]:k.children}),{}),x=T.reduce((B,k)=>({...B,[k.id]:k.getAttribute("duration")}),{});v?g=wI(v):(0,Wd.default)(x).filter(B=>B).length&&!u?g=(0,Wd.default)(x).reduce((B,k)=>B+(wI(k)??0),0):m&&(g=parseInt(m,10));let A=0,R=a.getAttribute("profiles")?.split(",")??[];for(let B of T.map(k=>k.id))for(let k of y[B]){let F=k.getAttribute("id")??"id"+(A++).toString(10),C=k.getAttribute("mimeType")??"",E=k.getAttribute("codecs")??"",I=k.getAttribute("contentType")??C?.split("/")[0],N=k.getAttribute("profiles")?.split(",")??[],L=II(k.getAttribute("lang")??"")??{},H=k.querySelector("Label")?.textContent?.trim()??void 0,X=k.querySelectorAll("Representation"),re=k.querySelector("SegmentTemplate"),le=k.querySelector("Role")?.getAttribute("value")??void 0,Te=I,Ie={id:F,language:L.language,isDefault:le==="main",label:H,codecs:E,hdr:Te==="video"&&zd(E),mime:C,representations:[]};for(let z of X){let q=z.getAttribute("lang")??void 0,Ee=H??k.getAttribute("label")??z.getAttribute("label")??void 0,Be=z.querySelector("BaseURL")?.textContent?.trim()??"",me=new URL(Be||o,e).toString(),at=z.getAttribute("mimeType")??C,Jt=z.getAttribute("codecs")??E??"",dt;if(I==="text"){let Xe=z.getAttribute("id")||"",Zt=L.privateuse?.includes("x-auto")||Xe.includes("_auto"),pt=z.querySelector("SegmentTemplate");if(pt){let ys={representationId:z.getAttribute("id")??void 0,bandwidth:z.getAttribute("bandwidth")??void 0},Ln=parseInt(z.getAttribute("bandwidth")??"",10)/1e3,Dn=parseInt(pt.getAttribute("startNumber")??"",10)??1,lr=parseInt(pt.getAttribute("timescale")??"",10),Ku=pt.querySelectorAll("SegmentTimeline S")??[],cr=pt.getAttribute("media");if(!cr)continue;let Bn=[],Cn=0,Vn="",dr=0,Ts=Dn,Ce=0;for(let ht of Ku){let xi=parseInt(ht.getAttribute("d")??"",10),nt=parseInt(ht.getAttribute("r")??"",10)||0,ei=parseInt(ht.getAttribute("t")??"",10);Ce=Number.isFinite(ei)?ei:Ce;let ki=xi/lr*1e3,pr=Ce/lr*1e3;for(let wt=0;wt<nt+1;wt++){let ti=tt(cr,{...ys,segmentNumber:Ts.toString(10),segmentTime:(Ce+wt*xi).toString(10)}),hr=(pr??0)+wt*ki,Es=hr+ki;Ts++,Bn.push({time:{from:hr,to:Es},url:ti})}Ce+=(nt+1)*xi,Cn+=(nt+1)*ki}dr=Ce/lr*1e3,Vn=tt(cr,{...ys,segmentNumber:Ts.toString(10),segmentTime:Ce.toString(10)});let Is={time:{from:dr,to:1/0},url:Vn},Bt={type:"template",baseUrl:me,segmentTemplateUrl:cr,initUrl:"",totalSegmentsDurationMs:Cn,segments:Bn,nextSegmentBeyondManifest:Is,timescale:lr};dt={id:Xe,kind:"text",segmentReference:Bt,profiles:[],duration:g,bitrate:Ln,mime:"",codecs:"",width:0,height:0,isAuto:Zt}}else dt={id:Xe,isAuto:Zt,kind:"text",url:me}}else{let Xe=z.getAttribute("contentType")??at?.split("/")[0]??I,Zt=k.getAttribute("profiles")?.split(",")??[],pt=parseInt(z.getAttribute("width")??"",10),ys=parseInt(z.getAttribute("height")??"",10),Ln=parseInt(z.getAttribute("bandwidth")??"",10)/1e3,Dn=z.getAttribute("frameRate")??"",lr=z.getAttribute("quality")??void 0,Ku=Dn?TI(Dn):void 0,cr=z.getAttribute("id")??"id"+(A++).toString(10),Bn=Xe==="video"?`${ys}p`:Xe==="audio"?`${Ln}Kbps`:Jt,Cn=`${cr}@${Bn}`,Vn=[...R,...N,...Zt],dr,Ts=z.querySelector("SegmentBase"),Ce=z.querySelector("SegmentTemplate")??re;if(Ts){let Bt=z.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[ht,xi]=Bt.split("-").map(ti=>parseInt(ti,10)),nt={from:ht,to:xi},ei=z.querySelector("SegmentBase")?.getAttribute("indexRange"),[ki,pr]=ei?ei.split("-").map(ti=>parseInt(ti,10)):[],wt=ei?{from:ki,to:pr}:void 0;dr={type:"byteRange",url:me,initRange:nt,indexRange:wt}}else if(Ce){let Bt={representationId:z.getAttribute("id")??void 0,bandwidth:z.getAttribute("bandwidth")??void 0},ht=parseInt(Ce.getAttribute("timescale")??"",10),xi=Ce.getAttribute("initialization")??"",nt=Ce.getAttribute("media"),ei=parseInt(Ce.getAttribute("startNumber")??"",10)??1,ki=tt(xi,Bt);if(!nt)throw new ReferenceError("No media attribute in SegmentTemplate");let pr=Ce.querySelectorAll("SegmentTimeline S")??[],wt=[],ti=0,hr="",Es=0;if(pr.length){let _n=ei,ft=0;for(let fr of pr){let xt=parseInt(fr.getAttribute("d")??"",10),Pi=parseInt(fr.getAttribute("r")??"",10)||0,On=parseInt(fr.getAttribute("t")??"",10);ft=Number.isFinite(On)?On:ft;let Xu=xt/ht*1e3,Ow=ft/ht*1e3;for(let Nn=0;Nn<Pi+1;Nn++){let Nw=tt(nt,{...Bt,segmentNumber:_n.toString(10),segmentTime:(ft+Nn*xt).toString(10)}),lh=(Ow??0)+Nn*Xu,Fw=lh+Xu;_n++,wt.push({time:{from:lh,to:Fw},url:Nw})}ft+=(Pi+1)*xt,ti+=(Pi+1)*Xu}Es=ft/ht*1e3,hr=tt(nt,{...Bt,segmentNumber:_n.toString(10),segmentTime:ft.toString(10)})}else if(PV(g)){let ft=parseInt(Ce.getAttribute("duration")??"",10)/ht*1e3,fr=Math.ceil(g/ft),xt=0;for(let Pi=1;Pi<fr;Pi++){let On=tt(nt,{...Bt,segmentNumber:Pi.toString(10),segmentTime:xt.toString(10)});wt.push({time:{from:xt,to:xt+ft},url:On}),xt+=ft}Es=xt,hr=tt(nt,{...Bt,segmentNumber:fr.toString(10),segmentTime:xt.toString(10)})}let _w={time:{from:Es,to:1/0},url:hr};dr={type:"template",baseUrl:me,segmentTemplateUrl:nt,initUrl:ki,totalSegmentsDurationMs:ti,segments:wt,nextSegmentBeyondManifest:_w,timescale:ht}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Xe||!at)continue;let Is={video:"video",audio:"audio",text:"text"}[Xe];if(!Is)continue;Te||=Is,dt={id:Cn,kind:Is,segmentReference:dr,profiles:Vn,duration:g,bitrate:Ln,mime:at,codecs:Jt,width:pt,height:ys,fps:Ku,quality:lr}}Ie.language||=q,Ie.label||=Ee,Ie.mime||=at,Ie.codecs||=Jt,Ie.hdr||=Te==="video"&&zd(Jt),Ie.representations.push(dt)}if(Te){let z=r[Te].find(q=>q.id===Ie.id);if(z&&Ie.representations.every(q=>q.segmentReference.type==="template"))for(let q of z.representations){let Ee=Ie.representations.find(at=>at.id===q.id);if(!Ee)continue;let Be=Ee.segmentReference,me=q.segmentReference;me.segments.push(...Be.segments),me.nextSegmentBeyondManifest=Be.nextSegmentBeyondManifest}else r[Te].push(Ie)}}return{duration:g,streams:r,baseUrls:n,live:S}};var au=D(Ge(),1),Gd=D(ke(),1);import{assertNever as nu}from"@vkontakte/videoplayer-shared/es2024";var su=s=>{let{webmDecodingInfo:e}=$.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(s){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:nu(s)}},AI=({webmCodec:s,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...su(s),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],a=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if($.device.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...a,"MPEG",...su(s),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...su(s),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...su(s),...a,"HLS","HLS_ONDEMAND"];default:nu(e)}if($.video.nativeHlsSupported)switch(t){case"hls":return[...r,"HLS","HLS_FMP4","HLS_ONDEMAND","MPEG"];case"hls_fmp4":return[...r,"HLS_FMP4","HLS","HLS_ONDEMAND","MPEG"];default:nu(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},RI=({androidPreferredFormat:s,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],a=[...i,...r],n=[...r,...i],o,u=$.device.isMac&&$.browser.isSafari;if($.device.isAndroid)switch(s){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=a;break}case"hls":case"mpeg":{o=n;break}default:nu(s)}else $.video.nativeHlsSupported&&!u&&!$.browser.isChromiumBased?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=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Yd=s=>s?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Jr=s=>{if(s.size===0)return;if(s.size===1){let t=s.values().next();return(0,au.default)(t.value.split("."),0)}for(let t of s){let i=(0,au.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=s.values().next();return(0,au.default)(e.value.split("."),0)},Zr=s=>{let e=s.map(i=>hi(i)),{codecs:t}=$.video;return MV().filter(i=>{if((0,Gd.default)(e,i))switch(i){case"av1":return t.av1;case"vp9":return t.vp9;case"avc1":return t.h264;case"hev1":return t.h265;default:return!1}else return!1})},es=s=>{let e=s.map(i=>hi(i)),{codecs:t}=$.video;return LV().filter(i=>{if((0,Gd.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},hi=s=>s.split(".")[0].replace("0",""),MV=()=>["av1","vp9","hev1","avc1"],LV=()=>["opus","mp4a"];var qI=D(Ge(),1);var DV=(s,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},BV=s=>window.clearTimeout(s),$I=s=>typeof s=="function"&&s?.toString().endsWith("{ [native code] }"),MI=!$I(window.requestIdleCallback)||!$I(window.cancelIdleCallback),Mt=MI?DV:window.requestIdleCallback,qe=MI?BV:window.cancelIdleCallback;import{abortable as tp,assertNonNullable as Lt,ErrorCategory as t0,fromEvent as i0,getExponentialDelay as r0,isHigher as s0,isNonNullable as oe,isNullable as ve,once as a0,Subject as n0,Subscription as o0,ValueSubject as za}from"@vkontakte/videoplayer-shared/es2024";var LI=D(Ge(),1);var ou=s=>s.valid,W=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,a;i===0?(this.size=void 0,this.valid=!1,a=void 0):i===1?(this.size=void 0,this.valid=!1,a=void 0):i>e.byteLength?(this.size=i,this.valid=!1,a=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,a=i-this.cursor),this.content=new DataView(e.buffer,r,a)}get id(){return this.type}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}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 ts=class extends W{};import{assertNever as CV}from"@vkontakte/videoplayer-shared/es2024";var va=class extends W{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readString(16),r=new DataView(this.content.buffer,this.content.byteOffset+16,this.content.byteLength-16);this.userData=this.parseData(i,r)}parseData(e,t){switch(e){case"ondemandlivejson":{let i=new TextDecoder("ascii").decode(t),r=JSON.parse(i);return{received:r["t-in"],prepared:r["t-out"]}}default:CV(e)}}};var ya=class extends W{constructor(e,t){if(super(e,t),!this.valid)return;this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8);for(let r=0;r<i.byteLength;r+=4){let a=this.readString(4);this.compatibleBrands.push(a)}}};var Ta=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var J=class extends W{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215,this.content=new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)}};var Ia=class extends J{constructor(e,t){super(e,t),this.valid&&(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 Ea=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var wa=class extends W{constructor(e,t){super(e,t),this.data=this.content}};var Yi=class extends J{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){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 r=this.readUint32(),a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}}};var xa=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ka=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Pa=class extends J{constructor(e,t){if(super(e,t),!this.valid)return;switch(this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Aa=class extends J{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var Ra=class extends J{constructor(e,t){super(e,t),this.valid&&(this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32())}};var $a=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ma=class extends J{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var La=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Da=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ba=class extends J{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var Ca=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Va=class extends J{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var _a=class extends J{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 Oa=class extends J{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 r=0;r<this.sampleCount;r++)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 Na=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Fa=class extends J{constructor(e,t){super(e,t),this.valid&&(this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)))}};var Ua=class extends W{constructor(e,t){super(e,t),this.valid&&(this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78)))}};var _V={ftyp:ya,moov:Ta,mvhd:Ia,moof:Ea,mdat:wa,sidx:Yi,trak:xa,mdia:$a,mfhd:Ba,tkhd:Ma,traf:Ca,tfhd:Va,tfdt:_a,trun:Oa,minf:La,sv3d:ka,st3d:Pa,prhd:Aa,proj:Da,equi:Ra,uuid:va,stbl:Na,stsd:Fa,avc1:Ua,unknown:ts},qt=class s{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n;try{n=this.createBox(a,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(o){if(!(o instanceof RangeError))throw o}if(!n||!ou(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=_V[e];return i?new i(t,new s):new ts(t,new s)}};var fi=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{ou(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 NV=new TextDecoder("ascii"),FV=s=>NV.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",UV=s=>{let e=new Yi(s,new qt),t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},qV=(s,e)=>{let i=new qt().parse(s),r=new fi(i),a=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&a.length))return null;let o=a[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(s.buffer,l,c)},jV=s=>{let t=new qt().parse(s),i=new fi(t),r={},a=i.findAll("uuid"),n=(0,LI.default)(a,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},HV=s=>{let t=new qt().parse(s);return new fi(t).find("sidx")?.timescale},zV=(s,e)=>{let i=new qt().parse(s),a=new fi(i).findAll("traf"),n=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,d)=>c+d,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},QV=s=>{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 qt().parse(s),r=new fi(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.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},DI={validateData:FV,parseInit:QV,getIndexRange:()=>{},parseSegments:UV,parseFeedableSegmentChunk:qV,getChunkEndTime:zV,getServerLatencyTimestamps:jV,getTimescaleFromIndex:HV};var ja=D(ke(),1);import{assertNonNullable as Kd,isNonNullable as _I,isNullable as GV}from"@vkontakte/videoplayer-shared/es2024";import{assertNever as WV}from"@vkontakte/videoplayer-shared/es2024";var BI={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"}},CI=s=>{let e=s.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=qa(s,t),r=i in BI,a=r?BI[i].type:"binary",n=s.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(s.buffer,s.byteOffset+t+1,o-1),l=n&255>>o,p=qa(u),c=l*2**((o-1)*8)+p,d=t+o,h;return d+c>s.byteLength?h=new DataView(s.buffer,s.byteOffset+d):h=new DataView(s.buffer,s.byteOffset+d,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:d,tagSize:d+c,value:h,valueSize:c}},qa=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{let t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},It=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return qa(s);case"float":return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case"string":return new TextDecoder("ascii").decode(s);case"utf8":return new TextDecoder("utf-8").decode(s);case"date":return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case"master":return s;case"binary":return s;default:WV(e)}},Ki=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=CI(i);if(!e(r))return;r.type==="master"&&Ki(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},VI=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=CI(s);return Ki(r.value,({tag:a,type:n,value:o})=>(a===17143?e=It(o,n):a===17026?t=It(o,n):a===17029&&(i=It(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var OI=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],YV=[231,22612,22743,167,171,163,160,175],KV=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,p=!1,c=0;return Ki(s,({tag:d,type:h,value:f,valueSize:m})=>{if(d===21419){let S=It(f,h);l=qa(S)}else d!==21420&&(l=void 0);return d===408125543?(e=f.byteOffset,t=f.byteOffset+m):d===357149030?a=!0:d===290298740?n=!0:d===2807729?i=It(f,h):d===17545?r=It(f,h):d===21420&&l===475249515?u=It(f,h):d===374648427?Ki(f,({tag:S,type:g,value:v})=>S===30321?(p=It(v,g)===1,!1):!0):a&&n&&(0,ja.default)(OI,d)&&(o=!0),!o}),Kd(e,"Failed to parse webm Segment start"),Kd(t,"Failed to parse webm Segment end"),Kd(r,"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(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:p,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},XV=s=>{if(GV(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},JV=(s,e)=>{let t=!1,i=!1,r=o=>_I(o.time)&&_I(o.position),a=[],n;return Ki(s,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=It(l,u));break;case 183:break;case 241:n&&(n.position=It(l,u));break;default:t&&(0,ja.default)(OI,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:l,position:p}=o,c=a[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+p,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},ZV=s=>{let e=0,t=!1;try{Ki(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,ja.default)(YV,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||=(0,ja.default)([163,160,175],i.tag)),!0):!1)}catch{}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},NI={validateData:VI,parseInit:KV,getIndexRange:XV,parseSegments:JV,parseFeedableSegmentChunk:ZV};var lt=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return NI;case"mp4":return DI}}throw new ReferenceError(`Unsupported mime type ${s}`)};var Xd=D(Ge(),1);import{videoSizeToQuality as e0}from"@vkontakte/videoplayer-shared/es2024";var mi=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{let o=(a?$t(a):void 0)??e0({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},Ha=({id:s,bitrate:e})=>({id:s,bitrate:e}),FI=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),UI=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Jd=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,Xd.default)(i.split("."),0),isDefault:r}),Zd=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,Xd.default)(r.split("."),0)}),ep=s=>"url"in s,it=s=>s.type==="template";var is=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,manifest:o}){this.error$=new n0;this.playingRepresentation$=new za(void 0);this.playingRepresentationInit$=new za(void 0);this.currentSegmentLength$=new za(0);this.onLastSegment$=new za(!1);this.fullyBuffered$=new za(!1);this.initData=new Map;this.initDataPromises=new Map;this.idleCallbacks=new Map;this.parsedInitData=new Map;this.segments=new Map;this.bufferPlaybackQueue=[];this.downloadingBufferItems=[];this.preloadOnly=!1;this.failedDownloads=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.currentVirtualBufferSize=0;this.baseUrls=[];this.baseUrlsIndex=0;this.maintainPlaybackBufferMutex=!1;this.maintainNativeBufferMutex=!1;this.bufferClearingMutex=!1;this.abortNativeBufferMutex=!1;this.switchMutex=!1;this.destroyAbortController=new j;this.downloadAbortController=new j;this.subscription=new o0;this.startWith=tp(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Lt(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.containerParser=lt(t.mime),this.nativeBufferManager.init(t.mime,t.codecs,this.tuning.dash.useAbortMSEFix),yield this.loadInits(t);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);Lt(i,"No init buffer for starting representation"),Lt(r,"No segments for starting representation"),await this.nativeBufferManager.addInitSegment(i),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a)}.bind(this));this.switchTo=tp(this.destroyAbortController.signal,async function*(e,t=!0){if(ve(this.downloadingRepresentationId)||e===this.downloadingRepresentationId||e===this.switchingRepresentationId)return;this.switchMutex=!0,this.switchingRepresentationId=e;let i=this.representations.get(this.downloadingRepresentationId),r=this.representations.get(e);Lt(r,`No such representation ${e}`),Lt(i,`No such representation ${this.downloadingRepresentationId}`),yield this.loadInitIfNeeded(r,"high");let a=this.initData.get(r.id),n=this.segments.get(r.id);Lt(a,"No init buffer for switching representation"),Lt(n,"No segments for switching representation");let o=this.getCurrentPosition()??0,u=c=>c.segment.networkStatus!=="downloaded"||c.segment.time.to-o>this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment,l=c=>{let d=this.representations.get(c.representationId);return Lt(d,"No itemRepresentation for previous track before switch"),c.segment.networkStatus!=="downloaded"||this.forceSwitchCondition(d,r)},p=c=>t?u(c)&&l(c):u(c);this.bufferPlaybackQueue.filter(p).forEach(c=>c.segment.bufferStatus="none"),this.bufferPlaybackQueue=this.bufferPlaybackQueue.filter(c=>!p(c)),this.downloadingRepresentationId=e,this.switchingRepresentationId=null,this.bufferPlaybackQueue.length?(this.abortDownload(),yield this.maintain()):yield this.seek(o),this.switchMutex=!1}.bind(this));this.waitExponentialDownloadDelay=tp(this.downloadAbortController.signal,async function*(){let e=r0(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(t=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(t,e),this.subscription.add(i0(window,"online").pipe(a0()).subscribe(()=>{t(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}))})}.bind(this));this.kind=e,this.nativeBufferManager=t,this.fetcher=r,this.tuning=a,this.getCurrentPosition=n,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.baseUrls=o?.baseUrls??[],this.representations=new Map(i.map(u=>[u.id,u]))}async seek(e){await this.abort(),await this.clearBuffer(),await this.maintain(e)}async maintain(e=this.getCurrentPosition()){ve(e)||(await this.maintainPlaybackBuffer(e),await this.maintainNativeBuffer(),this.actualizeLastSegmentInfo(e))}getForwardPlaybackBufferDuration(e=this.getCurrentPosition()){let t=this.getPlaybackBufferState();return oe(t)&&oe(e)?t.to-e:0}getPlaybackBufferState(){if(!this.bufferPlaybackQueue.length)return null;let t=this.bufferPlaybackQueue[0].segment.time.from,i=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segment.time.to;return{from:t,to:i}}async abort(){this.abortDownload(),await this.abortNativeBuffer()}findSegmentStartTime(e){let t=this.downloadingRepresentationId??this.playingRepresentationId??"";return this.segments.get(t)?.find(a=>a.time.from<=e&&a.time.to>=e)?.time.from}getRepresentationInitialTime(){return ve(this.playingRepresentationId)?0:(this.segments.get(this.playingRepresentationId)?.[0].time.from??0)/1e3}calculateDurationFromSegments(){if(ve(this.playingRepresentationId))return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,qI.default)(e,-1)?.time.to:0)||0}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.initDataPromises.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.downloadAbortController.abort(),this.destroyAbortController.abort(),this.subscription.unsubscribe(),qe)for(let e of this.idleCallbacks.values())qe(e);this.idleCallbacks.clear(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}forceSwitchCondition(e,t){let i=!0;if(this.kind==="video"){let r=mi(e),a=mi(t);i=oe(r)&&oe(a)&&s0(a.quality,r.quality)}else if(this.kind==="audio"){let r=Ha(e),a=Ha(t);i=oe(r?.bitrate)&&oe(a?.bitrate)&&a.bitrate>r.bitrate}return i}async clearBuffer(){this.bufferClearingMutex=!0,await this.nativeBufferManager.clear(this.destroyAbortController.signal),this.bufferPlaybackQueue.forEach(e=>e.segment.bufferStatus="none"),this.bufferPlaybackQueue=[],this.bufferClearingMutex=!1}abortDownload(){this.downloadAbortController.abort(),this.downloadAbortController=new j,this.abortDownloadingItems(),this.maintainPlaybackBufferMutex=!1}abortDownloadingItems(){for(let e of this.downloadingBufferItems)e.segment.networkStatus==="downloading"&&(e.segment.networkStatus="none",e.segment.size=0,e.segment.loadedBytes=0,e.segment.feedingBytes=0,e.segment.fedBytes=0,e.segment.data=null);this.downloadingBufferItems=[]}async abortNativeBuffer(){this.abortNativeBufferMutex=!0;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0,i=await this.nativeBufferManager.abortBuffer(t);return this.abortNativeBufferMutex=!1,this.maintainNativeBufferMutex=!1,i}async loadInits(e){await this.loadInit(e,"high",!0);for(let[t,i]of this.representations)this.idleCallbacks.set(i.id,Mt(async r=>await this.loadInitIfNeeded(i,"low",!1)))}async loadInitIfNeeded(e,t="auto",i=!1){let r=this.initDataPromises.get(e.id),a;this.initData.has(e.id)&&this.segments.has(e.id)?a=Promise.resolve():oe(r)?a=r:a=this.loadInit(e,t,i),await a}async loadInit(e,t="auto",i=!1){try{let r=this.tuning.dash.useFetchPriorityHints?t:"auto",a=this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r);this.initDataPromises.set(e.id,a);let{initMetadata:n,initDataView:o,segments:u}=await a??{};if(this.initDataPromises.delete(e.id),ve(o)||ve(u))return;n&&this.parsedInitData.set(e.id,n);let l=o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength);this.initData.set(e.id,l),this.segments.set(e.id,u),this.failedDownloads=0}catch(r){i&&this.error$.next({id:"LoadInits",category:t0.WTF,message:"loadInit threw",thrown:r})}}async maintainNativeBuffer(){let e=this.getCurrentPosition();if(ve(e)||this.maintainNativeBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex||this.preloadOnly)return;this.maintainNativeBufferMutex=!0;let t=this.bufferPlaybackQueue.find(o=>this.withinInterval(e,o.segment.time)),i=this.bufferPlaybackQueue.find(o=>o.segment.bufferStatus!=="fed"),r=this.initData.get(i?.representationId??""),a=this.bufferPlaybackQueue[0],n=this.downloadAbortController.signal;oe(r)&&oe(i)&&oe(t)&&this.playingRepresentationId!==i.representationId&&this.withinAppendInterval(e,i.segment.time)&&(i===t||t.segment.bufferStatus==="fed")&&(await this.abortNativeBuffer(),await this.nativeBufferManager.addInitSegment(r,this.downloadAbortController.signal),this.playingRepresentationId=i.representationId,this.playingRepresentation$.next(this.playingRepresentationId)),oe(i)&&this.withinAppendInterval(e,i.segment.time)&&(i.segment.loadedBytes===i.segment.size&&i.segment.bufferStatus==="none"?await this.appendSegmentFully(i,n):await this.appendSegmentPartially(i,n)),oe(a)&&this.withinRemoveInterval(e,a.segment.time)&&await this.removeSegment(a,n),this.pruneVirtualBuffer(e),this.maintainNativeBufferMutex=!1}async maintainPlaybackBuffer(e){Lt(this.downloadingRepresentationId);let t=this.segments.get(this.downloadingRepresentationId),i=this.representations.get(this.downloadingRepresentationId);if(ve(t)||ve(i)||this.maintainPlaybackBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex)return;this.maintainPlaybackBufferMutex=!0;let r=t.find(n=>e>=n.time.from&&e<n.time.to);oe(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from),this.downloadingBufferItems.length||(this.downloadingBufferItems=this.selectDownloadingItems(e,t)),await this.processCachedItems();let a=this.selectItemsToLoad();await this.loadItems(a,i),this.maintainPlaybackBufferMutex=!1}actualizeLastSegmentInfo(e){let t=this.segments.get(this.downloadingRepresentationId??"");if(ve(t)||t.length===0)return;let i=t[t?.length-1];ve(i)||(this.fullyBuffered$.next(i.time.to-e-this.getForwardPlaybackBufferDuration(e)<this.tuning.dash.bufferTolerance),this.onLastSegment$.next(e-i.time.from>0))}selectDownloadingItems(e,t){Lt(this.downloadingRepresentationId);let i=this.getPlaybackBufferState(),r,a;oe(i)&&this.withinInterval(e,i)?(a=this.forwardBufferTarget-this.getForwardPlaybackBufferDuration(e),r=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segmentIndex+1):(a=this.forwardBufferTarget,r=t.findIndex(o=>this.withinInterval(e,o.time))),r=r===-1?0:r;let n=[];for(;r<t.length&&a>0;){n.push({representationId:this.downloadingRepresentationId,segmentIndex:r,segment:t[r]});let{from:o,to:u}=t[r].time;a-=u-o,r++}return n}async processCachedItems(){let e=[...this.downloadingBufferItems];for(;e.length&&e[0].segment.networkStatus==="downloaded";)await this.onDownloadItem(e[0]),e.shift()}withinInterval(e,{from:t,to:i},r=this.tuning.dash.bufferTolerance){return oe(e)?e+r>=t&&e<i:!1}withinAppendInterval(e,{from:t,to:i}){let{actionTimeShiftFromSegment:r}=this.tuning.dash;return oe(e)?e+r>=t&&e+r<i||this.withinInterval(e,{from:t,to:i}):!1}withinRemoveInterval(e,{to:t}){let{actionTimeShiftFromSegment:i}=this.tuning.dash;return oe(e)?e-i>t:!1}async appendSegmentFully(e,t){if(ve(e.segment.data))return;e.segment.feedingBytes=e.segment.size,await this.nativeBufferManager.append(e.segment.data,t)&&(e.segment.fedBytes=e.segment.size,this.onItemFullyAppended(e))}async appendSegmentPartially(e,t){if(ve(e.segment.data)||ve(e.segment.loadedBytes)||ve(e.segment.feedingBytes)||ve(e.segment.fedBytes)||ve(e.segment.size))return;let i=e.segment.data,r=new DataView(i.buffer,i.byteOffset+e.segment.feedingBytes,i.byteLength-e.segment.feedingBytes),a=e.segment.loadedBytes!==e.segment.size?this.parseFeedableSegmentChunk(r):r;a?.byteLength&&(e.segment.bufferStatus="partially_fed",e.segment.feedingBytes+=a.byteLength,await this.nativeBufferManager.append(a,t)&&(e.segment.fedBytes+=a.byteLength,e.segment.fedBytes===e.segment.size&&this.onItemFullyAppended(e)))}parseFeedableSegmentChunk(e){return this.containerParser.parseFeedableSegmentChunk(e,!1)}onItemFullyDownloaded(e){e.segment.networkStatus="downloaded"}onItemFullyAppended(e){e.segment.bufferStatus="fed"}async removeSegment(e,t){let{from:i,to:r}=e.segment.time,a=(r-i)/4;await this.nativeBufferManager.remove(0,r-a,t)&&(e.segment.fedBytes=0,e.segment.feedingBytes=0,e.segment.bufferStatus="none",this.bufferPlaybackQueue.shift())}async onDownloadItem(e){if(!this.downloadingBufferItems.find(i=>i===e))return;let t=this.getCurrentPosition();return this.downloadingBufferItems=this.downloadingBufferItems.filter(i=>i!==e||i.segment.networkStatus!=="downloaded"),(this.preloadOnly||oe(t)&&!this.withinRemoveInterval(t,e.segment.time))&&!this.bufferPlaybackQueue.find(i=>i===e)&&this.bufferPlaybackQueue.push(e),this.maintainNativeBuffer()}pruneVirtualBuffer(e){let{maxVirtualBufferSize:t,virtualBufferPruneSize:i,bufferPruningSafeZone:r}=this.tuning.dash;if(this.currentVirtualBufferSize<t)return;let a=this.currentVirtualBufferSize-t+i;for(let n of this.segments.values())for(let o of n)oe(o.size)&&a>0&&o.time.to<=e-r&&o.bufferStatus==="none"&&o.networkStatus==="downloaded"&&(o.data=null,o.networkStatus="none",this.currentVirtualBufferSize-=o.size,a-=o.size);for(let n of this.segments.values())for(let o of[...n].reverse())oe(o.size)&&a>0&&o.time.from>=e+r&&o.bufferStatus==="none"&&o.networkStatus==="downloaded"&&!this.bufferPlaybackQueue.find(u=>u.segment===o)&&!this.downloadingBufferItems.find(u=>u.segment===o)&&(o.data=null,o.networkStatus="none",this.currentVirtualBufferSize-=o.size,a-=o.size)}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())this.updateRepresentationBaseUrl(t,e)}};import{ErrorCategory as u0,isNonNullable as l0,isNullable as jI,now as HI}from"@vkontakte/videoplayer-shared/es2024";var uu=class extends is{constructor(e,t,i,r){super(e,t,i,r)}async loadItems(e,t,i="auto"){let{signal:r}=this.downloadAbortController;if(r.aborted||!e.length)return;let{url:a,...n}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),!r.aborted)try{await this.fetcher.fetch(a,{...n,priority:i}),this.lastDataObtainedTimestampMs=HI(),this.failedDownloads=0}catch(o){this.abortDownloadingItems(),Le(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=0,t=0,i=[],r=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,a=this.preloadOnly?this.forwardBufferTarget:0,n=0;for(;n<this.downloadingBufferItems.length&&this.downloadingBufferItems[n].segment.networkStatus==="none"&&(e<=r||t<=a);){let o=this.downloadingBufferItems[n].segment;o.networkStatus="downloading",o.size=1/0,o.loadedBytes=0,o.feedingBytes=0,o.fedBytes=0,i.push(this.downloadingBufferItems[n]),e+=o.byte.to+1-o.byte.from,t+=o.time.to+1-o.time.from,n++}return i}prepareFetchParams(e,t){if(Ue(t.segmentReference))throw new Error("Representation is not byte range type");let{signal:i}=this.downloadAbortController,r=t.segmentReference.url,a={from:e[0].segment.byte.from,to:e[e.length-1].segment.byte.to};return{url:r,range:a,onProgress:async(o,u)=>{if(!i.aborted)try{this.lastDataObtainedTimestampMs=HI(),await this.onSomeDataLoaded({downloadingItems:e,dataView:o,loaded:u,signal:i,globalFrom:a?a.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:u0.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}},signal:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}async onSomeDataLoaded({downloadingItems:e,dataView:t,representationId:i,globalFrom:r,loaded:a,signal:n}){let o=this.representations.get(i);if(!(!this.downloadingBufferItems.length||jI(o)||jI(r)||n.aborted))for(let u of e){let{segment:l}=u,p=l.byte.from-r,c=l.byte.to-r,d=c-p+1,h=p<a,f=c<=a;l.size=d,h&&(l.networkStatus==="downloading"&&l.bufferStatus==="none"&&f?(l.data=new DataView(t.buffer,t.byteOffset+p,d),this.currentVirtualBufferSize+=l.size,this.onItemFullyDownloaded(u),l.loadedBytes=Math.min(d,a-p),await this.onDownloadItem(u)):l0(l.feedingBytes)&&this.tuning.dash.enableSubSegmentBufferFeeding&&l.networkStatus==="downloading"&&(l.loadedBytes=Math.min(d,a-p),f&&(this.currentVirtualBufferSize+=l.size,this.onItemFullyDownloaded(u)),l.loadedBytes>l.feedingBytes&&(l.data=new DataView(t.buffer,t.byteOffset+p,l.loadedBytes),await this.onDownloadItem(u))))}}updateRepresentationBaseUrl(e,t){if(Ue(e.segmentReference))throw new Error("Representation is not byte range type");e.segmentReference.url=t}};import{ErrorCategory as c0,isNullable as ip,now as zI}from"@vkontakte/videoplayer-shared/es2024";var rs=class extends is{constructor(e,t,i,r){super(e,t,i,r)}async loadItems(e,t,i="auto"){let{signal:r}=this.downloadAbortController;if(r.aborted||!e.length)return;let{url:a,...n}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),!r.aborted)try{let o=await this.fetcher.fetch(a,{...n,priority:i});if(this.lastDataObtainedTimestampMs=zI(),ip(o))return;let u=e[0],l=new DataView(o);u.segment.size=l.byteLength,u.segment.loadedBytes=l.byteLength,u.segment.data=l,this.onItemFullyDownloaded(u),await this.onDownloadItem(u),this.failedDownloads=0}catch(o){this.abortDownloadingItems(),Le(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=[];for(let t of this.downloadingBufferItems){let i=t.segment;i.networkStatus="downloading",i.size=1/0,i.loadedBytes=0,i.feedingBytes=0,i.fedBytes=0,e.push(t)}return e}prepareFetchParams(e,t){let i=this.getFetchUrl(e,t).toString(),{signal:r}=this.downloadAbortController;return{url:i,onProgress:async(n,o)=>{if(!r.aborted)try{this.lastDataObtainedTimestampMs=zI(),await this.onSomeDataLoaded({downloadingItems:e,dataView:n,loaded:o,signal:r,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:c0.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}},signal:r,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}getFetchUrl(e,t){if(!Ue(t.segmentReference))throw new Error("Representation is not template type");return new URL(e[0].segment.url,t.segmentReference.baseUrl)}async onSomeDataLoaded({downloadingItems:e,dataView:t,representationId:i,loaded:r,signal:a}){let n=e[0],{segment:o}=n,u=this.representations.get(i);!this.downloadingBufferItems.length||ip(u)||ip(o.feedingBytes)||o.networkStatus!=="downloading"||a.aborted||(o.loadedBytes=r,o.loadedBytes>o.feedingBytes&&this.tuning.dash.enableSubSegmentBufferFeeding&&(o.data=new DataView(t.buffer,t.byteOffset,o.loadedBytes),await this.onDownloadItem(n)))}updateRepresentationBaseUrl(e,t){if(!Ue(e.segmentReference))throw new Error("Representation is not template type");e.segmentReference.baseUrl=t}};var rp=D(Wi(),1),WI=D(Ge(),1);import{assertNonNullable as d0,ErrorCategory as p0,isNullable as jt,ValueSubject as QI}from"@vkontakte/videoplayer-shared/es2024";var lu=class extends rs{constructor(t,i,r,a){super(t,i,r,a);this.currentLiveSegmentServerLatency$=new QI(0);this.currentLowLatencySegmentLength$=new QI(0);this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.isActiveLowLatency=a.isActiveLowLatency}updateManifest(t){if(!t||[...this.segments.values()].every(r=>!r.length))return;let i=(0,rp.default)(t.streams[this.kind],r=>r.representations);for(let r of i){if(jt(r)||!Ue(r.segmentReference))return;let a=r.segmentReference.segments.map(p=>({...p,networkStatus:"none",bufferStatus:"none",size:void 0})),n=100,o=this.segments.get(r.id)??[],u=(0,WI.default)(o,-1)?.time.to??0,l=a?.findIndex(p=>u>=p.time.from+n&&u<=p.time.to+n);if(l===-1){let p=this.getActualLiveStartingSegments(r.segmentReference);this.segments.set(r.id,p)}else{let p=a.slice(l+1);this.segments.set(r.id,[...o,...p])}this.representations.set(r.id,r)}}proceedLowLatencyLive(){let t=this.downloadingRepresentationId;d0(t);let i=this.segments.get(t);if(i?.length){let r={representationId:t,segmentIndex:i.length-1,segment:i[i.length-1]};this.updateLowLatencyLive(r)}}getLiveSegmentsToLoadState(t){let i=t?.streams[this.kind],r=(0,rp.default)(i,n=>n.representations).find(n=>n.id===this.downloadingRepresentationId);if(jt(r))return;let a=this.segments.get(r.id);if(a?.length)return{from:a[0].time.from,to:a[a.length-1].time.to}}getRepresentationInitialTime(){if(jt(this.playingRepresentationId))return 0;let t=this.representations.get(this.playingRepresentationId)?.segmentReference;return jt(t)||!Ue(t)?0:this.getActualLiveStartingSegments(t)[0].time.from+this.tuning.dash.bufferTolerance}prepareFetchParams(t,i){return{...super.prepareFetchParams(t,i),isLowLatency:this.isActiveLowLatency()}}async onSomeDataLoaded({downloadingItems:t,...i}){await super.onSomeDataLoaded({downloadingItems:t,...i}),this.isActiveLowLatency()&&this.updateLowLatencyItemTime(t[0])}onItemFullyDownloaded(t){if(super.onItemFullyDownloaded(t),jt(t.segment.data)||!this.isActiveLowLatency())return;let i=t.segment.data,r=this.containerParser,{serverDataReceivedTimestamp:a,serverDataPreparedTime:n}=r.getServerLatencyTimestamps(i);a&&n&&this.currentLiveSegmentServerLatency$.next(n-a),this.updateLowLatencyItemTime(t),this.updateLowLatencyLive(t)}updateLowLatencyItemTime(t){let i=t.segment.data,r=this.representations.get(t.representationId)?.segmentReference;if(jt(t.segment.data)||jt(r)||!Ue(r))return;let a=this.containerParser;if(t.segment.isCurrentLowLatency){let{timescale:n}=r;t.segment.time.to=a.getChunkEndTime(i,n)}}updateLowLatencyLive(t){let i=0;for(let r of this.representations.values()){let a=r.segmentReference;if(!Ue(a))return;let n=this.segments.get(r.id)??[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(t.segment.time.from));if(o?.isCurrentLowLatency&&(o.time.to=t.segment.time.to,i=o.time.to-o.time.from,o.isCurrentLowLatency=!1),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(t.segment.time.to))&&this.isActiveLowLatency()){let l=Math.round(t.segment.time.to*a.timescale/1e3).toString(10),p=tt(a.segmentTemplateUrl,{segmentTime:l});n.push({networkStatus:"none",bufferStatus:"none",time:{from:t.segment.time.to,to:t.segment.time.to+this.tuning.dash.bufferTolerance},url:p,isCurrentLowLatency:!0})}}this.currentLowLatencySegmentLength$.next(i)}parseFeedableSegmentChunk(t){return this.containerParser.parseFeedableSegmentChunk(t,!0)}getFetchUrl(t,i){let r=super.getFetchUrl(t,i);return this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes"),r}async loadInit(t,i="auto",r=!1){try{let a=this.tuning.dash.useFetchPriorityHints?i:"auto",n=this.fetcher.fetchRepresentation(t.segmentReference,this.containerParser,a);this.initDataPromises.set(t.id,n);let{initMetadata:o,initDataView:u,segments:l}=await n??{};if(this.initDataPromises.delete(t.id),jt(u)||jt(l))return;o&&this.parsedInitData.set(t.id,o);let p=this.getActualLiveStartingSegments(t.segmentReference);this.segments.has(t.id)||this.segments.set(t.id,p);let c=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(t.id,c),this.failedDownloads=0}catch(a){r&&this.error$.next({id:"LoadInits",category:p0.WTF,message:"loadInit threw",thrown:a})}}getActualLiveStartingSegments(t){let i=t.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,a=[],n=0,o=i.length-1;do a.unshift(i[o]),n+=i[o].time.to-i[o].time.from,o--;while(n<r&&o>=0);return this.liveInitialAdditionalOffset=n-r,this.isActiveLowLatency()?[a[0]]:a}};var Qa=class{static getBufferManager(e,t,i,r){return r.manifest?.live?new lu(e,t,i,r):Ue(i[0].segmentReference)?new rs(e,t,i,r):new uu(e,t,i,r)}};import{ErrorCategory as m0,fromEvent as b0,isNullable as ss,Subject as g0,Subscription as S0}from"@vkontakte/videoplayer-shared/es2024";import{assertNever as h0,ErrorCategory as GI,Subject as YI}from"@vkontakte/videoplayer-shared/es2024";var f0=18,KI=!1;try{KI=$.browser.isSafari&&!!$.browser.safariVersion&&$.browser.safariVersion<=f0}catch(s){console.error(s)}var sp=class{constructor(e,t=!1){this.bufferFull$=new YI;this.error$=new YI;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:GI.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};KI&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,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)&&!this.abortRequested)return;let e=this.isAbortFixEnabled?this.queue[0]: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(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:GI.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),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:h0(t)}}},XI=sp;var de=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){let r=s.start(i)*1e3,a=s.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};var Wa=class{constructor(e){this.error$=new g0;this.subscription=new S0;this.mediaSource=e}init(e,t,i=!1){this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e}; codecs="${t}"`),this.sourceBufferTaskQueue=new XI(this.sourceBuffer,i),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(r=>this.error$.next(r))),this.subscription.add(b0(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:m0.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"})))}addInitSegment(e,t){return this.sourceBufferTaskQueue.append(e,t)}append(e,t){return this.sourceBufferTaskQueue.append(e,t)}remove(e,t,i){return this.sourceBufferTaskQueue.remove(e,t,i)}async clear(e){let t=this.getBufferState();if(ss(t))return Promise.resolve(!1);let i=!0;await this.sourceBufferTaskQueue.abort();for(let r of t)i&&=await this.sourceBufferTaskQueue.remove(r.from,r.to,e);return i}warmUpMediaSource(){!ss(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}getBufferState(){if(ss(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length)return null;let e=[];for(let t=0;t<this.sourceBuffer.buffered.length;t++)e.push({from:this.sourceBuffer.buffered.start(t)*1e3,to:this.sourceBuffer.buffered.end(t)*1e3});return e}getForwardBufferDuration(e){return ss(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ss(e)?0:de(this.sourceBuffer.buffered,e)}async abortBuffer(e){return ss(this.sourceBuffer)?!1:this.sourceBufferTaskQueue.abort(e)}destroy(){if(this.subscription.unsubscribe(),this.sourceBufferTaskQueue?.destroy(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null}};var w0=["timeupdate","progress","play","seeked","stalled","waiting"],eE=["timeupdate","progress","loadeddata","playing","seeked"],du=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.nativeBufferManagers=[];this.subscription=new ZI;this.subscriptionRemovable=new E0;this.representationSubscription=new ZI;this.forceEnded$=new gi;this.destroyController=new j;this.state$=new O("none");this.currentVideoRepresentation$=new Z(void 0);this.currentVideoRepresentationInit$=new Z(void 0);this.currentAudioRepresentation$=new Z(void 0);this.currentVideoSegmentLength$=new Z(0);this.currentAudioSegmentLength$=new Z(0);this.error$=new gi;this.manifestRequested=new gi;this.manifestReceived=new gi;this.firstBytesRequested=new gi;this.firstBytesReceived=new gi;this.lastConnectionType$=new Z(void 0);this.lastConnectionReused$=new Z(void 0);this.lastRequestFirstBytes$=new Z(void 0);this.currentLiveTextRepresentation$=new Z(null);this.isLive$=new Z(!1);this.isActiveLive$=new Z(!1);this.isLowLatency$=new Z(!1);this.liveDuration$=new Z(0);this.liveSeekableDuration$=new Z(0);this.liveAvailabilityStartTime$=new Z(0);this.liveStreamStatus$=new Z(void 0);this.currentBuffer$=new Z({from:0,to:0});this.bufferLength$=new Z(0);this.nativeBufferLength$=new Z(0);this.liveLatency$=new Z(void 0);this.liveLoadBufferLength$=new Z(0);this.livePositionFromPlayer$=new Z(0);this.currentStallDuration$=new Z(0);this.videoLastDataObtainedTimestamp$=new Z(0);this.fetcherRecoverableError$=new gi;this.fetcherError$=new gi;this.initRepresentations=JI(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",cu({initialVideo:e,initialAudio:t,sourceHls:i})),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest};this.createBuffers(r,e,t,i),this.initRepresentationSubscriptions(),yield this.waitStreamToOpen(),this.setSourceDuration(),Ht(this.videoBufferManager),yield Promise.all([this.videoBufferManager.startWith(e),t?this.audioBufferManager?.startWith(t):Promise.resolve()]),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.fetchManifest=JI(this.destroyController.signal,async function*(){try{return yield this.fetcher.fetchManifest(this.manifestUrlString)}catch(e){Ga(this.manifest)&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Xi.NETWORK,message:"Failed to load manifest",thrown:e})}}.bind(this));this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new iu({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.initTracerSubscription()}async initManifest(e,t,i){this.tracer.log("initManifest"),this.state$.startTransitionTo("manifest_ready"),this.element=e,this.manifestUrlString=this.prepareManifestUrlString(t,i),this.manifest=await this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Xi.PARSER,message:"No playable video representations"})}initBuffer(){Ht(this.element),this.state$.setState("running"),this.subscription.add(Ya(...w0.map(t=>Ji(this.element,t)),Ji(window,"online")).subscribe(()=>this.tick(),t=>this.error$.next({id:"DashVKPlayer",category:Xi.WTF,message:"Internal logic error",thrown:t})));let e=[...this.source?.activeSourceBuffers??[]];this.subscription.add(Ya(...e.map(t=>Ji(t,"updateend"))).subscribe(t=>this.reinitDecoderIfNeeded())),this.subscription.add(Ji(this.element,"waiting").subscribe(t=>{this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=T0(this.tuning.dash.stallWatchdogInterval).subscribe(()=>this.stallWatchdogIntervalCallback(),i=>this.error$.next({id:"StallWatchdogCallback",category:Xi.NETWORK,message:"Can't restore DASH after stall.",thrown:i})),this.subscriptionRemovable.add(this.stallWatchdogSubscription)}))}async switchRepresentation(e,t,i=!1){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,i)}async seek(e,t=!1){Ht(this.element),Ht(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),this.warmUpMediaSourceIfNeeded(i),this.element.currentTime=i/1e3,await this.videoBufferManager.seek(i),await this.audioBufferManager?.seek(i),this.tracer.log("seek",cu({requestedPosition:e,forcePrecise:t,position:i}))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){bi(this.element)&&bi(this.source)&&bi(e)&&this.isStreamEnded&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.nativeBufferManagers.forEach(t=>t.warmUpMediaSource())}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}get isStreamEnded(){return this.source?.readyState==="ended"}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setBufferTarget(e){this.bufferManagers.forEach(t=>t.setTarget(e))}setPreloadOnly(e){this.bufferManagers.forEach(t=>t.setPreloadOnly(e))}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.nativeBufferManagers.forEach(e=>e.destroy()),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),bi(this.source)&&this.isStreamNotOpen&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}get isStreamNotOpen(){return this.source?.readyState!=="open"}async reinitDecoderIfNeeded(e=!1){let t=this.videoNativeBufferManager?.getBufferState()??[];if(Ga(this.element)||!t.length)return;let i=this.element.currentTime*1e3;this.element.readyState<3&&t.some(r=>i>=r.from&&i<=r.to)&&(e?await this.seek(i):this.element.currentTime=this.element.currentTime)}async stallWatchdogIntervalCallback(){Ht(this.element),Ht(this.source);let{stallWatchdogInterval:e}=this.tuning.dash;if(this.isStreamNotOpen)return;let t=this.currentStallDuration$.getValue()+e;this.currentStallDuration$.next(t);let i={timeInWaiting:t};if(await this.reinitDecoderIfNeeded(t%1e3===0),this.isStallExceeded(t))throw new Error(`Stall timeout exceeded: ${t} ms`);await this.restoreAfterDeepStall(i),this.tracer.log("stallIntervalCallback",cu(i))}isStallExceeded(e){let{crashOnStallTimeout:t,crashOnStallTWithoutDataTimeout:i}=this.tuning.dash,r=I0(),a=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardPlaybackBufferDuration()??0,l=this.audioBufferManager?.getForwardPlaybackBufferDuration()??0,p=bi(this.videoBufferManager)&&u<a&&r-n>i,c=bi(this.audioBufferManager)&&l<a&&r-o>i;return(p||c)&&e>i||e>=t}async updateManifest(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=await this.fetchManifest();if(Ga(e))return null;let t=this.parseManifest(e);if(!t)return null;let i=this.getResultManifest(t);return this.tracer.log("updateManifestEnd",cu(i)),i}parseManifest(e){try{return Xr(e??"",this.manifestUrlString)}catch(t){let i=Hr(e)??{id:"ManifestParsing",category:Xi.PARSER,message:"Failed to parse MPD manifest",thrown:t};this.error$.next(i)}}getResultManifest(e){let t={text:e.streams.text,video:[],audio:[]},i=(o,u,l)=>!!(this.element?.canPlayType?.(u)&&Ve()?.isTypeSupported?.(`${u}; codecs="${l}"`)||o==="text"),r,a;for(let o of["video","audio"]){let l=e.streams[o].filter(({mime:c,codecs:d})=>i(o,c,d));t[o]=l;let p;if(this.tuning.dash.codecsPrioritizeEnabled){let c=l.map(({codecs:d})=>d);o==="audio"&&(a=es(c),p=a[0]),o==="video"&&(r=Zr(c),this.forceVideoCodec&&(0,tE.default)(r,this.forceVideoCodec)?p=this.forceVideoCodec:p=r[0]),p&&(t[o]=l.filter(({codecs:d})=>hi(d)===p))}else{let c=new Set(l.map(({codecs:d})=>d));p=Jr(c),p&&(t[o]=l.filter(({codecs:d})=>d.startsWith(p)))}if(o==="video"){let c=this.tuning.preferHDR,d=t.video.some(f=>f.hdr),h=t.video.some(f=>!f.hdr);$.display.isHDR&&c&&d?t.video=t.video.filter(f=>f.hdr):h&&(t.video=t.video.filter(f=>!f.hdr))}}let n={...e,streams:t};return this.tuning.dash.codecsPrioritizeEnabled&&(n.codecs={video:r,audio:a}),n}stopStallWatchdogSubscription(){this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)}createBuffers(e,t,i,r){Ht(this.manifest),Ht(this.element);let a=u=>{this.representationSubscription.add(Ji(u,"error").pipe(ap(l=>!!this.element?.played.length)).subscribe(l=>{this.error$.next({id:"VideoSource",category:Xi.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:l})}))};this.source=Ir();let n=document.createElement("source");if(a(n),n.src=URL.createObjectURL(this.source),this.element.appendChild(n),ai())if(r){let u=document.createElement("source");a(u),u.type="application/x-mpegurl",u.src=r.url,this.element.appendChild(u)}else this.element.disableRemotePlayback=!0;let o=this.manifest.streams.video.reduce((u,l)=>[...u,...l.representations],[]);if(this.videoNativeBufferManager=new Wa(this.source),this.videoBufferManager=Qa.getBufferManager("video",this.videoNativeBufferManager,o,e),this.bufferManagers=[this.videoBufferManager],this.nativeBufferManagers=[this.videoNativeBufferManager],bi(i)){this.audioNativeBufferManager=new Wa(this.source);let u=this.manifest.streams.audio.reduce((l,p)=>[...l,...p.representations],[]);this.audioBufferManager=Qa.getBufferManager("audio",this.audioNativeBufferManager,u,e),this.bufferManagers.push(this.audioBufferManager),this.nativeBufferManagers.push(this.audioNativeBufferManager)}}async waitStreamToOpen(){if(this.isStreamNotOpen){let e=this.tuning.dash.sourceOpenTimeout>=0;await new Promise(t=>{e&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.isStreamNotOpen){t();return}this.error$.next({id:"OpenOfStream",category:Xi.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),t()},{once:!0})})}}initRepresentationSubscriptions(){this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),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(Ya(...this.bufferManagers.map(e=>e.error$)).subscribe(this.error$)),Ht(this.videoBufferManager),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.initBufferLengthSubscription()}initBufferLengthSubscription(){this.representationSubscription.add(Ya(...eE.map(e=>Ji(this.element,e))).pipe(np(e=>this.videoBufferManager?.getPlaybackBufferState()),ap(bi),np(({from:e,to:t})=>({from:e/1e3,to:t/1e3}))).subscribe(this.currentBuffer$)),this.representationSubscription.add(Ya(...eE.map(e=>Ji(this.element,e))).pipe(np(e=>Math.max(this.videoBufferManager?.getForwardPlaybackBufferDuration()??0,this.audioBufferManager?.getForwardPlaybackBufferDuration()??0)),v0()).subscribe(this.bufferLength$)),this.representationSubscription.add(this.nativeBufferLength$.pipe(ap(e=>e>this.tuning.dash.bufferEmptinessTolerance)).subscribe(e=>this.stopStallWatchdogSubscription()))}initTracerSubscription(){let e=y0(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}async tick(){if(Ga(this.element)||Ga(this.videoBufferManager)||this.isStreamNotOpen)return;let e=this.element.currentTime*1e3,i=(this.videoNativeBufferManager?.getBufferState()??[]).find(r=>e>=r.from&&e<=r.to);this.nativeBufferLength$.next(i?i.to-e:0),await this.videoBufferManager.maintain(e),await this.audioBufferManager?.maintain(e)}};import{assertNonNullable as pu,combine as x0,ErrorCategory as k0,filter as op,filterChanged as P0,fromEvent as A0,isNonNullable as R0,map as up,merge as Ka}from"@vkontakte/videoplayer-shared/es2024";var hu=class extends du{constructor(e){super(e)}prepareManifestUrlString(e,t){return e}initRepresentationSubscriptions(){super.initRepresentationSubscriptions(),this.initDisableStallWatchdogSubscription(),this.initEndOfVideoSubscription()}setSourceDuration(){pu(this.manifest),pu(this.source);let e=[this.manifest.duration??0,...(0,lp.default)((0,lp.default)([...this.manifest.streams.audio,...this.manifest.streams.video],t=>t.representations),t=>{let i=[];return t.duration&&i.push(t.duration),Ue(t.segmentReference)&&t.segmentReference.totalSegmentsDurationMs&&i.push(t.segmentReference.totalSegmentsDurationMs),i})];this.source.duration=Math.max(...e)/1e3}async restoreAfterDeepStall(e){pu(this.element);let t=this.element.currentTime*1e3;await Promise.all([this.videoBufferManager?.maintain(t),this.audioBufferManager?.maintain(t)]),e.position=t}initDisableStallWatchdogSubscription(){pu(this.element);let e=Ka(A0(this.element,"ended"),this.forceEnded$),t=this.nativeBufferLength$.pipe(op(i=>i>this.tuning.dash.bufferEmptinessTolerance));this.representationSubscription.add(Ka(e,t).subscribe(i=>this.stopStallWatchdogSubscription()))}initEndOfVideoSubscription(){let e=Ka(...this.bufferManagers.map(a=>a.fullyBuffered$)).pipe(up(()=>this.bufferManagers.every(a=>a.fullyBuffered$.getValue()))),t=Ka(...this.bufferManagers.map(a=>a.onLastSegment$)).pipe(up(()=>this.bufferManagers.some(a=>a.onLastSegment$.getValue()))),i=x0({allBuffersFull:e,someBufferEnded:t}).pipe(P0(),up(({allBuffersFull:a,someBufferEnded:n})=>a&&n),op(a=>a)),r=()=>{try{this.source?.endOfStream()}catch(a){this.error$.next({id:"EndOfStream",category:k0.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:a})}};this.representationSubscription.add(Ka(this.forceEnded$,i).pipe(op(a=>R0(this.source)&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(n=>!n.updating))).subscribe(r))}};var as=class extends pa{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i,genericErrorListener:r}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$),this.subscription.add(this.player.currentVideoRepresentation$.pipe($0()).subscribe(a=>{let n=[...this.videoTracksMap.entries()].find(([,{representation:c}])=>c.id===a);if(!n){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[o,{stream:u}]=n,l=this.params.desiredState.videoStream.getTransition();l&&l.to&&l.to.id===u.id&&this.params.desiredState.videoStream.setState(l.to),e.currentVideoTrack$.next(o),e.currentVideoStream$.next(Wo(u));let p=this.player.calculateDurationFromSegments();p&&this.params.output.duration$.next(p/1e3)},r))}getPlayer(){return new hu({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec})}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{assertNever as t_,assertNonNullable as i_,combine as r_,debounce as s_,ErrorCategory as fE,filter as vp,filterChanged as nn,fromEvent as a_,isNonNullable as mE,isNullable as n_,map as on,merge as un,observableFrom as xu,once as bE,Subscription as o_,throttle as u_}from"@vkontakte/videoplayer-shared/es2024";var hE=D(ke(),1),gp=D(Wi(),1);var De=(s,e,t=0)=>{for(let i=0;i<s.length;i++)if(s.start(i)*1e3-t<=e&&s.end(i)*1e3+t>e)return!0;return!1};import{abortable as fp,assertNonNullable as cs,combine as ds,ErrorCategory as ct,filter as Iu,filterChanged as rn,flattenObject as sn,fromEvent as Wt,getTraceSubscriptionMethod as j0,interval as mp,isNonNullable as an,isNullable as cE,map as ps,merge as tr,now as bp,Subject as Gt,Subscription as dE,SubscriptionRemovable as H0,tap as z0,throttle as Q0,ValueSubject as ee}from"@vkontakte/videoplayer-shared/es2024";var mu=D(ke(),1),er=D(Ge(),1),bu=D(Wi(),1);var nE=D(Ro(),1);import{assertNever as M0,ErrorCategory as iE,Subject as rE}from"@vkontakte/videoplayer-shared/es2024";var L0=18,sE=!1;try{sE=$.browser.isSafari&&!!$.browser.safariVersion&&$.browser.safariVersion<=L0}catch(s){console.error(s)}var cp=class{constructor(e,t=!1){this.bufferFull$=new rE;this.error$=new rE;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:iE.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};sE&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,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)&&!this.abortRequested)return;let e=this.isAbortFixEnabled?this.queue[0]: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(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:iE.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),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:M0(t)}}},aE=cp;var ns=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};import{abortable as Si,assertNonNullable as je,ErrorCategory as zt,fromEvent as dp,getExponentialDelay as pp,isHigher as D0,isNonNullable as vi,isNullable as pe,now as fu,once as B0,Subject as C0,Subscription as V0,ValueSubject as Zi}from"@vkontakte/videoplayer-shared/es2024";var Xa=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Zi(0);this.currentLowLatencySegmentLength$=new Zi(0);this.currentSegmentLength$=new Zi(0);this.onLastSegment$=new Zi(!1);this.fullyBuffered$=new Zi(!1);this.playingRepresentation$=new Zi(void 0);this.playingRepresentationInit$=new Zi(void 0);this.error$=new C0;this.gaps=[];this.subscription=new V0;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new j;this.switchAbortController=new j;this.destroyAbortController=new j;this.useSmartRepresentationSwitch=!1;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=Si(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);je(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new aE(this.sourceBuffer,this.tuning.dash.useAbortMSEFix),this.subscription.add(dp(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:zt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:zt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add(dp(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:zt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!V(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,ns(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<p).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),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),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);je(i,"No init buffer for starting representation"),je(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))}.bind(this));this.switchTo=Si(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);je(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(pe(a)||pe(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),je(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();vi(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Si(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);je(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(pe(a)||pe(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),je(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();vi(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=Si(this.destroyAbortController.signal,async function*(e){let t=(0,bu.default)(e,u=>u.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let u of this.representations.keys()){let l=t.find(d=>d.id===u);l&&this.representations.set(u,l);let p=this.representations.get(u);if(!p||!it(p.segmentReference)){this.isSeekingLive=!1;return}let c=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);je(r,`Representation not found by id ${i}`);let a=this.segments.get(i);je(a,"No segments for starting representation");let n=this.initData.get(i);if(je(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(p=>[p.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(p=>[p.id,p])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new j,Si(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);je(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(pe(o)||pe(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),je(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();vi(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))}warmUpMediaSource(){!pe(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new j,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(pe(e)||pe(this.downloadingRepresentationId)||pe(this.playingRepresentationId)||pe(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||vi(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),a=this.segments.get(this.playingRepresentationId);if(je(t,`No such representation ${this.downloadingRepresentationId}`),je(i,`No such representation ${this.playingRepresentationId}`),pe(r)||pe(a))return;let n=r.find(d=>e>=d.time.from&&e<d.time.to);vi(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next(n?.time.to-n.time.from);let o=e,u=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=this.getForwardBufferDuration(e),h=mi(i),f=mi(t),m=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&vi(h)&&vi(f)&&D0(h.quality,f.quality),S=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(m||S?o+=Math.min(d,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=n.time.to-e+u&&(o=n?n.time.to+u:-1/0),this.tuning.dash.useNewRepresentationSwitch){let v=[...this.segments.entries()].map(([T,y])=>{let x=y.find(A=>e>=A.time.from&&e<A.time.to);return{representationId:T,status:x?.status}}).find(T=>T.status==="fed")?.representationId;v&&(this.playingRepresentationId=v,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&ns(this.sourceBuffer.buffered)>=this.bufferLimit){let d=this.getForwardBufferDuration(e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let p=[];if(!this.activeSegments.size&&(p=this.selectForwardBufferSegments(r,t.segmentReference.type,o),p.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,mu.default)(p,n))d="high";else{let h=(0,er.default)(p,0);h&&h.time.from-n.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(p,t,d).catch(h=>{this.handleAsyncError(h,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!p.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let c=(0,er.default)(r,-1);!this.isLive&&c&&(this.fullyBuffered$.next(c.time.to-e-this.getForwardBufferDuration(e)<u),this.onLastSegment$.next(e-c.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r,persistent:!0}),i=a.time.to;vi(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind];if(!t)return;let i=(0,bu.default)(t,a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){if(!e||[...this.segments.values()].every(i=>!i.length))return;let t=(0,bu.default)(e.streams[this.kind],i=>i.representations);for(let i of t){if(!i||!it(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),a=100,n=this.segments.get(i.id)??[],o=(0,er.default)(n,-1)?.time.to??0,u=r?.findIndex(l=>o>=l.time.from+a&&o<=l.time.to+a);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(u+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;je(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,er.default)(e,-1)?.time.to:0)||0}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!it(r))return;let a=this.segments.get(i.id)??[],n=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=tt(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(a=>a.time.from<=e&&a.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&&qe&&qe(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&qe&&qe(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)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(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),a=e.findIndex(({status:d,time:{from:h,to:f}},m)=>{let S=h<=i&&f>=i,g=h>i||S||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&h<=i+v||r<v&&f-h>=v||f<=i+v;return(d==="none"||d==="partially_ejected"&&g&&T&&this.sourceBuffer&&V(this.mediaSource,this.sourceBuffer)&&!(De(this.sourceBuffer.buffered,h)&&De(this.sourceBuffer.buffered,f)))&&g&&T});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,l=[],p=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<n.length&&(o<=p||u<=c);d++){let h=n[d];if(o+=h.byte.to+1-h.byte.from,u+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){it(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 r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Si(o,async function*(){let p=pp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,p))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let p=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=fu(),!p)return;let c=new DataView(p),d=lt(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(c,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=d.getServerLatencyTimestamps(c);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(p){this.abortActiveSegments([e]),Le(p)||(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())it(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:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Si(n,async function*(){let u=pp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),dp(window,"online").pipe(B0()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=fu(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Le(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(it(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,er.default)(e,0).byte.from,to:(0,er.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:async(o,u)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=fu(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:zt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!it(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 r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,p)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=fu();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:p,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:zt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,mu.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!V(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),p=lt(n.mime).parseFeedableSegmentChunk(l,this.isLive);p?.byteLength&&(u.status="partially_fed",o.feedingBytes+=p.byteLength,await this.sourceBufferTaskQueue.append(p),o.fedBytes+=p.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!V(this.mediaSource,this.sourceBuffer))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(a.aborted){await n();continue}let p=l.byte.from-i,c=l.byte.to-i,d=c-p+1,h=p<r,f=c<=r;if(!h)continue;let m=lt(o.mime);if(l.status==="downloading"&&f){l.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+p,d);await this.sourceBufferTaskQueue.append(S,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(d,r-p),u.loadedBytes>u.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+p+u.feedingBytes,u.loadedBytes-u.feedingBytes),g=u.loadedBytes===d?S:m.parseFeedableSegmentChunk(S);g?.byteLength&&(l.status="partially_fed",u.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,a)&&!a.aborted?(u.fedBytes+=g.byteLength,u.fedBytes===d&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){if(!(pe(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer))){!this.isLive&&$.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(De(this.sourceBuffer.buffered,e.segment.time.from,100)&&De(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:zt.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.tuning.dash.useNewRepresentationSwitch||(this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))),e.segment.status="fed",ep(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&Math.round(r.time.from)===Math.round(e.segment.time.from)&&Math.round(r.time.to)===Math.round(e.segment.time.to)&&(r.status="none");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[r,a]of this.initData.entries()){let n=a instanceof Promise;t||=n,a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Mt(()=>(0,nE.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",a=!i&&this.tuning.dash.ignoreNetworkErrorsOnLoadInit,o=(!i&&this.failedDownloads>0?Si(this.destroyAbortController.signal,async function*(){let u=pp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,lt(e.mime),{priority:r,ignoreNetworkErrors:a})).then(async u=>{if(!u)return;let{init:l,dataView:p,segments:c}=u,d=p.buffer.slice(p.byteOffset,p.byteOffset+p.byteLength);this.initData.set(e.id,d);let h=c;this.isLive&&it(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),l&&this.parsedInitData.set(e.id,l)}).then(()=>this.failedDownloads=0,u=>{a||this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:zt.WTF,message:"loadInit threw",thrown:u})});return this.initData.set(e.id,o),o}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||!V(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||pe(e))return!1;let r=[],a=0,n=u=>{u.sort((p,c)=>p.from-c.from);let l=[u[0]];for(let p=1;p<u.length;p++){let{from:c,to:d}=u[p],h=l[l.length-1];h.to>=c?h.to=Math.max(h.to,d):l.push(u[p])}return l},o=u=>{if(a>=t)return r;r.push({...u.time}),r=n(r);let l=ep(u)?u.size??0:u.byte.to-u.byte.from;a+=l};for(let u of this.segments.values())for(let l of u){let p=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(p||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,p=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let d of this.segments.values())for(let h of d)(0,mu.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(p)&&c++;if(c===this.segments.size){let d={time:{from:l,to:p},url:"",status:"none"};o(d)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let p of l)p.time.from>=e+u&&p.status==="fed"&&o(p)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,p)=>l||p,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||pe(e)?0:de(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)))for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to,persistent:!1},{buffered:a}=this.sourceBuffer;for(let n=0;n<a.length;n++){let o=a.start(n)*1e3,u=a.end(n)*1e3;if(!(u<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&u>=i.time.to){r=void 0;break}u>i.time.from&&u<i.time.to&&(r.from=u),o<i.time.to&&o>i.time.from&&(r.to=o)}}r&&r.to-r.from>1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,{usePersistentGaps:r}=this.tuning.dash;this.gaps=this.gaps.filter(a=>{if(r&&a.persistent)return!0;let n=Math.round(a.from),o=Math.round(a.to);for(let u=0;u<i.length;u++)if(n>=Math.round(i.start(u)*1e3)&&o<=Math.round(i.end(u)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=Mt(()=>{try{this.detectGaps(e,t)}catch(a){this.error$.next({id:"GapDetection",category:zt.WTF,message:"detectGaps threw",thrown:a})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(pe(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||pe(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),a=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(p=>p.from-t<=n&&p.to+t>=o),l=e.filter(p=>n>=p.from&&n<p.to-t||o>p.from+t&&o<=p.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(p=>p.from===r.time.from||p.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:zt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};import{abortable as Ja,assertNever as oE,fromEvent as uE,merge as _0,now as Za,Subject as os,ValueSubject as hp,flattenObject as us,ErrorCategory as en,SubscriptionRemovable as O0}from"@vkontakte/videoplayer-shared/es2024";var Su=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.manifestRequested$=new os;this.firstBytesManifest$=new os;this.firstBytesRequested$=new os;this.firstBytesReceived$=new os;this.lastConnectionType$=new hp(void 0);this.lastConnectionReused$=new hp(void 0);this.lastRequestFirstBytes$=new hp(void 0);this.recoverableError$=new os;this.error$=new os;this.abortAllController=new j;this.subscription=new O0;this.fetchManifest=Ja(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Tt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Qr(i)),this.manifestRequested$.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(gu);return r?(t.log("success",us({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),this.firstBytesManifest$.next(),r.text()):(t.error("error",us({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Ja(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:l=!1,ignoreNetworkErrors:p=!1}={}){let c=e,d=new Headers,h=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let I=new URL(c,location.href);I.searchParams.append("bytes",`${i.from}-${i.to}`),c=I.toString();break}default:oE(t)}this.requestQuic&&(c=Tt(c));let f=this.abortAllController.signal,m;if(n){let I=new j;if(m=_0(uE(this.abortAllController.signal,"abort"),uE(n,"abort")).subscribe(()=>{try{I.abort()}catch(N){gu(N)}}),this.subscription.add(m),this.abortAllController.signal.aborted||n.aborted)try{I.abort()}catch(N){gu(N)}f=I.signal}let S=0,g=Za();h.log("startRequest",us({url:c,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:g})),this.firstBytesRequested$.next();let v=yield this.doFetch(c,{priority:a,headers:d,signal:f},{ignoreNetworkErrors:p}),T=Za();if(!v)return h.error("error",{message:"No response in request"}),h.end(),this.unsubscribeAbortSubscription(m),null;if(this.throughputEstimator?.addRawRtt(T-g),!v.ok||!v.body){this.unsubscribeAbortSubscription(m);let I=`Fetch error ${v.status}: ${v.statusText}`;return h.error("error",{message:I}),h.end(),Promise.reject(new Error(`Fetch error ${v.status}: ${v.statusText}`))}if(this.onHeadersReceived(v.headers),!r&&!o){this.unsubscribeAbortSubscription(m);let I=Za(),N={requestStartedAt:g,requestEndedAt:I,duration:I-g};return h.log("endRequest",us(N)),h.end(),v.arrayBuffer()}let y=v.body;if(o){let I;[y,I]=v.body.tee(),this.throughputEstimator?.trackStream(I,u)}let x=y.getReader(),A,R=parseInt(v.headers.get("content-length")??"",10);Number.isFinite(R)&&(A=R),!A&&i&&(A=i.to-i.from+1);let w=A?new Uint8Array(A):new Uint8Array(0),B=!1,k=I=>{this.unsubscribeAbortSubscription(m),B=!0,gu(I)},F=Ja(f,async function*({done:I,value:N}){if(S===0&&(this.lastRequestFirstBytes$.next(Za()-g),this.firstBytesReceived$.next()),f.aborted){this.unsubscribeAbortSubscription(m);return}if(!I&&N){if(l&&A)w.set(N,S),S+=N.byteLength;else{let L=new Uint8Array(w.length+N.length);L.set(w),L.set(N,w.length),w=L,S+=N.byteLength}r?.(new DataView(w.buffer),S),yield x?.read().then(F,k)}}.bind(this));yield x?.read().then(F,k),this.unsubscribeAbortSubscription(m);let C=Za(),E={failed:B,requestStartedAt:g,requestEndedAt:C,duration:C-g};return B?(h.error("endRequest",us(E)),h.end(),null):(h.log("endRequest",us(E)),h.end(),w.buffer)}.bind(this));this.fetchByteRangeRepresentation=Ja(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,p;e.indexRange&&(l=e.indexRange.from,p=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(p,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},measureThroughput:!1,...i});if(!c)return null;let d=new DataView(c,r-n,a-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),f=e.indexRange??t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(c,f.from-n,f.to-f.from+1);else{let g=yield this.fetch(e.url,{range:f,measureThroughput:!1});if(!g)return null;m=new DataView(g)}let S=t.parseSegments(m,h,f);return{init:h,dataView:new DataView(c),segments:S}}.bind(this));this.fetchTemplateRepresentation=Ja(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{measureThroughput:!1,...t});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=zr(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:oE(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t,i){let r=await Ke(e,t);if(r.ok)return r;if(i?.ignoreNetworkErrors)return;let a=await r.text(),n=parseInt(a);if(!isNaN(n))switch(n){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:en.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:en.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:en.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:en.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${n})`,category:en.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},gu=s=>{if(!Le(s))throw s};import{isNullable as N0,ValueSubject as lE}from"@vkontakte/videoplayer-shared/es2024";var yi=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 lE(e.initial),this.debounced$=new lE(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ne(`raw_${t}`),this.smoothedSeries$=new Ne(`smoothed_${t}`),this.reportedSeries$=new Ne(`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 r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;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>a||this.smoothed<n)&&(N0(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 vu=class extends yi{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Ft(this.slow,e,this.params.emaAlphaSlow),this.fast=Ft(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var yu=class extends yi{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Id(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ft(this.emaSmoothed,e,this.params.emaAlpha);let i=_y(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Tu=class extends yi{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?Ft(this.smoothed,t,this.params.emaAlpha):t}};var Qt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new vu({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new yu({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new Tu({initial:e,label:"liveEdgeDelay",...t})}};var ls=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)};import{isNullable as F0,ValueSubject as U0}from"@vkontakte/videoplayer-shared/es2024";var tn=class s{constructor(e,t){this.currentRepresentation$=new U0(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(!F0(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,a=r.segments.length,n=r.segments[0].time.from,o=r.segments[a-1].time.to;if(e<n||e>o)continue;let u=r.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,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=s.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=>s.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&it(t.segmentReference))}};var W0=["timeupdate","progress","play","seeked","stalled","waiting"],G0=["timeupdate","progress","loadeddata","playing","seeked"];var Eu=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new dE;this.subscriptionRemovable=new H0;this.representationSubscription=new dE;this.state$=new O("none");this.currentVideoRepresentation$=new ee(void 0);this.currentVideoRepresentationInit$=new ee(void 0);this.currentAudioRepresentation$=new ee(void 0);this.currentVideoSegmentLength$=new ee(0);this.currentAudioSegmentLength$=new ee(0);this.error$=new Gt;this.manifestRequested$=new Gt;this.firstBytesManifest$=new Gt;this.manifestReceived$=new Gt;this.firstBytesRequested$=new Gt;this.firstBytesReceived$=new Gt;this.lastConnectionType$=new ee(void 0);this.lastConnectionReused$=new ee(void 0);this.lastRequestFirstBytes$=new ee(void 0);this.currentLiveTextRepresentation$=new ee(null);this.isLive$=new ee(!1);this.isActiveLive$=new ee(!1);this.isLowLatency$=new ee(!1);this.liveDuration$=new ee(0);this.liveSeekableDuration$=new ee(0);this.liveAvailabilityStartTime$=new ee(0);this.liveStreamStatus$=new ee(void 0);this.bufferLength$=new ee(0);this.liveLatency$=new ee(void 0);this.liveLoadBufferLength$=new ee(0);this.livePositionFromPlayer$=new ee(0);this.currentStallDuration$=new ee(0);this.videoLastDataObtainedTimestamp$=new ee(0);this.fetcherRecoverableError$=new Gt;this.fetcherError$=new Gt;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Gt;this.gapWatchdogActive=!1;this.liveWasInterrupted=!1;this.destroyController=new j;this.initManifest=fp(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ne(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:ct.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=fp(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ct.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Xr(e??"",this.manifestUrlString),this.manifestReceived$.next()}catch(u){let l=Hr(e)??{id:"ManifestParsing",category:ct.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,p)=>!!(this.element?.canPlayType?.(l)&&Ve()?.isTypeSupported?.(`${l}; codecs="${p}"`)||u==="text");if(t.live){this.isLive$.next(!0);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:p,streamIsAlive:c}=t.live,d=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*d),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";if(c||(h=p?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h),c&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let f=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(f).catch(m=>{this.error$.next({id:"updateManifest",category:ct.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:m})})}}let r={text:t.streams.text,video:[],audio:[]},a,n;for(let u of["video","audio"]){let p=t.streams[u].filter(({mime:d,codecs:h})=>i(u,d,h));r[u]=p;let c;if(this.tuning.dash.codecsPrioritizeEnabled){let d=p.map(({codecs:h})=>h);u==="audio"&&(n=es(d),c=n[0]),u==="video"&&(a=Zr(d),this.forceVideoCodec&&(0,hE.default)(a,this.forceVideoCodec)?c=this.forceVideoCodec:c=a[0]),c&&(r[u]=p.filter(({codecs:h})=>hi(h)===c))}else{let d=new Set(p.map(({codecs:h})=>h));c=Jr(d),c&&(r[u]=p.filter(({codecs:h})=>h.startsWith(c)))}if(u==="video"){let d=this.tuning.preferHDR,h=r.video.some(m=>m.hdr),f=r.video.some(m=>!m.hdr);$.display.isHDR&&d&&h?r.video=r.video.filter(m=>m.hdr):f&&(r.video=r.video.filter(m=>!m.hdr))}}let o={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:a,audio:n}),this.tracer.log("updateManifestEnd",sn(o)),o}.bind(this));this.initRepresentations=fp(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",sn({initialVideo:e,initialAudio:t,sourceHls:i})),cs(this.manifest),cs(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=c=>{this.representationSubscription.add(Wt(c,"error").pipe(Iu(d=>!!this.element?.played.length)).subscribe(d=>{this.error$.next({id:"VideoSource",category:ct.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:d})}))};this.source=Ir();let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),ai())if(i){let c=document.createElement("source");r(c),c.type="application/x-mpegurl",c.src=i.url,this.element.appendChild(c)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((c,d)=>[...c,...d.representations],[]);if(this.videoBufferManager=new Xa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],an(t)){let c=this.manifest.streams.audio.reduce((d,h)=>[...d,...h.representations],[]);this.audioBufferManager=new Xa("audio",this.source,c,n),this.bufferManagers.push(this.audioBufferManager)}if(tn.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new tn(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(tr(...G0.map(c=>Wt(this.element,c))).pipe(ps(c=>this.element?de(this.element.buffered,this.element.currentTime*1e3):0),rn(),z0(c=>{c>this.tuning.dash.bufferEmptinessTolerance&&this.stopStallWatchdogSubscription()})).subscribe(this.bufferLength$)),this.representationSubscription.add(tr(Wt(this.element,"ended"),this.forceEnded$).subscribe(()=>{this.stopStallWatchdogSubscription()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(rn()).subscribe(d=>this.liveStreamEndTimestamp=bp())),this.subscription.add(Wt(this.element,"pause").subscribe(()=>{let{liveUpdateInterval:d}=this.tuning.dash;this.livePauseWatchdogSubscription=mp(d).subscribe(h=>{let f=si(this.manifestUrlString,2);this.manifestUrlString=ne(this.manifestUrlString,f+d,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Wt(this.element,"play").subscribe(d=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(ds({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ps(({isActiveLive:d,isLowLatency:h})=>d&&h),rn()).subscribe(d=>{this.isManualDecreasePlaybackInLive()||ls(this.element,1)})),this.representationSubscription.add(ds({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Iu(({bufferLength:d,isActiveLive:h,isLowLatency:f})=>h&&f&&!!d)).subscribe(({bufferLength:d})=>this.liveBuffer.next(d))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(d=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!d)return;let h=this.liveSeekableDuration$.getValue()-d/1e3;this.liveSeekableDuration$.next(Math.max(h,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+d/1e3)})),this.representationSubscription.add(ds({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Iu(({isLive:d})=>d),rn((d,h)=>h.bufferLength<d.bufferLength),ps(({rtt:d,bufferLength:h,segmentServerLatency:f})=>{let m=si(this.manifestUrlString,2);return(d/2+h+f+m)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(ds({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:d,isActiveLive:h,isLowLatency:f})=>{if(!f||!h)return;let m=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,g=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,v=d-m;if(this.isManualDecreasePlaybackInLive())return;let T=1;Math.abs(v)>S&&(T=1+Math.sign(v)*g),ls(this.element,T)})),this.representationSubscription.add(this.bufferLength$.subscribe(d=>{let h=0;if(d){let f=(this.element?.currentTime??0)*1e3;h=Math.min(...this.bufferManagers.map(S=>S.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==h&&this.liveLoadBufferLength$.next(h)}));let c=0;this.representationSubscription.add(ds({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Q0(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:d,bufferLength:h})=>{if(!this.element||this.isUpdatingLive)return;let f=this.element.playbackRate,m=si(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,g=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),v=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,T=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,y=isFinite(d)?d:h,x=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),A=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(A);let R="none";if(x?R="active_low_latency":this.isLowLatency$.getValue()&&A?(this.bufferManagers.forEach(w=>w.proceedLowLatencyLive()),R="active_low_latency"):m!==0&&y<g?R="live_forward_buffering":y<g+T&&(R="live_with_target_offset"),isFinite(d)&&(c=d>c?d:c),R==="live_forward_buffering"||R==="live_with_target_offset"){let w=c-(g+v),B=this.normalizeLiveOffset(Math.trunc(m+w/f)),k=Math.abs(B-m),F=0;!d||k<=this.tuning.dashCmafLive.offsetCalculationError?F=m:B>0&&k>this.tuning.dashCmafLive.offsetCalculationError&&(F=B),this.manifestUrlString=ne(this.manifestUrlString,F,2)}(R==="live_with_target_offset"||R==="live_forward_buffering")&&(c=0,await this.updateLive())},d=>{this.error$.next({id:"updateLive",category:ct.VIDEO_PIPELINE,thrown:d,message:"Failed to update live with subscription"})}))}let u=tr(...this.bufferManagers.map(c=>c.fullyBuffered$)).pipe(ps(()=>this.bufferManagers.every(c=>c.fullyBuffered$.getValue()))),l=tr(...this.bufferManagers.map(c=>c.onLastSegment$)).pipe(ps(()=>this.bufferManagers.some(c=>c.onLastSegment$.getValue()))),p=ds({allBuffersFull:u,someBufferEnded:l}).pipe(rn(),ps(({allBuffersFull:c,someBufferEnded:d})=>c&&d),Iu(c=>c));if(this.representationSubscription.add(tr(this.forceEnded$,p).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(c=>!c.updating))try{this.source?.endOfStream()}catch(c){this.error$.next({id:"EndOfStream",category:ct.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:c})}})),this.representationSubscription.add(tr(...this.bufferManagers.map(c=>c.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"){let c=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(d=>{c&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){d();return}this.error$.next({id:"OpenOfStream",category:ct.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),d()},{once:!0})})}if(!this.isLive$.getValue()){let c=[this.manifest.duration??0,...(0,gp.default)((0,gp.default)([...this.manifest.streams.audio,...this.manifest.streams.video],d=>d.representations),d=>{let h=[];return d.duration&&h.push(d.duration),it(d.segmentReference)&&d.segmentReference.totalSegmentsDurationMs&&h.push(d.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...c)/1e3}this.audioBufferManager&&an(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||this.source?.readyState!=="open")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=mp(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:ct.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new Su({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.firstBytesRequested$.subscribe(this.firstBytesRequested$)),this.subscription.add(this.fetcher.firstBytesReceived$.subscribe(this.firstBytesReceived$)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.liveBuffer=Qt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){cs(this.element),this.updateManifestUrlWithTimeOffset(e),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.updateLiveBuffersFromManifest(this.manifest))}updateManifestUrlWithTimeOffset(e){let t=this.liveStreamStatus$.getValue()!=="active"?bp()-this.liveStreamEndTimestamp:0,i=this.normalizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ne(this.manifestUrlString,i,2)}async updateLiveBuffersFromManifest(e){await this.videoBufferManager?.seekLive(e.streams.video),await this.audioBufferManager?.seekLive(e.streams.audio),this.liveTextManager?.seekLive(e.streams.text)}stopStallWatchdogSubscription(){this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)}initBuffer(){cs(this.element),this.state$.setState("running"),this.subscription.add(tr(...W0.map(e=>Wt(this.element,e)),Wt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ct.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Wt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Wt(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===2&&!this.element.seeking&&De(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{let{keepSilentStallWatchdogWhenNotActive:t}=this.tuning.dashCmafLive,{crashOnStallTimeout:i,crashOnStallTWithoutDataTimeout:r,liveStallReinitInterval:a,stallWatchdogInterval:n}=this.tuning.dash,o=this.isLive$.getValue(),l=this.liveStreamStatus$.getValue()==="active";if(!this.element||this.source?.readyState!=="open")return;let p=this.currentStallDuration$.getValue();p+=n,this.currentStallDuration$.next(p);let c={timeInWaiting:p},d=bp(),h=100,f=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(f);let m=this.audioBufferManager?.lastDataObtainedTimestamp??0,S=this.videoBufferManager?.getForwardBufferDuration()??0,g=this.audioBufferManager?.getForwardBufferDuration()??0,v=S<h&&d-f>r,T=this.audioBufferManager&&g<h&&d-m>r;if((!t||l)&&((v||T)&&p>r||p>=i))throw new Error(`Stall timeout exceeded: ${p} ms`);if(o&&p%a===0){let y=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);!l&&t?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(y),this.updateManifest()):this.seekLive(y).catch(x=>{this.error$.next({id:"stallIntervalCallback",category:ct.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:x})}),c.liveLastOffset=y}else{let y=this.element.currentTime*1e3;this.videoBufferManager?.maintain(y),this.audioBufferManager?.maintain(y),c.position=y}this.tracer.log("stallIntervalCallback",sn(c))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=mp(this.tuning.dash.stallWatchdogInterval).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:ct.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){cs(this.element),cs(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),this.warmUpMediaSourceIfNeeded(i),De(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(cE(this.element)||cE(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",sn({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){an(this.element)&&an(this.source)&&an(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),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}getCodecs(){return this.manifest?.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),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=j0(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normalizeLiveOffset(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=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime},{usePersistentGaps:r}=this.tuning.dash;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let a=this.element.currentTime*1e3,n=[],o=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(r&&l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=a&&l.to+o>a&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n.push(1/0):n.push(l.to));if(n.length){let u=Math.max(...n)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,i={...i,gapEnds:n,jumpTo:u,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",sn(i)))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};import{combine as Y0,map as K0,observeElementSize as X0,Subscription as J0,ValueSubject as Sp,noop as Z0}from"@vkontakte/videoplayer-shared/es2024";var wu=class{constructor(){this.subscription=new J0;this.pipSize$=new Sp(void 0);this.videoSize$=new Sp(void 0);this.elementSize$=new Sp(void 0);this.pictureInPictureWindowRemoveEventListener=Z0}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(X0(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(Y0({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(K0(({videoSize:r,inPip:a,pipSize:n})=>a?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var ir=class{constructor(e){this.subscription=new o_;this.videoState=new O("stopped");this.observableVideo=null;this.droppedFramesManager=new li;this.stallsManager=new qr;this.elementSizeManager=new wu;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new yt;this.audioTrackSwitchHistory=new yt;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),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.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&P(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return t_(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new di(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.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new We(e.source.url),this.params=e,this.video=Pe(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(ce(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 Eu({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;n_(this.observableVideo)&&(this.observableVideo=$e(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:fE.WTF,message:`${i} internal logic error`,thrown:n})},a=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:a}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(vp(c=>!!c.length),bE()).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(on(c=>c.to.state!=="none"),nn());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.currentBuffer$,e.currentNativeBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.manifestRequested$,e.manifestRequested$),a(this.player.firstBytesManifest$,e.firstBytesManifest$),a(this.player.manifestReceived$,e.manifestReceived$),a(this.player.firstBytesRequested$,e.firstBytesRequested$),a(this.player.firstBytesReceived$,e.firstBytesReceived$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(vp(mE),bE()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(on(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),pi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(Re(this.video,t.volume,i.volumeState$,r)),this.subscription.add(Qe(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Ye(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")})),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(),h=this.player.getCodecs();if(i_(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let S of d.audio){m.push(Jd(S));let g=[];for(let v of S.representations){let T=Ha(v);g.push(T),this.audioTracksMap.set(T,{stream:S,representation:v})}this.audioStreamsMap.set(S,g)}this.params.output.availableAudioStreams$.next(m)}let f=[];for(let m of d.video){f.push(Zd(m));let S=[];for(let g of m.representations){let v=mi({...g,streamId:m.id});v&&(S.push(v),this.videoTracksMap.set(v,{stream:m,representation:g}))}this.videoStreamsMap.set(m,S)}this.params.output.availableVideoStreams$.next(f);for(let m of d.text)for(let S of m.representations){let g=FI(m,S);this.textTracksMap.set(g,{stream:m,representation:S})}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),h?.video&&this.params.output.availableVideoCodecs$.next(h.video),h?.audio&&this.params.output.availableAudioCodecs$.next(h.audio),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())},r));let o=un(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,a_(this.video,"progress")).pipe(vp(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe(u_(u))),this.subscription.add(o.subscribe(async()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[f,m]=h,S=[...this.videoTracksMap.keys()].find(v=>this.videoTracksMap.get(v)?.representation.id===f.id);mE(S)&&(this.stallsManager.lastVideoTrackSelected=S);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")await this.player.initRepresentations(f.id,m?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",f.id),m){let v=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",m.id,v)}},r)),this.subscription.add(r_({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:un(xu([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(on(c=>c.to)))}).pipe(on(({videoState:c,autoVideoTrackState:d})=>c.to!=="stopped"&&d),nn()).subscribe(c=>this.player.setSmartRepresentationSwitch(c))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(nn()).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:f}]=d,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Zd(f));let S=this.player.calculateDurationFromSegments();S&&this.params.output.duration$.next(S/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(nn()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:S}])=>S.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:f}]=d,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(Jd(f))},r)),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)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(on(({to:c})=>c==="ready"),nn());this.subscription.add(un(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,xu(["init"])).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(un(l,this.player.state$.stateChangeEnded$,xu(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let p=un(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,xu(["init"])).pipe(s_(0));this.subscription.add(p.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Qi:zi,t=this.params.tuning.useNewAutoSelectVideoTrack?Fr:Nr,i=this.params.tuning.useNewAutoSelectVideoTrack?ut:Or,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,u=[...this.videoTracksMap.keys()].find(({id:w})=>w===o),l=a.currentVideoTrack$.getValue(),p=r.videoStream.getState()??(u&&this.videoTracksMap.get(u)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!p)return;let c=[...this.videoStreamsMap.keys()].find(({id:w})=>w===p.id),d=c&&this.videoStreamsMap.get(c);if(!d)return;let h=de(this.video.buffered,this.video.currentTime*1e3),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(f,m||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),v=[...this.audioStreamsMap.keys()].find(({id:w})=>w===g?.id)??this.audioStreamsMap.keys().next().value,T=0;if(v){if(u&&!n){let w=e(u,d,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}if(l){let w=e(l,d,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}}let y=u;(n||!y)&&(y=i(d,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:T,forwardBufferHealth:S,current:l,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}));let x=v&&t(y,d,this.audioStreamsMap.get(v)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),A=this.videoTracksMap.get(y)?.representation,R=x&&this.audioTracksMap.get(x)?.representation;if(A&&R)return[A,R];if(A&&!R&&this.audioTracksMap.size===0)return[A,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:fE.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Ae(this.video),this.tracer.end()}};var ln=class extends ir{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)}};import{combine as yp,merge as gE,filter as SE,filterChanged as vE,isNullable as Tp,map as yE,ValueSubject as Ip,isNonNullable as l_}from"@vkontakte/videoplayer-shared/es2024";var cn=class extends ir{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:a,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let o=new Ip(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(vE()).subscribe(u=>{let l=i.position$.getValue(),p=i.volume$.getValue(),c=!p.volume||p.muted;!u&&!l&&c?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(a.isLowLatency.stateChangeEnded$.pipe(yE(u=>u.to)).subscribe(this.player.isLowLatency$)).add(yp({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(yE(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u*1e3+l+t:void 0)).subscribe(i.liveTime$)).add(yp({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:gE(r.playbackRateState$,new Ip(1))}).pipe(SE(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let p=i.liveBufferTime$.getValue(),c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||l<1-d||this.video.paused||Tp(p)||(t=u-p)})).add(yp({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:gE(r.playbackRateState$,new Ip(1))}).pipe(vE((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:p})=>{let c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&p>=1-d||Tp(u)||Tp(l))return;let h=-1*(l-u-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let l=UI(u);this.params.output.availableTextTracks$.next([l])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe(SE(u=>l_(u))).subscribe(u=>i.isLiveEnded$.next(u==="unpublished"&&i.position$.getValue()===0)))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as __,assertNonNullable as O_,combine as N_,debounce as F_,ErrorCategory as _E,filter as Op,filterChanged as yn,fromEvent as U_,isNonNullable as OE,isNullable as q_,map as Tn,merge as In,observableFrom as Vu,once as NE,Subscription as j_}from"@vkontakte/videoplayer-shared/es2024";var VE=D(ke(),1),Vp=D(Wi(),1);import{abortable as Lp,assertNonNullable as ms,combine as bs,ErrorCategory as Et,filter as Du,filterChanged as gn,flattenObject as Sn,fromEvent as Dt,getTraceSubscriptionMethod as k_,interval as Dp,isNonNullable as vn,isNullable as BE,map as gs,merge as or,now as Bp,Subject as Yt,Subscription as Cp,SubscriptionRemovable as P_,tap as A_,throttle as CE,ValueSubject as te}from"@vkontakte/videoplayer-shared/es2024";var Ru=D(ke(),1),nr=D(Ge(),1),$u=D(Wi(),1);var $E=D(Ro(),1);import{assertNever as c_,ErrorCategory as TE,Subject as IE}from"@vkontakte/videoplayer-shared/es2024";var d_=18,EE=!1;try{EE=$.browser.isSafari&&!!$.browser.safariVersion&&$.browser.safariVersion<=d_}catch(s){console.error(s)}var Ep=class{constructor(e,t=!1){this.bufferFull$=new IE;this.error$=new IE;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:TE.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};EE&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,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)&&!this.abortRequested)return;let e=this.isAbortFixEnabled?this.queue[0]: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(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:TE.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),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:c_(t)}}},wE=Ep;import{abortable as Ti,assertNonNullable as He,ErrorCategory as sr,fromEvent as Ap,getExponentialDelay as Rp,isHigher as b_,isNonNullable as Ii,isNullable as he,now as Au,once as g_,Subject as S_,Subscription as v_,ValueSubject as ar}from"@vkontakte/videoplayer-shared/es2024";var wp=D(Ge(),1);import{videoSizeToQuality as p_,throttleFn as h_}from"@vkontakte/videoplayer-shared/es2024";var dn=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{let o=(a?$t(a):void 0)??p_({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},xE=({id:s,bitrate:e})=>({id:s,bitrate:e}),kE=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),PE=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),xp=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,wp.default)(i.split("."),0),isDefault:r}),kp=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,wp.default)(r.split("."),0)}),Pp=s=>"url"in s,rt=s=>s.type==="template";var AE=s=>{s.sort((t,i)=>t.from-i.from);let e=[s[0]];for(let t=1;t<s.length;t++){let{from:i,to:r}=s[t],a=e[e.length-1];a.to>=i?a.to=Math.max(a.to,r):e.push(s[t])}return e},rr=(s,e)=>{for(let t of s)if(e(t))return t;return null},RE=s=>{let e=!1,t=h_(()=>{e=!0},s);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as f_,Subscription as m_}from"@vkontakte/videoplayer-shared/es2024";var ku=s=>{let e=[];for(let t=0;t<s.length;t++){let i=Math.floor(s.start(t)*1e3),r=Math.ceil(s.end(t)*1e3);e.push(i,r)}return e};var Pu=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new m_;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(f_(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!V(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=ku(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],a=e[i+1],n=t[i],o=t[i+1];if(n>r||o<a)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var pn=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new ar(0);this.currentLowLatencySegmentLength$=new ar(0);this.currentSegmentLength$=new ar(0);this.onLastSegment$=new ar(!1);this.fullyBuffered$=new ar(!1);this.playingRepresentation$=new ar(void 0);this.playingRepresentationInit$=new ar(void 0);this.error$=new S_;this.gaps=[];this.subscription=new v_;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new j;this.switchAbortController=new j;this.destroyAbortController=new j;this.useSmartRepresentationSwitch=!1;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.sourceBufferBufferedDiff=null;this.startWith=Ti(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);He(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new wE(this.sourceBuffer,this.tuning.dash.useAbortMSEFix),this.sourceBufferBufferedDiff=new Pu(this.mediaSource,this.sourceBuffer),this.subscription.add(Ap(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(Ap(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:sr.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!V(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,ns(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=de(this.sourceBuffer.buffered,o),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<p).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),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),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);He(i,"No init buffer for starting representation"),He(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))}.bind(this));this.switchTo=Ti(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);He(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(he(a)||he(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),He(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();Ii(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Ti(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);He(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(he(a)||he(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),He(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();Ii(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=Ti(this.destroyAbortController.signal,async function*(e){let t=(0,$u.default)(e,u=>u.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let u of this.representations.keys()){let l=t.find(d=>d.id===u);l&&this.representations.set(u,l);let p=this.representations.get(u);if(!p||!rt(p.segmentReference)){this.isSeekingLive=!1;return}let c=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);He(r,`Representation not found by id ${i}`);let a=this.segments.get(i);He(a,"No segments for starting representation");let n=this.initData.get(i);if(He(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(p=>[p.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(p=>[p.id,p])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new j,Ti(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);He(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(he(o)||he(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),He(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();Ii(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))}warmUpMediaSource(){!he(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new j,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(he(e)||he(this.downloadingRepresentationId)||he(this.playingRepresentationId)||he(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||Ii(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),a=this.segments.get(this.playingRepresentationId);if(He(t,`No such representation ${this.downloadingRepresentationId}`),He(i,`No such representation ${this.playingRepresentationId}`),he(r)||he(a))return;let n=r.find(d=>e>=d.time.from&&e<d.time.to);Ii(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next(n?.time.to-n.time.from);let o=e,u=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=this.getForwardBufferDuration(e),h=dn(i),f=dn(t),m=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&Ii(h)&&Ii(f)&&b_(h.quality,f.quality),S=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(m||S?o+=Math.min(d,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=n.time.to-e+u&&(o=n?n.time.to+u:-1/0),this.tuning.dash.useNewRepresentationSwitch){let v=[...this.segments.entries()].map(([T,y])=>{let x=y.find(A=>e>=A.time.from&&e<A.time.to);return{representationId:T,status:x?.status}}).find(T=>T.status==="fed")?.representationId;v&&(this.playingRepresentationId=v,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&ns(this.sourceBuffer.buffered)>=this.bufferLimit){let d=de(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let p=null;if(!this.activeSegments.size&&(p=this.selectForwardBufferSegments(r,t.segmentReference.type,o),p?.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,Ru.default)(p,n))d="high";else{let h=(0,nr.default)(p,0);h&&h.time.from-n.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(p,t,d).catch(h=>{this.handleAsyncError(h,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!p?.length&&de(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let c=(0,nr.default)(r,-1);!this.isLive&&c&&(this.fullyBuffered$.next(c.time.to-e-de(this.sourceBuffer.buffered,e)<u),this.onLastSegment$.next(e-c.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r,persistent:!0}),i=a.time.to;Ii(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind];if(!t)return;let i=(0,$u.default)(t,a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){if(!e||[...this.segments.values()].every(i=>!i.length))return;let t=(0,$u.default)(e.streams[this.kind],i=>i.representations)??[];for(let i of t){if(!i||!rt(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),a=100,n=this.segments.get(i.id)??[],o=(0,nr.default)(n,-1)?.time.to??0,u=r?.findIndex(l=>o>=l.time.from+a&&o<=l.time.to+a);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(u+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;He(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!rt(r))return;let a=this.segments.get(i.id);if(!a)continue;let n=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=tt(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(a=>a.time.from<=e&&a.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.sourceBufferBufferedDiff?.destroy(),this.gapDetectionIdleCallback&&qe&&qe(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&qe&&qe(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)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.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),a=e.findIndex(({status:d,time:{from:h,to:f}},m)=>{let S=h<=i&&f>=i,g=h>i||S||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&h<=i+v||r<v&&f-h>=v||f<=i+v;return(d==="none"||d==="partially_ejected"&&g&&T&&this.sourceBuffer&&V(this.mediaSource,this.sourceBuffer)&&!(De(this.sourceBuffer.buffered,h)&&De(this.sourceBuffer.buffered,f)))&&g&&T});if(a===-1)return null;if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,l=[],p=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<n.length&&(o<=p||u<=c);d++){let h=n[d];if(o+=h.byte.to+1-h.byte.from,u+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){rt(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 r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Ti(o,async function*(){let p=Rp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,p))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let p=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=Au(),!p)return;let c=new DataView(p),d=lt(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(c,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=d.getServerLatencyTimestamps(c);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(p){this.abortActiveSegments([e]),Le(p)||(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())rt(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:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Ti(n,async function*(){let u=Rp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Ap(window,"online").pipe(g_()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=Au(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Le(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(rt(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,nr.default)(e,0).byte.from,to:(0,nr.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:async(o,u)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=Au(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:sr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!rt(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 r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,p)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=Au();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:p,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:sr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Ru.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!V(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),p=lt(n.mime).parseFeedableSegmentChunk(l,this.isLive);p?.byteLength&&(u.status="partially_fed",o.feedingBytes+=p.byteLength,await this.sourceBufferTaskQueue.append(p),o.fedBytes+=p.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!V(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){if(u.representationId!==t)continue;if(a.aborted){await n();continue}let{segment:l}=u,p=l.byte.from-i,c=l.byte.to-i,d=c-p+1,h=p<r,f=c<=r;if(h){if(l.status==="downloading"&&f){l.status="downloaded";let m=new DataView(e.buffer,e.byteOffset+p,d);await this.sourceBufferTaskQueue.append(m,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(d,r-p),u.loadedBytes>u.feedingBytes)){let m=new DataView(e.buffer,e.byteOffset+p+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===d?m:lt(o.mime).parseFeedableSegmentChunk(m);S?.byteLength&&(l.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,a)&&!a.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===d&&this.onSegmentFullyAppended(u,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!(he(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer))){!this.isLive&&$.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(De(this.sourceBuffer.buffered,e.segment.time.from,100)&&De(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:sr.VIDEO_PIPELINE,message:"Browser 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",Pp(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let a of r)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")}this.isActiveLowLatency()&&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[r,a]of this.initData.entries()){let n=a instanceof Promise;t||=n,a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Mt(()=>(0,$E.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Ti(this.destroyAbortController.signal,async function*(){let o=Rp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,lt(e.mime),r)).then(o=>{if(!o)return;let{init:u,dataView:l,segments:p}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let d=p;this.isLive&&rt(e.segmentReference)&&(d=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,d),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:sr.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||!V(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||he(e))return!1;this.checkEjectedSegments();let r=[],a=0,n=o=>{if(a>=t)return;r.push({...o.time});let u=Pp(o)?o.size??0:o.byte.to-o.byte.from;a+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,p=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||p)&&u.status==="fed"&&n(u)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let u=this.sourceBuffer.buffered.start(o)*1e3,l=this.sourceBuffer.buffered.end(o)*1e3,p=0;for(let c of this.segments.values())for(let d of c)(0,Ru.default)(["none","partially_ejected"],d.status)&&Math.round(d.time.from)<=Math.round(u)&&Math.round(d.time.to)>=Math.round(l)&&p++;if(p===this.segments.size){let c={time:{from:u,to:l},url:"",status:"none"};n(c)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let l of u)l.time.from>=e+o&&l.status==="fed"&&n(l)}return r.length?(r=AE(r),(await Promise.all(r.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,l)=>u||l,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getBufferedTo(){return!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||he(e)?0:de(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let a=0;a<i.length;a++){let n=i.start(a)*1e3,o=i.end(a)*1e3;if(!(o<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&o>=t.time.to){r=void 0;break}o>t.time.from&&o<t.time.to&&(r.from=o),n<t.time.to&&n>t.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.gaps=this.gaps.filter(r=>{if(r.persistent)return!0;let a=Math.round(r.from),n=Math.round(r.to);for(let o=0;o<i.length;o++)if(a>=Math.round(i.start(o)*1e3)&&n<=Math.round(i.end(o)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=Mt(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:sr.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(he(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||he(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=ku(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=!1,l=0;for(let p=0;p<e.length;p+=2){let c=e[p],d=e[p+1];u||(u=c-t<=n&&d+t>=o),(n>=c&&n<d-t||o>c+t&&o<=d)&&(l+=1)}u||(l===1?r.status="partially_ejected":this.gaps.some(p=>p.from===r.time.from||p.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:sr.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,nr.default)(e,-1)?.time.to:0)||0}};import{abortable as hn,assertNever as ME,fromEvent as LE,merge as y_,now as fn,Subject as hs,ValueSubject as $p,flattenObject as fs,ErrorCategory as mn,SubscriptionRemovable as T_}from"@vkontakte/videoplayer-shared/es2024";var Lu=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.manifestRequested$=new hs;this.firstBytesManifest$=new hs;this.firstBytesRequested$=new hs;this.firstBytesReceived$=new hs;this.lastConnectionType$=new $p(void 0);this.lastConnectionReused$=new $p(void 0);this.lastRequestFirstBytes$=new $p(void 0);this.recoverableError$=new hs;this.error$=new hs;this.abortAllController=new j;this.subscription=new T_;this.fetchManifest=hn(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Tt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Qr(i)),this.manifestRequested$.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Mu);return r?(t.log("success",fs({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),this.firstBytesManifest$.next(),r.text()):(t.error("error",fs({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=hn(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:l=!1}={}){let p=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(p,location.href);E.searchParams.append("bytes",`${i.from}-${i.to}`),p=E.toString();break}default:ME(t)}this.requestQuic&&(p=Tt(p));let h=this.abortAllController.signal,f;if(n){let E=new j;if(f=y_(LE(this.abortAllController.signal,"abort"),LE(n,"abort")).subscribe(()=>{try{E.abort()}catch(I){Mu(I)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{E.abort()}catch(I){Mu(I)}h=E.signal}let m=0,S=fn();d.log("startRequest",fs({url:p,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:S})),this.firstBytesRequested$.next();let g=yield this.doFetch(p,{priority:a,headers:c,signal:h}),v=fn();if(!g)return d.error("error",{message:"No response in request"}),d.end(),this.unsubscribeAbortSubscription(f),null;if(this.throughputEstimator?.addRawRtt(v-S),!g.ok||!g.body){this.unsubscribeAbortSubscription(f);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),!r&&!o){this.unsubscribeAbortSubscription(f);let E=fn(),I={requestStartedAt:S,requestEndedAt:E,duration:E-S};return d.log("endRequest",fs(I)),d.end(),g.arrayBuffer()}let T=g.body;if(o){let E;[T,E]=g.body.tee(),this.throughputEstimator?.trackStream(E,u)}let y=T.getReader(),x,A=parseInt(g.headers.get("content-length")??"",10);Number.isFinite(A)&&(x=A),!x&&i&&(x=i.to-i.from+1);let R=x?new Uint8Array(x):new Uint8Array(0),w=!1,B=E=>{this.unsubscribeAbortSubscription(f),w=!0,Mu(E)},k=hn(h,async function*({done:E,value:I}){if(m===0&&(this.lastRequestFirstBytes$.next(fn()-S),this.firstBytesReceived$.next()),h.aborted){this.unsubscribeAbortSubscription(f);return}if(!E&&I){if(l&&x)R.set(I,m),m+=I.byteLength;else{let N=new Uint8Array(R.length+I.length);N.set(R),N.set(I,R.length),R=N,m+=I.byteLength}r?.(new DataView(R.buffer),m),yield y?.read().then(k,B)}}.bind(this));yield y?.read().then(k,B),this.unsubscribeAbortSubscription(f);let F=fn(),C={failed:w,requestStartedAt:S,requestEndedAt:F,duration:F-S};return w?(d.error("endRequest",fs(C)),d.end(),null):(d.log("endRequest",fs(C)),d.end(),R.buffer)}.bind(this));this.fetchByteRangeRepresentation=hn(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,p;e.indexRange&&(l=e.indexRange.from,p=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(p,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let d=new DataView(c,r-n,a-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),f=e.indexRange??t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(c,f.from-n,f.to-f.from+1);else{let g=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!g)return null;m=new DataView(g)}let S=t.parseSegments(m,h,f);return{init:h,dataView:new DataView(c),segments:S}}.bind(this));this.fetchTemplateRepresentation=hn(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=zr(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:ME(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await Ke(e,t);if(i.ok)return i;let r=await i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:mn.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:mn.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:mn.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:mn.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:mn.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Mu=s=>{if(!Le(s))throw s};import{isNullable as I_,ValueSubject as E_}from"@vkontakte/videoplayer-shared/es2024";var bn=class s{constructor(e,t){this.currentRepresentation$=new E_(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(!I_(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,a=r.segments.length,n=r.segments[0].time.from,o=r.segments[a-1].time.to;if(e<n||e>o)continue;let u=r.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,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=s.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=>s.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&rt(t.segmentReference))}};var R_=["progress","play","seeked","stalled","waiting"],$_=["timeupdate","progress","loadeddata","playing","seeked"];var Bu=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new Cp;this.subscriptionRemovable=new P_;this.representationSubscription=new Cp;this.state$=new O("none");this.currentVideoRepresentation$=new te(void 0);this.currentVideoRepresentationInit$=new te(void 0);this.currentAudioRepresentation$=new te(void 0);this.currentVideoSegmentLength$=new te(0);this.currentAudioSegmentLength$=new te(0);this.error$=new Yt;this.manifestRequested$=new Yt;this.firstBytesManifest$=new Yt;this.manifestReceived$=new Yt;this.firstBytesRequested$=new Yt;this.firstBytesReceived$=new Yt;this.lastConnectionType$=new te(void 0);this.lastConnectionReused$=new te(void 0);this.lastRequestFirstBytes$=new te(void 0);this.currentLiveTextRepresentation$=new te(null);this.isLive$=new te(!1);this.isActiveLive$=new te(!1);this.isLowLatency$=new te(!1);this.liveDuration$=new te(0);this.liveSeekableDuration$=new te(0);this.liveAvailabilityStartTime$=new te(0);this.liveStreamStatus$=new te(void 0);this.bufferLength$=new te(0);this.liveLatency$=new te(void 0);this.liveLoadBufferLength$=new te(0);this.livePositionFromPlayer$=new te(0);this.currentStallDuration$=new te(0);this.videoLastDataObtainedTimestamp$=new te(0);this.fetcherRecoverableError$=new Yt;this.fetcherError$=new Yt;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Yt;this.gapWatchdogActive=!1;this.destroyController=new j;this.initManifest=Lp(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ne(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:Et.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Lp(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Et.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Xr(e??"",this.manifestUrlString),this.manifestReceived$.next()}catch(u){let l=Hr(e)??{id:"ManifestParsing",category:Et.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,p)=>!!(this.element?.canPlayType?.(l)&&Ve()?.isTypeSupported?.(`${l}; codecs="${p}"`)||u==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:p,streamIsAlive:c}=t.live,d=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*d),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";c||(h=p?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h)}let r={text:t.streams.text,video:[],audio:[]},a,n;for(let u of["video","audio"]){let p=t.streams[u].filter(({mime:d,codecs:h})=>i(u,d,h));r[u]=p;let c;if(this.tuning.dash.codecsPrioritizeEnabled){let d=p.map(({codecs:h})=>h);u==="audio"&&(n=es(d),c=n[0]),u==="video"&&(a=Zr(d),this.forceVideoCodec&&(0,VE.default)(a,this.forceVideoCodec)?c=this.forceVideoCodec:c=a[0]),c&&(r[u]=p.filter(({codecs:h})=>hi(h)===c))}else{let d=new Set(p.map(({codecs:h})=>h));c=Jr(d),c&&(r[u]=p.filter(({codecs:h})=>h.startsWith(c)))}if(u==="video"){let d=this.tuning.preferHDR,h=r.video.some(m=>m.hdr),f=r.video.some(m=>!m.hdr);$.display.isHDR&&d&&h?r.video=r.video.filter(m=>m.hdr):f&&(r.video=r.video.filter(m=>!m.hdr))}}let o={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:a,audio:n}),this.tracer.log("updateManifestEnd",Sn(o)),o}.bind(this));this.initRepresentations=Lp(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",Sn({initialVideo:e,initialAudio:t,sourceHls:i})),ms(this.manifest),ms(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new Cp,this.state$.startTransitionTo("representations_ready");let r=d=>{this.representationSubscription.add(Dt(d,"error").pipe(Du(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:Et.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=Ir();let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),ai())if(i){let d=document.createElement("source");r(d),d.type="application/x-mpegurl",d.src=i.url,this.element.appendChild(d)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((d,h)=>[...d,...h.representations],[]);if(this.videoBufferManager=new pn("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],vn(t)){let d=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new pn("audio",this.source,d,n),this.bufferManagers.push(this.audioBufferManager)}bn.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new bn(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(or(...$_.map(d=>Dt(this.element,d))).pipe(gs(d=>this.element?de(this.element.buffered,this.element.currentTime*1e3):0),gn(),A_(d=>{d>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(or(Dt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(gn()).subscribe(h=>this.liveStreamEndTimestamp=Bp())),this.subscription.add(Dt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Dp(1e3).subscribe(h=>{let f=si(this.manifestUrlString,2);this.manifestUrlString=ne(this.manifestUrlString,f+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Dt(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(bs({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(gs(({isActiveLive:h,isLowLatency:f})=>h&&f),gn()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||ls(this.element,1)})),this.representationSubscription.add(bs({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Du(({bufferLength:h,isActiveLive:f,isLowLatency:m})=>f&&m&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let f=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(f,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(bs({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Du(({isLive:h})=>h),gn((h,f)=>f.bufferLength<h.bufferLength),gs(({rtt:h,bufferLength:f,segmentServerLatency:m})=>{let S=si(this.manifestUrlString,2);return(h/2+f+m+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(bs({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:f,isLowLatency:m})=>{if(!m||!f)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=h-S;if(this.isManualDecreasePlaybackInLive())return;let y=1;Math.abs(T)>g&&(y=1+Math.sign(T)*v),ls(this.element,y)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let f=0;if(h){let m=(this.element?.currentTime??0)*1e3;f=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??m))-m}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let d=0;this.representationSubscription.add(bs({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(CE(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(!this.element||this.isUpdatingLive)return;let m=this.element.playbackRate,S=si(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*m),T=this.tuning.dashCmafLive.normalizedActualBufferOffset*m,y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*m,x=isFinite(h)?h:f,A=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),R=g<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(R);let w="none";if(A?w="active_low_latency":this.isLowLatency$.getValue()&&R?(this.bufferManagers.forEach(B=>B.proceedLowLatencyLive()),w="active_low_latency"):S!==0&&x<v?w="live_forward_buffering":x<v+y&&(w="live_with_target_offset"),isFinite(h)&&(d=h>d?h:d),w==="live_forward_buffering"||w==="live_with_target_offset"){let B=d-(v+T),k=this.normolizeLiveOffset(Math.trunc(S+B/m)),F=Math.abs(k-S),C=0;!h||F<=this.tuning.dashCmafLive.offsetCalculationError?C=S:k>0&&F>this.tuning.dashCmafLive.offsetCalculationError&&(C=k),this.manifestUrlString=ne(this.manifestUrlString,C,2)}(w==="live_with_target_offset"||w==="live_forward_buffering")&&(d=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:Et.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=or(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe(gs(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),p=or(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe(gs(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue()))),c=bs({allBuffersFull:l,someBufferEnded:p}).pipe(gn(),gs(({allBuffersFull:d,someBufferEnded:h})=>d&&h),Du(d=>d));if(this.representationSubscription.add(or(this.forceEnded$,c).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{this.source?.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:Et.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add(or(...this.bufferManagers.map(d=>d.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"){let d=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{d&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.error$.next({id:"OpenOfStream",category:Et.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let d=[this.manifest.duration??0,...(0,Vp.default)((0,Vp.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),rt(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...d)/1e3}this.audioBufferManager&&vn(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||this.source?.readyState!=="open")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=Dp(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Et.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.forceVideoCodec=e.forceVideoCodec,this.fetcher=new Lu({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.firstBytesRequested$.subscribe(this.firstBytesRequested$)),this.subscription.add(this.fetcher.firstBytesReceived$.subscribe(this.firstBytesReceived$)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.liveBuffer=Qt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){ms(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Bp()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ne(this.manifestUrlString,i,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(){ms(this.element),this.state$.setState("running");let e=Dt(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(CE(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(or(...R_.map(t=>Dt(this.element,t)),Dt(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:Et.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(Dt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Dt(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&De(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{if(!this.element||this.source?.readyState!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},a=Bp(),n=100,o=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(o);let u=this.audioBufferManager?.lastDataObtainedTimestamp??0,l=this.videoBufferManager?.getForwardBufferDuration()??0,p=this.audioBufferManager?.getForwardBufferDuration()??0,c=l<n&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&p<n&&a-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||d)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let h=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(h).catch(f=>{this.error$.next({id:"stallIntervalCallback",category:Et.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:f})}),r.liveLastOffset=h}else{let h=this.element.currentTime*1e3;this.videoBufferManager?.maintain(h),this.audioBufferManager?.maintain(h),r.position=h}this.tracer.log("stallIntervalCallback",Sn(r))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=Dp(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:Et.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){ms(this.element),ms(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),this.warmUpMediaSourceIfNeeded(i),De(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(BE(this.element)||BE(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Sn({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){vn(this.element)&&vn(this.source)&&vn(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),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}getCodecs(){return this.manifest?.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),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=k_(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}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.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let a=this.element.currentTime*1e3,n=null,o=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=a&&l.to+o>a&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n=1/0:(n===null||l.to>n)&&(n=l.to));if(n!==null){let u=n+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,this.tracer.log("jumpGap",Sn({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};import{combine as M_,map as L_,observeElementSize as D_,Subscription as B_,ValueSubject as _p,noop as C_}from"@vkontakte/videoplayer-shared/es2024";var Cu=class{constructor(){this.subscription=new B_;this.pipSize$=new _p(void 0);this.videoSize$=new _p(void 0);this.elementSize$=new _p(void 0);this.pictureInPictureWindowRemoveEventListener=C_}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(D_(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(M_({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(L_(({videoSize:r,inPip:a,pipSize:n})=>a?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var ur=class{constructor(e){this.subscription=new j_;this.videoState=new O("stopped");this.observableVideo=null;this.droppedFramesManager=new li;this.stallsManager=new qr;this.elementSizeManager=new Cu;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new yt;this.audioTrackSwitchHistory=new yt;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),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.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&P(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return __(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new di(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.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new We(e.source.url),this.params=e,this.video=Pe(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(ce(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 Bu({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;q_(this.observableVideo)&&(this.observableVideo=$e(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:_E.WTF,message:`${i} internal logic error`,thrown:n})},a=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:a}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Op(c=>!!c.length),NE()).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(Tn(c=>c.to.state!=="none"),yn());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.currentBuffer$,e.currentNativeBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.manifestRequested$,e.manifestRequested$),a(this.player.firstBytesManifest$,e.firstBytesManifest$),a(this.player.manifestReceived$,e.manifestReceived$),a(this.player.firstBytesRequested$,e.firstBytesRequested$),a(this.player.firstBytesReceived$,e.firstBytesReceived$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(Op(OE),NE()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(Tn(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(Re(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Qe(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Ye(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")})),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(),h=this.player.getCodecs();if(O_(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let S of d.audio){m.push(xp(S));let g=[];for(let v of S.representations){let T=xE(v);g.push(T),this.audioTracksMap.set(T,{stream:S,representation:v})}this.audioStreamsMap.set(S,g)}this.params.output.availableAudioStreams$.next(m)}let f=[];for(let m of d.video){f.push(kp(m));let S=[];for(let g of m.representations){let v=dn({...g,streamId:m.id});v&&(S.push(v),this.videoTracksMap.set(v,{stream:m,representation:g}))}this.videoStreamsMap.set(m,S)}this.params.output.availableVideoStreams$.next(f);for(let m of d.text)for(let S of m.representations){let g=kE(m,S);this.textTracksMap.set(g,{stream:m,representation:S})}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),h?.video&&this.params.output.availableVideoCodecs$.next(h.video),h?.audio&&this.params.output.availableAudioCodecs$.next(h.audio),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())},r));let{vktvAbrThrottle:o}=this.params.tuning.dash,u=o&&RE(o)||null;this.subscription.add(In(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,U_(this.video,"progress")).pipe(Op(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||d||c==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:h,audio:f}=this.selectedRepresentations;if(!h)return;let m=rr(this.videoTracksMap.keys(),g=>this.videoTracksMap.get(g)?.representation.id===h.id);OE(m)&&(this.stallsManager.lastVideoTrackSelected=m);let S=this.params.desiredState.autoVideoTrackLimits.getTransition();if(S&&this.params.output.autoVideoTrackLimits$.next(S.to),c==="manifest_ready")await this.player.initRepresentations(h.id,f?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",h.id),f){let g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",f.id,g)}},r)),this.subscription.add(N_({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:In(Vu([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(Tn(c=>c.to)))}).pipe(Tn(({videoState:c,autoVideoTrackState:d})=>c.to!=="stopped"&&d),yn()).subscribe(c=>this.player.setSmartRepresentationSwitch(c))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(yn()).subscribe(c=>{let d=rr(this.videoTracksMap.entries(),([,{representation:g}])=>g.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:f}]=d,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(kp(f));let S=this.player.calculateDurationFromSegments();S&&this.params.output.duration$.next(S/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(yn()).subscribe(c=>{let d=rr(this.audioTracksMap.entries(),([,{representation:S}])=>S.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:f}]=d,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(xp(f))},r)),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)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(Tn(({to:c})=>c==="ready"),yn());this.subscription.add(In(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Vu(["init"])).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(In(l,this.player.state$.stateChangeEnded$,Vu(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let p=In(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Vu(["init"])).pipe(F_(0));this.subscription.add(p.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Qi:zi,t=this.params.tuning.useNewAutoSelectVideoTrack?Fr:Nr,i=this.params.tuning.useNewAutoSelectVideoTrack?ut:Or,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,u=rr(this.videoTracksMap.keys(),w=>w.id===o),l=a.currentVideoTrack$.getValue(),p=r.videoStream.getState()??(u&&this.videoTracksMap.get(u)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!p)return;let c=rr(this.videoStreamsMap.keys(),w=>w.id===p.id),d=c&&this.videoStreamsMap.get(c);if(!d)return;let h=de(this.video.buffered,this.video.currentTime*1e3),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(f,m||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),v=g?.id&&rr(this.audioStreamsMap.keys(),w=>w.id===g.id)||this.audioStreamsMap.keys().next().value,T=0;if(v){if(u&&!n){let w=e(u,d,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}if(l){let w=e(l,d,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}}let y=u;(n||!y)&&(y=i(d,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:T,forwardBufferHealth:S,current:l,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}));let x=v&&t(y,d,this.audioStreamsMap.get(v)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),A=this.videoTracksMap.get(y)?.representation,R=x&&this.audioTracksMap.get(x)?.representation;A&&R?(this.selectedRepresentations.video=A,this.selectedRepresentations.audio=R):A&&!R&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=A,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_E.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Ae(this.video),this.tracer.end()}};var En=class extends ur{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)}};import{combine as Np,merge as FE,filter as UE,filterChanged as qE,isNullable as Fp,map as jE,ValueSubject as Up,isNonNullable as H_}from"@vkontakte/videoplayer-shared/es2024";var wn=class extends ur{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:a,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let o=new Up(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(qE()).subscribe(u=>{let l=i.position$.getValue(),p=i.volume$.getValue(),c=!p.volume||p.muted;!u&&!l&&c?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(a.isLowLatency.stateChangeEnded$.pipe(jE(u=>u.to)).subscribe(this.player.isLowLatency$)).add(Np({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(jE(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(UE(u=>H_(u))).subscribe(u=>i.isLiveEnded$.next(u!=="active"&&i.position$.getValue()===0))).add(Np({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:FE(r.playbackRateState$,new Up(1))}).pipe(UE(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let p=i.liveBufferTime$.getValue(),c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||l<1-d||this.video.paused||Fp(p)||(t=u-p)})).add(Np({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:FE(r.playbackRateState$,new Up(1))}).pipe(qE((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:p})=>{let c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&p>=1-d||Fp(u)||Fp(l))return;let h=-1*(l-u-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let l=PE(u);this.params.output.availableTextTracks$.next([l])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var HE="X-Playback-Duration",qp=async s=>{let e=await Ke(s),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(HE)?parseInt(e.headers.get(HE),10):void 0};import{assertNever as tO,combine as iO,debounce as rO,ErrorCategory as Nu,filter as sO,filterChanged as aO,isNonNullable as WE,isNullable as Fu,map as GE,merge as nO,observableFrom as oO,Subscription as uO,ValueSubject as zp,VideoQuality as lO}from"@vkontakte/videoplayer-shared/es2024";var Hp=D(fc(),1);import{videoSizeToQuality as z_,getExponentialDelay as Q_}from"@vkontakte/videoplayer-shared/es2024";var W_=s=>{let e=null;if(s.QUALITY&&(e=$t(s.QUALITY)),!e&&s.RESOLUTION){let[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=z_({width:t,height:i})}return e??null},G_=(s,e)=>{let t=s.split(`
179
179
  `),i=[],r=[];for(let a=0;a<t.length;a++){let n=t[a],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),u=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!u)){if(o){let l=(0,Hp.default)(o[1].split(",").map(S=>S.split("="))),p=l.QUALITY??`stream-${l.BANDWIDTH}`,c=W_(l),d;l.BANDWIDTH&&(d=parseInt(l.BANDWIDTH,10)/1e3||void 0),!d&&l["AVERAGE-BANDWIDTH"]&&(d=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,f;if(l.RESOLUTION){let[S,g]=l.RESOLUTION.split("x").map(v=>parseInt(v,10));S&&g&&(f={width:S,height:g})}let m=new URL(t[++a],e).toString();c&&i.push({id:p,quality:c,url:m,bandwidth:d,size:f,fps:h})}if(u){let l=(0,Hp.default)(u[1].split(",").map(h=>{let f=h.indexOf("=");return[h.substring(0,f),h.substring(f+1)]}).map(([h,f])=>[h,f.replace(/^"|"$/g,"")])),p=l.URI?.replace(/playlist$/,"subtitles.vtt"),c=l.LANGUAGE,d=l.NAME;p&&c&&r.push({type:"internal",id:c,label:d,language:c,url:p,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},Y_=s=>new Promise(e=>{setTimeout(()=>{e()},s)}),jp=0,zE=async(s,e=s,t,i)=>{let a=await(await Ke(s,i)).text();jp+=1;try{let{qualityManifests:n,textTracks:o}=G_(a,e);return{qualityManifests:n,textTracks:o}}catch{if(jp<=t.manifestRetryMaxCount)return await Y_(Q_(jp-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),zE(s,e,t)}return{qualityManifests:[],textTracks:[]}},_u=zE;import{isNonNullable as K_,Subscription as X_,throttle as J_,ValueSubject as QE,Subject as Z_,ErrorCategory as eO}from"@vkontakte/videoplayer-shared/es2024";var Ou=class{constructor(e,t,i,r,a){this.subscription=new X_;this.abortControllers={destroy:new j,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new QE(null);this.getCurrentTime$=new QE(null);this.error$=new Z_;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:a},this.subscription.add(e.pipe(J_(1e3)).subscribe(n=>{this.processLiveTime(n)})),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 r=new URL(i.url,t).toString(),n=await(await Ke(r,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,r);return{textTrack:i,playlist:o}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
180
180
  `),a=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),p=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:a,to:a+p},url:l}),a=a+p,!i.segmentStartTime){let c=new Date(i.vkStartTime).valueOf(),d=new Date(i.programDateTime).valueOf();i.segmentStartTime=d-c}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),a=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(K_(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&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 j;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:eO.WTF,thrown:t,message:e})}};var xn=class{constructor(e){this.subscription=new uO;this.videoState=new O("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new zp([]);this.liveOffset=new qi;this.manifestStartTime$=new zp(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=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.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let p=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(p),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(r?.to!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?P(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),P(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()):r?.to==="playing"&&P(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 p=this.liveOffset.getTotalOffset();p>=this.maxSeekBackTime$.getValue()&&(p=0,this.liveOffset.resetTo(p)),this.liveOffset.resume(),this.params.output.position$.next(-p/1e3),this.prepare()}else r?.to==="paused"&&(P(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return tO(t)}};this.params=e,this.video=Pe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:lO.INVARIANT,url:this.params.source.url};let t=(i,r)=>_u(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},r);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new Ou(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new We(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Nu.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(r,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:Nu.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(ce(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new zp(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=r?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&!r&&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:Nu.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=$e(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.currentBuffer$,e.currentNativeBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Re(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Qe(this.video,t.playbackRate,r.playbackRateState$,i)),a(Ye(this.video),e.elementVisible$),this.liveTextManager?(a(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),a(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},i)).add(r.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(aO(),GE(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),p=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&WE(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let d=this.manifests$.getValue().find(h=>h.id===c);d&&(this.params.output.currentVideoTrack$.next(d),this.params.output.hostname$.next(ce(d.url)))}p&&this.params.desiredState.autoVideoTrackSwitching.setState(p.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(iO({startTime:this.manifestStartTime$.pipe(sO(WE)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(GE(o=>o.map(({id:u,quality:l,size:p,bandwidth:c,fps:d})=>({id:u,quality:l,size:p,fps:d,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let n=nO(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,oO(["init"])).pipe(rO(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),Ae(this.video)}prepare(){let e=this.selectManifest();if(Fu(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=t?.to??i??{};for(let[l,p]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));p&&l&&r.searchParams.set(p,c)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ne(r.toString(),this.liveOffset.getTotalOffset(),a);this.liveTextManager?.prepare(n),this.video.setAttribute("src",n),this.video.load(),qp(n).then(o=>{if(!Fu(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(Fu(u)||!isFinite(u))&&Ke(n).then(l=>l.text()).then(l=>{let p=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(p){let c=new URL(p,n).toString();qp(c).then(d=>{Fu(d)||this.maxSeekBackTime$.next(d)})}}).catch(()=>{})}})}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Nu.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=ne(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}};import{assertNever as cO,debounce as dO,ErrorCategory as Qp,fromEvent as Wp,isNonNullable as pO,isNullable as hO,map as YE,merge as KE,observableFrom as XE,Subscription as fO,ValueSubject as JE,VideoQuality as mO}from"@vkontakte/videoplayer-shared/es2024";var kn=class{constructor(e){this.subscription=new fO;this.videoState=new O("stopped");this.manifests$=new JE([]);this.unmuteAfterBrowserResetsHappened=new JE(!1);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=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.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let p=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(p);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?P(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),P(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()):r?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return cO(t)}};this.textTracksManager=new We(e.source.url),this.params=e,this.video=Pe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:mO.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(ce(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),_u(ne(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.params.output.firstBytesManifest$.next(),this.manifests$.next([this.masterManifest,...t]),this.params.output.manifestReceived$.next(),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Qp.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=r?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&(!r||!r.from)&&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:Qp.WTF,message:"HlsProvider internal logic error",thrown:o})},r=$e(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.currentBuffer$,e.currentNativeBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe(YE(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Qe(this.video,t.playbackRate,r.playbackRateState$,i)),pi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(Re(this.video,t.volume,r.volumeState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),p=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&pO(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(m=>m.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ce(f.url)))}let c=this.params.desiredState.playbackRate.getState(),d=this.params.output.element$.getValue()?.playbackRate;if(c!==d){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}p&&this.params.desiredState.autoVideoTrackSwitching.setState(p.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe(YE(o=>o.map(({id:u,quality:l,size:p,bandwidth:c,fps:d})=>({id:u,quality:l,size:p,fps:d,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!$.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(KE(Wp(o,"addtrack"),Wp(o,"removetrack"),Wp(o,"change"),XE(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=KE(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,XE(["init"])).pipe(dO(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ae(this.video)}prepare(){let e=this.selectManifest();if(hO(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:a,min:n}=t?.to??i??{};for(let[o,u]of[[a,"mq"],[n,"lq"]]){let l=String(parseFloat(o||""));u&&o&&r.searchParams.set(u,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Qp.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var tw=D(ni(),1),Gp=D(Di(),1),iw=D(Ge(),1);import{assertNever as bO,assertNonNullable as ZE,debounce as gO,ErrorCategory as ew,isHigherOrEqual as SO,isLowerOrEqual as vO,isNonNullable as yO,merge as TO,observableFrom as IO,Subscription as EO,map as wO}from"@vkontakte/videoplayer-shared/es2024";var Pn=class{constructor(e){this.subscription=new EO;this.videoState=new O("stopped");this.trackUrls={};this.textTracksManager=new We;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.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!=="ready"&&!n){this.handleQualityLimitTransition(a.to);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});return}switch(i?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?P(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return bO(e)}};this.params=e,this.video=Pe(e.container,e.tuning),this.params.output.element$.next(this.video),(0,tw.default)(this.params.source).reverse().forEach(([t,i],r)=>{let a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Gp.default)(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:ew.WTF,message:"MpegProvider internal logic error",thrown:o})},r=$e(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentNativeBuffer$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe(wO(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,i)),pi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(Re(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Qe(this.video,t.playbackRate,r.playbackRateState$,i)),a(Ye(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&yO(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 p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(u),p.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let n=TO(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,IO(["init"])).pipe(gO(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),Ae(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;ZE(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];ZE(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Tt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ce(t))}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ew.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){this.params.output.autoVideoTrackLimits$.next(e);let t=l=>{this.params.output.currentVideoTrack$.next(l),this.params.desiredState.videoTrack.startTransitionTo(l)},i=l=>{let p=ut(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:l,abrLogger:this.params.dependencies.abrLogger});t(p)},r=this.params.output.currentVideoTrack$.getValue()?.quality,a=!!(e.max||e.min),n=(0,Gp.default)(this.trackUrls).map(l=>l.track);if(!r||!a||Cr(e,n[0].quality,(0,iw.default)(n,-1)?.quality)){i();return}let o=e.max?vO(r,e.max):!0,u=e.min?SO(r,e.min):!0;o&&u||i(e)}};import{assertNever as sw,debounce as AO,merge as aw,observableFrom as RO,Subscription as $O,map as nw,ValueSubject as MO,ErrorCategory as Kp,VideoQuality as LO}from"@vkontakte/videoplayer-shared/es2024";import{ErrorCategory as xO}from"@vkontakte/videoplayer-shared/es2024";var rw=["stun:videostun.mycdn.me:80"],kO=1e3,PO=3,Yp=()=>null,Uu=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=Yp;this.externalStopCallback=Yp;this.externalErrorCallback=Yp;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:rw}]};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:xO.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),kO)}normalizeOptions(e={}){let t={stunServerList:rw,maxRetryNumber:PO,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var An=class{constructor(e){this.videoState=new O("stopped");this.maxSeekBackTime$=new MO(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.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return sw(e)}};this.subscription=new $O,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Pe(e.container,e.tuning),this.liveStreamClient=new Uu(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),Ae(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Kp.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(aw(this.videoState.stateChangeStarted$.pipe(nw(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(nw(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=$e(this.video);this.subscription.add(()=>r.destroy());let a=(n,o)=>this.subscription.add(n.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.currentBuffer$,e.currentNativeBuffer$),a(Ye(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Re(this.video,t.volume,r.volumeState$,i)).add(r.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 sw(n.to)}},i)).add(aw(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,RO(["init"])).pipe(AO(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(ce(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:LO.INVARIANT}),this.video.srcObject=e,P(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.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:Kp.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Kp.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ss=class{constructor(e){this.length=e.length,this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next(),this.index=this.index===void 0?0:this.index+1}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}isLast(){return this.index===this.length-1}};import{assertNever as Rn,assertNonNullable as Kt,ErrorCategory as qu,filter as pw,isNonNullable as hw,isNullable as NO,map as FO,merge as UO,once as qO,Subject as ie,Subscription as fw,ValueSubject as U,flattenObject as Xp,devNull as jO}from"@vkontakte/videoplayer-shared/es2024";import{Observable as DO,map as ow,Subscription as BO,Subject as CO}from"@vkontakte/videoplayer-shared/es2024";var uw=s=>new DO(e=>{let t=new BO,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(ow(({from:l,to:p})=>`${l}-${p}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe(ow(({type:l})=>l!==void 0)),n=new CO,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),s.maxTransitionInterval),_({m:"hangup.set",l,id:o})})),t.add(r.subscribe(()=>{_({m:"hangup.cl",id:o}),window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(l=>{o&&(_({m:"hangup.rs.0",id:o}),window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval),_({m:"hangup.rs.1",id:o})))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as VO,Subscription as _O,combine as OO,filter as cw,once as dw}from"@vkontakte/videoplayer-shared/es2024";function lw(){return new(window.AudioContext||window.webkitAudioContext)}var vs=class s{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new j;this.subscriptions=new _O;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(cw(a=>!!a.type),dw()).subscribe(({type:a})=>this.subscribe(a)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){$.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(OO({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(cw(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),dw()).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=lw();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let a=i.createMediaElementSource(e);return this.mediaElementSource=a,a.connect(r),!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:s.errorId,category:VO.VIDEO_PIPELINE,message:e?.message??`${s.errorId} exception`,thrown:e})}};var HO={chunkDuration:5e3,maxParallelRequests:5},$n=class{constructor(e){this.current$=new U({type:void 0});this.providerError$=new ie;this.noAvailableProvidersError$=new ie;this.volumeMultiplierError$=new ie;this.providerOutput={position$:new U(0),duration$:new U(1/0),volume$:new U({muted:!1,volume:1}),availableVideoStreams$:new U([]),currentVideoStream$:new U(void 0),availableVideoTracks$:new U([]),currentVideoTrack$:new U(void 0),availableVideoCodecs$:new U([]),availableAudioStreams$:new U([]),currentAudioStream$:new U(void 0),availableAudioTracks$:new U([]),availableAudioCodecs$:new U([]),currentVideoSegmentLength$:new U(0),currentAudioSegmentLength$:new U(0),isAudioAvailable$:new U(!0),autoVideoTrackLimitingAvailable$:new U(!1),autoVideoTrackLimits$:new U(void 0),currentBuffer$:new U(void 0),currentNativeBuffer$:new U(void 0),isBuffering$:new U(!0),error$:new ie,fetcherError$:new ie,fetcherRecoverableError$:new ie,warning$:new ie,willSeekEvent$:new ie,soundProhibitedEvent$:new ie,seekedEvent$:new ie,loopedEvent$:new ie,endedEvent$:new ie,manifestRequested$:new ie,firstBytesManifest$:new ie,manifestReceived$:new ie,firstBytesRequested$:new ie,firstBytesReceived$:new ie,firstBytesEvent$:new ie,loadedMetadataEvent$:new ie,firstFrameEvent$:new ie,canplay$:new ie,isLive$:new U(void 0),isLiveEnded$:new U(null),canPlayLiveTailBuffer$:new U(!1),isLowLatency$:new U(!1),canChangePlaybackSpeed$:new U(!0),liveTime$:new U(void 0),liveBufferTime$:new U(void 0),liveLatency$:new U(void 0),severeStallOccurred$:new ie,availableTextTracks$:new U([]),currentTextTrack$:new U(void 0),hostname$:new U(void 0),httpConnectionType$:new U(void 0),httpConnectionReused$:new U(void 0),inPiP$:new U(!1),inFullscreen$:new U(!1),element$:new U(void 0),elementVisible$:new U(!0),availableSources$:new U(void 0),is3DVideo$:new U(!1),playbackState$:new U(""),getCurrentTime$:new U(null)};this.subscription=new fw;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=Nl([...RI(this.params.tuning),...AI(this.params.tuning)]).filter(l=>hw(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(l=>!(0,Jp.default)(r,l)),...t.filter(l=>(0,Jp.default)(r,l))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",Xp(a)),this.screenFormatsIterator=new Ss(a);let n=[...Yd(!0),...Yd(!1)];this.chromecastFormatsIterator=new Ss(n.filter(l=>hw(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&vs.isSupported()&&(this.volumeMultiplierManager=new vs(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){_.reset(),this.subscription.add(this.initProviderErrorHandling()).add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()})).add(this.providerOutput.availableVideoCodecs$.subscribe(e=>{!this.videoCodecsIterator&&e.length>1&&(this.videoCodecsIterator=new Ss(e))}))}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(NO(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:qu.WTF,message:"Failed to create provider",thrown:r})}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()}switchToNextVideoCodec(){this.params.tuning.dash.codecsPrioritizeEnabled&&!this.videoCodecsIterator.isLast()&&(this.tracer.log("switchToNextVideoCodec"),this.destroyProvider(),this.videoCodecsIterator.next(),this.initProvider())}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let a=this.providerOutput.isBuffering$;a.getValue()||a.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 Rn(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:a}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:a};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let u=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Kt(u),this.params.tuning.useNewDashProvider?new En({...o,source:u,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()}):this.params.tuning.useDashProviderVirtual&&!$.device.isMobile?new as({...o,source:u,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()}):this.params.tuning.useDashProviderVirtualMobile&&$.device.isMobile?new as({...o,source:u,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()}):new ln({...o,source:u,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Kt(u),this.params.tuning.useNewDashProvider?new wn({...o,source:u}):new cn({...o,source:u})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let u=this.applyFailoverHost(t[e]);return Kt(u),new kn({...o,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Kt(u),new xn({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return Kt(u),new Pn({...o,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return Kt(u),new My({...o,source:u,config:{...HO,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return Kt(u),new An({container:i,source:u,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Rn(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,n=this.providerOutput,o={meta:a,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};if(this.params.tuning.chromecastPresentationApi&&this.params.dependencies.chromecastInitializer instanceof _t){let{chromecastConnector:l}=this.params.dependencies.chromecastInitializer;return Kt(l),new Os({...o,chromecastConnector:l})}let u=this.params.dependencies.chromecastInitializer.connection$.getValue();return Kt(u),new ea({...o,connection:u})}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 Rn(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Rn(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 Rn(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let a=new URL(r);return a.host=t,a.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,mw.default)((0,Zp.default)(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new fw,t=!1,i=0;e.add(UO(this.providerOutput.error$.pipe(pw(a=>!this.params.tuning.ignoreAudioRendererError||!a.message||!/AUDIO_RENDERER_ERROR/ig.test(a.message))),uw({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(FO(a=>({id:`ProviderHangup:${a}`,category:qu.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let a=this.params.desiredState.playbackState.transitionEnded$.pipe(pw(({to:n})=>n==="playing"),qO()).subscribe(()=>t=!0);e.add(a)}));let r=()=>{let a=_.drain(),{logDashLiveDebug:n,sendDashLiveDebug:o}=this.params.tuning;if(n&&window.console.log(`===== DASH_LIVE DEBUG START ====
181
181
  `,a.map(({time:u,data:l,stack:p})=>`${u}: ${JSON.stringify(l)}${p?`