@vkontakte/videoplayer-core 2.0.154 → 2.0.155

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/es2018.cjs CHANGED
@@ -1,10 +1,10 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.154
3
- * Tue, 10 Mar 2026 14:08:59 GMT
4
- * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-154/doc/
2
+ * @vkontakte/videoplayer-core v2.0.155
3
+ * Wed, 11 Mar 2026 06:02:14 GMT
4
+ * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-155/doc/
5
5
  */
6
6
  "use strict";var vT=Object.create;var Zs=Object.defineProperty;var ST=Object.getOwnPropertyDescriptor;var yT=Object.getOwnPropertyNames;var TT=Object.getPrototypeOf,IT=Object.prototype.hasOwnProperty;var g=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),ET=(s,e)=>{for(var t in e)Zs(s,t,{get:e[t],enumerable:!0})},Bd=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of yT(e))!IT.call(s,r)&&r!==t&&Zs(s,r,{get:()=>e[r],enumerable:!(i=ST(e,r))||i.enumerable});return s};var G=(s,e,t)=>(t=s!=null?vT(TT(s)):{},Bd(e||!s||!s.__esModule?Zs(t,"default",{value:s,enumerable:!0}):t,s)),wT=s=>Bd(Zs({},"__esModule",{value:!0}),s);var Pe=g((Jo,Vd)=>{"use strict";var sa=function(s){return s&&s.Math===Math&&s};Vd.exports=sa(typeof globalThis=="object"&&globalThis)||sa(typeof window=="object"&&window)||sa(typeof self=="object"&&self)||sa(typeof global=="object"&&global)||sa(typeof Jo=="object"&&Jo)||function(){return this}()||Function("return this")()});var Ce=g((vL,_d)=>{"use strict";_d.exports=function(s){try{return!!s()}catch(e){return!0}}});var na=g((SL,Od)=>{"use strict";var xT=Ce();Od.exports=!xT(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")})});var Zo=g((yL,qd)=>{"use strict";var PT=na(),Ud=Function.prototype,Nd=Ud.apply,Fd=Ud.call;qd.exports=typeof Reflect=="object"&&Reflect.apply||(PT?Fd.bind(Nd):function(){return Fd.apply(Nd,arguments)})});var De=g((TL,Wd)=>{"use strict";var Hd=na(),jd=Function.prototype,eu=jd.call,kT=Hd&&jd.bind.bind(eu,eu);Wd.exports=Hd?kT:function(s){return function(){return eu.apply(s,arguments)}}});var Ni=g((IL,zd)=>{"use strict";var Qd=De(),AT=Qd({}.toString),RT=Qd("".slice);zd.exports=function(s){return RT(AT(s),8,-1)}});var tu=g((EL,Gd)=>{"use strict";var MT=Ni(),$T=De();Gd.exports=function(s){if(MT(s)==="Function")return $T(s)}});var ke=g((wL,Yd)=>{"use strict";var iu=typeof document=="object"&&document.all;Yd.exports=typeof iu=="undefined"&&iu!==void 0?function(s){return typeof s=="function"||s===iu}:function(s){return typeof s=="function"}});var nt=g((xL,Kd)=>{"use strict";var LT=Ce();Kd.exports=!LT(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var ot=g((PL,Xd)=>{"use strict";var CT=na(),an=Function.prototype.call;Xd.exports=CT?an.bind(an):function(){return an.apply(an,arguments)}});var ru=g(ep=>{"use strict";var Jd={}.propertyIsEnumerable,Zd=Object.getOwnPropertyDescriptor,DT=Zd&&!Jd.call({1:2},1);ep.f=DT?function(e){var t=Zd(this,e);return!!t&&t.enumerable}:Jd});var oa=g((AL,tp)=>{"use strict";tp.exports=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}}});var rp=g((RL,ip)=>{"use strict";var BT=De(),VT=Ce(),_T=Ni(),au=Object,OT=BT("".split);ip.exports=VT(function(){return!au("z").propertyIsEnumerable(0)})?function(s){return _T(s)==="String"?OT(s,""):au(s)}:au});var ua=g((ML,ap)=>{"use strict";ap.exports=function(s){return s==null}});var li=g(($L,sp)=>{"use strict";var NT=ua(),FT=TypeError;sp.exports=function(s){if(NT(s))throw new FT("Can't call method on "+s);return s}});var Fi=g((LL,np)=>{"use strict";var UT=rp(),qT=li();np.exports=function(s){return UT(qT(s))}});var Ke=g((CL,op)=>{"use strict";var HT=ke();op.exports=function(s){return typeof s=="object"?s!==null:HT(s)}});var Ui=g((DL,up)=>{"use strict";up.exports={}});var zt=g((BL,lp)=>{"use strict";var su=Ui(),nu=Pe(),jT=ke(),cp=function(s){return jT(s)?s:void 0};lp.exports=function(s,e){return arguments.length<2?cp(su[s])||cp(nu[s]):su[s]&&su[s][e]||nu[s]&&nu[s][e]}});var ca=g((VL,dp)=>{"use strict";var WT=De();dp.exports=WT({}.isPrototypeOf)});var qi=g((_L,fp)=>{"use strict";var QT=Pe(),pp=QT.navigator,hp=pp&&pp.userAgent;fp.exports=hp?String(hp):""});var uu=g((OL,yp)=>{"use strict";var Sp=Pe(),ou=qi(),mp=Sp.process,bp=Sp.Deno,gp=mp&&mp.versions||bp&&bp.version,vp=gp&&gp.v8,wt,sn;vp&&(wt=vp.split("."),sn=wt[0]>0&&wt[0]<4?1:+(wt[0]+wt[1]));!sn&&ou&&(wt=ou.match(/Edge\/(\d+)/),(!wt||wt[1]>=74)&&(wt=ou.match(/Chrome\/(\d+)/),wt&&(sn=+wt[1])));yp.exports=sn});var cu=g((NL,Ip)=>{"use strict";var Tp=uu(),zT=Ce(),GT=Pe(),YT=GT.String;Ip.exports=!!Object.getOwnPropertySymbols&&!zT(function(){var s=Symbol("symbol detection");return!YT(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&Tp&&Tp<41})});var lu=g((FL,Ep)=>{"use strict";var KT=cu();Ep.exports=KT&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var du=g((UL,wp)=>{"use strict";var XT=zt(),JT=ke(),ZT=ca(),eI=lu(),tI=Object;wp.exports=eI?function(s){return typeof s=="symbol"}:function(s){var e=XT("Symbol");return JT(e)&&ZT(e.prototype,tI(s))}});var la=g((qL,xp)=>{"use strict";var iI=String;xp.exports=function(s){try{return iI(s)}catch(e){return"Object"}}});var Vt=g((HL,Pp)=>{"use strict";var rI=ke(),aI=la(),sI=TypeError;Pp.exports=function(s){if(rI(s))return s;throw new sI(aI(s)+" is not a function")}});var da=g((jL,kp)=>{"use strict";var nI=Vt(),oI=ua();kp.exports=function(s,e){var t=s[e];return oI(t)?void 0:nI(t)}});var Rp=g((WL,Ap)=>{"use strict";var pu=ot(),hu=ke(),fu=Ke(),uI=TypeError;Ap.exports=function(s,e){var t,i;if(e==="string"&&hu(t=s.toString)&&!fu(i=pu(t,s))||hu(t=s.valueOf)&&!fu(i=pu(t,s))||e!=="string"&&hu(t=s.toString)&&!fu(i=pu(t,s)))return i;throw new uI("Can't convert object to primitive value")}});var xt=g((QL,Mp)=>{"use strict";Mp.exports=!0});var Cp=g((zL,Lp)=>{"use strict";var $p=Pe(),cI=Object.defineProperty;Lp.exports=function(s,e){try{cI($p,s,{value:e,configurable:!0,writable:!0})}catch(t){$p[s]=e}return e}});var pa=g((GL,Vp)=>{"use strict";var lI=xt(),dI=Pe(),pI=Cp(),Dp="__core-js_shared__",Bp=Vp.exports=dI[Dp]||pI(Dp,{});(Bp.versions||(Bp.versions=[])).push({version:"3.43.0",mode:lI?"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 mu=g((YL,Op)=>{"use strict";var _p=pa();Op.exports=function(s,e){return _p[s]||(_p[s]=e||{})}});var vr=g((KL,Np)=>{"use strict";var hI=li(),fI=Object;Np.exports=function(s){return fI(hI(s))}});var Pt=g((XL,Fp)=>{"use strict";var mI=De(),bI=vr(),gI=mI({}.hasOwnProperty);Fp.exports=Object.hasOwn||function(e,t){return gI(bI(e),t)}});var bu=g((JL,Up)=>{"use strict";var vI=De(),SI=0,yI=Math.random(),TI=vI(1.1.toString);Up.exports=function(s){return"Symbol("+(s===void 0?"":s)+")_"+TI(++SI+yI,36)}});var He=g((ZL,Hp)=>{"use strict";var II=Pe(),EI=mu(),qp=Pt(),wI=bu(),xI=cu(),PI=lu(),Sr=II.Symbol,gu=EI("wks"),kI=PI?Sr.for||Sr:Sr&&Sr.withoutSetter||wI;Hp.exports=function(s){return qp(gu,s)||(gu[s]=xI&&qp(Sr,s)?Sr[s]:kI("Symbol."+s)),gu[s]}});var zp=g((eC,Qp)=>{"use strict";var AI=ot(),jp=Ke(),Wp=du(),RI=da(),MI=Rp(),$I=He(),LI=TypeError,CI=$I("toPrimitive");Qp.exports=function(s,e){if(!jp(s)||Wp(s))return s;var t=RI(s,CI),i;if(t){if(e===void 0&&(e="default"),i=AI(t,s,e),!jp(i)||Wp(i))return i;throw new LI("Can't convert object to primitive value")}return e===void 0&&(e="number"),MI(s,e)}});var vu=g((tC,Gp)=>{"use strict";var DI=zp(),BI=du();Gp.exports=function(s){var e=DI(s,"string");return BI(e)?e:e+""}});var nn=g((iC,Kp)=>{"use strict";var VI=Pe(),Yp=Ke(),Su=VI.document,_I=Yp(Su)&&Yp(Su.createElement);Kp.exports=function(s){return _I?Su.createElement(s):{}}});var yu=g((rC,Xp)=>{"use strict";var OI=nt(),NI=Ce(),FI=nn();Xp.exports=!OI&&!NI(function(){return Object.defineProperty(FI("div"),"a",{get:function(){return 7}}).a!==7})});var eh=g(Zp=>{"use strict";var UI=nt(),qI=ot(),HI=ru(),jI=oa(),WI=Fi(),QI=vu(),zI=Pt(),GI=yu(),Jp=Object.getOwnPropertyDescriptor;Zp.f=UI?Jp:function(e,t){if(e=WI(e),t=QI(t),GI)try{return Jp(e,t)}catch(i){}if(zI(e,t))return jI(!qI(HI.f,e,t),e[t])}});var Tu=g((sC,th)=>{"use strict";var YI=Ce(),KI=ke(),XI=/#|\.prototype\./,ha=function(s,e){var t=ZI[JI(s)];return t===tE?!0:t===eE?!1:KI(e)?YI(e):!!e},JI=ha.normalize=function(s){return String(s).replace(XI,".").toLowerCase()},ZI=ha.data={},eE=ha.NATIVE="N",tE=ha.POLYFILL="P";th.exports=ha});var yr=g((nC,rh)=>{"use strict";var ih=tu(),iE=Vt(),rE=na(),aE=ih(ih.bind);rh.exports=function(s,e){return iE(s),e===void 0?s:rE?aE(s,e):function(){return s.apply(e,arguments)}}});var Iu=g((oC,ah)=>{"use strict";var sE=nt(),nE=Ce();ah.exports=sE&&nE(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var _t=g((uC,sh)=>{"use strict";var oE=Ke(),uE=String,cE=TypeError;sh.exports=function(s){if(oE(s))return s;throw new cE(uE(s)+" is not an object")}});var Hi=g(oh=>{"use strict";var lE=nt(),dE=yu(),pE=Iu(),on=_t(),nh=vu(),hE=TypeError,Eu=Object.defineProperty,fE=Object.getOwnPropertyDescriptor,wu="enumerable",xu="configurable",Pu="writable";oh.f=lE?pE?function(e,t,i){if(on(e),t=nh(t),on(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Pu in i&&!i[Pu]){var r=fE(e,t);r&&r[Pu]&&(e[t]=i.value,i={configurable:xu in i?i[xu]:r[xu],enumerable:wu in i?i[wu]:r[wu],writable:!1})}return Eu(e,t,i)}:Eu:function(e,t,i){if(on(e),t=nh(t),on(i),dE)try{return Eu(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new hE("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Tr=g((lC,uh)=>{"use strict";var mE=nt(),bE=Hi(),gE=oa();uh.exports=mE?function(s,e,t){return bE.f(s,e,gE(1,t))}:function(s,e,t){return s[e]=t,s}});var Me=g((dC,lh)=>{"use strict";var fa=Pe(),vE=Zo(),SE=tu(),yE=ke(),TE=eh().f,IE=Tu(),Ir=Ui(),EE=yr(),Er=Tr(),ch=Pt();pa();var wE=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 vE(s,this,arguments)};return e.prototype=s.prototype,e};lh.exports=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?fa:r?fa[t]:fa[t]&&fa[t].prototype,o=i?Ir:Ir[t]||Er(Ir,t,{})[t],u=o.prototype,c,l,d,p,h,m,b,S,v;for(p in e)c=IE(i?p:t+(r?".":"#")+p,s.forced),l=!c&&n&&ch(n,p),m=o[p],l&&(s.dontCallGetSet?(v=TE(n,p),b=v&&v.value):b=n[p]),h=l&&b?b:e[p],!(!c&&!a&&typeof m==typeof h)&&(s.bind&&l?S=EE(h,fa):s.wrap&&l?S=wE(h):a&&yE(h)?S=SE(h):S=h,(s.sham||h&&h.sham||m&&m.sham)&&Er(S,"sham",!0),Er(o,p,S),a&&(d=t+"Prototype",ch(Ir,d)||Er(Ir,d,{}),Er(Ir[d],p,h),s.real&&u&&(c||!u[p])&&Er(u,p,h)))}});var un=g((pC,ph)=>{"use strict";var xE=mu(),PE=bu(),dh=xE("keys");ph.exports=function(s){return dh[s]||(dh[s]=PE(s))}});var fh=g((hC,hh)=>{"use strict";var kE=Ce();hh.exports=!kE(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype})});var cn=g((fC,bh)=>{"use strict";var AE=Pt(),RE=ke(),ME=vr(),$E=un(),LE=fh(),mh=$E("IE_PROTO"),ku=Object,CE=ku.prototype;bh.exports=LE?ku.getPrototypeOf:function(s){var e=ME(s);if(AE(e,mh))return e[mh];var t=e.constructor;return RE(t)&&e instanceof t?t.prototype:e instanceof ku?CE:null}});var vh=g((mC,gh)=>{"use strict";var DE=Math.ceil,BE=Math.floor;gh.exports=Math.trunc||function(e){var t=+e;return(t>0?BE:DE)(t)}});var ma=g((bC,Sh)=>{"use strict";var VE=vh();Sh.exports=function(s){var e=+s;return e!==e||e===0?0:VE(e)}});var Th=g((gC,yh)=>{"use strict";var _E=ma(),OE=Math.max,NE=Math.min;yh.exports=function(s,e){var t=_E(s);return t<0?OE(t+e,0):NE(t,e)}});var Au=g((vC,Ih)=>{"use strict";var FE=ma(),UE=Math.min;Ih.exports=function(s){var e=FE(s);return e>0?UE(e,9007199254740991):0}});var wr=g((SC,Eh)=>{"use strict";var qE=Au();Eh.exports=function(s){return qE(s.length)}});var Ru=g((yC,xh)=>{"use strict";var HE=Fi(),jE=Th(),WE=wr(),wh=function(s){return function(e,t,i){var r=HE(e),a=WE(r);if(a===0)return!s&&-1;var n=jE(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}};xh.exports={includes:wh(!0),indexOf:wh(!1)}});var ln=g((TC,Ph)=>{"use strict";Ph.exports={}});var Rh=g((IC,Ah)=>{"use strict";var QE=De(),Mu=Pt(),zE=Fi(),GE=Ru().indexOf,YE=ln(),kh=QE([].push);Ah.exports=function(s,e){var t=zE(s),i=0,r=[],a;for(a in t)!Mu(YE,a)&&Mu(t,a)&&kh(r,a);for(;e.length>i;)Mu(t,a=e[i++])&&(~GE(r,a)||kh(r,a));return r}});var $u=g((EC,Mh)=>{"use strict";Mh.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Lu=g((wC,$h)=>{"use strict";var KE=Rh(),XE=$u();$h.exports=Object.keys||function(e){return KE(e,XE)}});var Cu=g((xC,Vh)=>{"use strict";var Ch=nt(),JE=Ce(),Dh=De(),ZE=cn(),ew=Lu(),tw=Fi(),iw=ru().f,Bh=Dh(iw),rw=Dh([].push),aw=Ch&&JE(function(){var s=Object.create(null);return s[2]=2,!Bh(s,2)}),Lh=function(s){return function(e){for(var t=tw(e),i=ew(t),r=aw&&ZE(t)===null,a=i.length,n=0,o=[],u;a>n;)u=i[n++],(!Ch||(r?u in t:Bh(t,u)))&&rw(o,s?[u,t[u]]:t[u]);return o}};Vh.exports={entries:Lh(!0),values:Lh(!1)}});var _h=g(()=>{"use strict";var sw=Me(),nw=Cu().values;sw({target:"Object",stat:!0},{values:function(e){return nw(e)}})});var Nh=g((AC,Oh)=>{"use strict";_h();var ow=Ui();Oh.exports=ow.Object.values});var Uh=g((RC,Fh)=>{"use strict";var uw=Nh();Fh.exports=uw});var ji=g((MC,qh)=>{"use strict";var cw=Uh();qh.exports=cw});var ba=g(($C,Hh)=>{"use strict";Hh.exports=function(){}});var jh=g(()=>{"use strict";var lw=Me(),dw=Ru().includes,pw=Ce(),hw=ba(),fw=pw(function(){return!Array(1).includes()});lw({target:"Array",proto:!0,forced:fw},{includes:function(e){return dw(this,e,arguments.length>1?arguments[1]:void 0)}});hw("includes")});var di=g((DC,Wh)=>{"use strict";var mw=zt();Wh.exports=mw});var zh=g((BC,Qh)=>{"use strict";jh();var bw=di();Qh.exports=bw("Array","includes")});var Yh=g((VC,Gh)=>{"use strict";var gw=zh();Gh.exports=gw});var Xe=g((_C,Kh)=>{"use strict";var vw=Yh();Kh.exports=vw});var pf=g(()=>{"use strict";var Aw=Me(),Rw=Cu().entries;Aw({target:"Object",stat:!0},{entries:function(e){return Rw(e)}})});var ff=g((w0,hf)=>{"use strict";pf();var Mw=Ui();hf.exports=Mw.Object.entries});var bf=g((x0,mf)=>{"use strict";var $w=ff();mf.exports=$w});var mi=g((P0,gf)=>{"use strict";var Lw=bf();gf.exports=Lw});var Qi=g((k0,vf)=>{"use strict";vf.exports={}});var Tf=g((A0,yf)=>{"use strict";var Cw=Pe(),Dw=ke(),Sf=Cw.WeakMap;yf.exports=Dw(Sf)&&/native code/.test(String(Sf))});var Uu=g((R0,wf)=>{"use strict";var Bw=Tf(),Ef=Pe(),Vw=Ke(),_w=Tr(),Ou=Pt(),Nu=pa(),Ow=un(),Nw=ln(),If="Object already initialized",Fu=Ef.TypeError,Fw=Ef.WeakMap,En,Ta,wn,Uw=function(s){return wn(s)?Ta(s):En(s,{})},qw=function(s){return function(e){var t;if(!Vw(e)||(t=Ta(e)).type!==s)throw new Fu("Incompatible receiver, "+s+" required");return t}};Bw||Nu.state?(kt=Nu.state||(Nu.state=new Fw),kt.get=kt.get,kt.has=kt.has,kt.set=kt.set,En=function(s,e){if(kt.has(s))throw new Fu(If);return e.facade=s,kt.set(s,e),e},Ta=function(s){return kt.get(s)||{}},wn=function(s){return kt.has(s)}):(zi=Ow("state"),Nw[zi]=!0,En=function(s,e){if(Ou(s,zi))throw new Fu(If);return e.facade=s,_w(s,zi,e),e},Ta=function(s){return Ou(s,zi)?s[zi]:{}},wn=function(s){return Ou(s,zi)});var kt,zi;wf.exports={set:En,get:Ta,has:wn,enforce:Uw,getterFor:qw}});var ju=g((M0,Pf)=>{"use strict";var qu=nt(),Hw=Pt(),xf=Function.prototype,jw=qu&&Object.getOwnPropertyDescriptor,Hu=Hw(xf,"name"),Ww=Hu&&function(){}.name==="something",Qw=Hu&&(!qu||qu&&jw(xf,"name").configurable);Pf.exports={EXISTS:Hu,PROPER:Ww,CONFIGURABLE:Qw}});var Af=g(kf=>{"use strict";var zw=nt(),Gw=Iu(),Yw=Hi(),Kw=_t(),Xw=Fi(),Jw=Lu();kf.f=zw&&!Gw?Object.defineProperties:function(e,t){Kw(e);for(var i=Xw(t),r=Jw(t),a=r.length,n=0,o;a>n;)Yw.f(e,o=r[n++],i[o]);return e}});var Wu=g((L0,Rf)=>{"use strict";var Zw=zt();Rf.exports=Zw("document","documentElement")});var Yu=g((C0,Vf)=>{"use strict";var ex=_t(),tx=Af(),Mf=$u(),ix=ln(),rx=Wu(),ax=nn(),sx=un(),$f=">",Lf="<",zu="prototype",Gu="script",Df=sx("IE_PROTO"),Qu=function(){},Bf=function(s){return Lf+Gu+$f+s+Lf+"/"+Gu+$f},Cf=function(s){s.write(Bf("")),s.close();var e=s.parentWindow.Object;return s=null,e},nx=function(){var s=ax("iframe"),e="java"+Gu+":",t;return s.style.display="none",rx.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(Bf("document.F=Object")),t.close(),t.F},xn,Pn=function(){try{xn=new ActiveXObject("htmlfile")}catch(e){}Pn=typeof document!="undefined"?document.domain&&xn?Cf(xn):nx():Cf(xn);for(var s=Mf.length;s--;)delete Pn[zu][Mf[s]];return Pn()};ix[Df]=!0;Vf.exports=Object.create||function(e,t){var i;return e!==null?(Qu[zu]=ex(e),i=new Qu,Qu[zu]=null,i[Df]=e):i=Pn(),t===void 0?i:tx.f(i,t)}});var Pr=g((D0,_f)=>{"use strict";var ox=Tr();_f.exports=function(s,e,t,i){return i&&i.enumerable?s[e]=t:ox(s,e,t),s}});var Zu=g((B0,Ff)=>{"use strict";var ux=Ce(),cx=ke(),lx=Ke(),dx=Yu(),Of=cn(),px=Pr(),hx=He(),fx=xt(),Ju=hx("iterator"),Nf=!1,Yt,Ku,Xu;[].keys&&(Xu=[].keys(),"next"in Xu?(Ku=Of(Of(Xu)),Ku!==Object.prototype&&(Yt=Ku)):Nf=!0);var mx=!lx(Yt)||ux(function(){var s={};return Yt[Ju].call(s)!==s});mx?Yt={}:fx&&(Yt=dx(Yt));cx(Yt[Ju])||px(Yt,Ju,function(){return this});Ff.exports={IteratorPrototype:Yt,BUGGY_SAFARI_ITERATORS:Nf}});var kn=g((V0,qf)=>{"use strict";var bx=He(),gx=bx("toStringTag"),Uf={};Uf[gx]="z";qf.exports=String(Uf)==="[object z]"});var Ia=g((_0,Hf)=>{"use strict";var vx=kn(),Sx=ke(),An=Ni(),yx=He(),Tx=yx("toStringTag"),Ix=Object,Ex=An(function(){return arguments}())==="Arguments",wx=function(s,e){try{return s[e]}catch(t){}};Hf.exports=vx?An:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=wx(e=Ix(s),Tx))=="string"?t:Ex?An(e):(i=An(e))==="Object"&&Sx(e.callee)?"Arguments":i}});var Wf=g((O0,jf)=>{"use strict";var xx=kn(),Px=Ia();jf.exports=xx?{}.toString:function(){return"[object "+Px(this)+"]"}});var Ea=g((N0,zf)=>{"use strict";var kx=kn(),Ax=Hi().f,Rx=Tr(),Mx=Pt(),$x=Wf(),Lx=He(),Qf=Lx("toStringTag");zf.exports=function(s,e,t,i){var r=t?s:s&&s.prototype;r&&(Mx(r,Qf)||Ax(r,Qf,{configurable:!0,value:e}),i&&!kx&&Rx(r,"toString",$x))}});var Yf=g((F0,Gf)=>{"use strict";var Cx=Zu().IteratorPrototype,Dx=Yu(),Bx=oa(),Vx=Ea(),_x=Qi(),Ox=function(){return this};Gf.exports=function(s,e,t,i){var r=e+" Iterator";return s.prototype=Dx(Cx,{next:Bx(+!i,t)}),Vx(s,r,!1,!0),_x[r]=Ox,s}});var Xf=g((U0,Kf)=>{"use strict";var Nx=De(),Fx=Vt();Kf.exports=function(s,e,t){try{return Nx(Fx(Object.getOwnPropertyDescriptor(s,e)[t]))}catch(i){}}});var Zf=g((q0,Jf)=>{"use strict";var Ux=Ke();Jf.exports=function(s){return Ux(s)||s===null}});var tm=g((H0,em)=>{"use strict";var qx=Zf(),Hx=String,jx=TypeError;em.exports=function(s){if(qx(s))return s;throw new jx("Can't set "+Hx(s)+" as a prototype")}});var ec=g((j0,im)=>{"use strict";var Wx=Xf(),Qx=Ke(),zx=li(),Gx=tm();im.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var s=!1,e={},t;try{t=Wx(Object.prototype,"__proto__","set"),t(e,[]),s=e instanceof Array}catch(i){}return function(r,a){return zx(r),Gx(a),Qx(r)&&(s?t(r,a):r.__proto__=a),r}}():void 0)});var hm=g((W0,pm)=>{"use strict";var Yx=Me(),Kx=ot(),Rn=xt(),lm=ju(),Xx=ke(),Jx=Yf(),rm=cn(),am=ec(),Zx=Ea(),eP=Tr(),tc=Pr(),tP=He(),sm=Qi(),dm=Zu(),iP=lm.PROPER,rP=lm.CONFIGURABLE,nm=dm.IteratorPrototype,Mn=dm.BUGGY_SAFARI_ITERATORS,wa=tP("iterator"),om="keys",xa="values",um="entries",cm=function(){return this};pm.exports=function(s,e,t,i,r,a,n){Jx(t,e,i);var o=function(v){if(v===r&&p)return p;if(!Mn&&v&&v in l)return l[v];switch(v){case om:return function(){return new t(this,v)};case xa:return function(){return new t(this,v)};case um:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",c=!1,l=s.prototype,d=l[wa]||l["@@iterator"]||r&&l[r],p=!Mn&&d||o(r),h=e==="Array"&&l.entries||d,m,b,S;if(h&&(m=rm(h.call(new s)),m!==Object.prototype&&m.next&&(!Rn&&rm(m)!==nm&&(am?am(m,nm):Xx(m[wa])||tc(m,wa,cm)),Zx(m,u,!0,!0),Rn&&(sm[u]=cm))),iP&&r===xa&&d&&d.name!==xa&&(!Rn&&rP?eP(l,"name",xa):(c=!0,p=function(){return Kx(d,this)})),r)if(b={values:o(xa),keys:a?p:o(om),entries:o(um)},n)for(S in b)(Mn||c||!(S in l))&&tc(l,S,b[S]);else Yx({target:e,proto:!0,forced:Mn||c},b);return(!Rn||n)&&l[wa]!==p&&tc(l,wa,p,{name:r}),sm[e]=p,b}});var mm=g((Q0,fm)=>{"use strict";fm.exports=function(s,e){return{value:s,done:e}}});var rc=g((z0,ym)=>{"use strict";var aP=Fi(),ic=ba(),bm=Qi(),vm=Uu(),sP=Hi().f,nP=hm(),$n=mm(),oP=xt(),uP=nt(),Sm="Array Iterator",cP=vm.set,lP=vm.getterFor(Sm);ym.exports=nP(Array,"Array",function(s,e){cP(this,{type:Sm,target:aP(s),index:0,kind:e})},function(){var s=lP(this),e=s.target,t=s.index++;if(!e||t>=e.length)return s.target=null,$n(void 0,!0);switch(s.kind){case"keys":return $n(t,!1);case"values":return $n(e[t],!1)}return $n([t,e[t]],!1)},"values");var gm=bm.Arguments=bm.Array;ic("keys");ic("values");ic("entries");if(!oP&&uP&&gm.name!=="values")try{sP(gm,"name",{value:"values"})}catch(s){}});var Im=g((G0,Tm)=>{"use strict";var dP=He(),pP=Qi(),hP=dP("iterator"),fP=Array.prototype;Tm.exports=function(s){return s!==void 0&&(pP.Array===s||fP[hP]===s)}});var ac=g((Y0,wm)=>{"use strict";var mP=Ia(),Em=da(),bP=ua(),gP=Qi(),vP=He(),SP=vP("iterator");wm.exports=function(s){if(!bP(s))return Em(s,SP)||Em(s,"@@iterator")||gP[mP(s)]}});var Pm=g((K0,xm)=>{"use strict";var yP=ot(),TP=Vt(),IP=_t(),EP=la(),wP=ac(),xP=TypeError;xm.exports=function(s,e){var t=arguments.length<2?wP(s):e;if(TP(t))return IP(yP(t,s));throw new xP(EP(s)+" is not iterable")}});var Rm=g((X0,Am)=>{"use strict";var PP=ot(),km=_t(),kP=da();Am.exports=function(s,e,t){var i,r;km(s);try{if(i=kP(s,"return"),!i){if(e==="throw")throw t;return t}i=PP(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return km(i),t}});var Cn=g((J0,Cm)=>{"use strict";var AP=yr(),RP=ot(),MP=_t(),$P=la(),LP=Im(),CP=wr(),Mm=ca(),DP=Pm(),BP=ac(),$m=Rm(),VP=TypeError,Ln=function(s,e){this.stopped=s,this.result=e},Lm=Ln.prototype;Cm.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=AP(e,i),c,l,d,p,h,m,b,S=function(y){return c&&$m(c,"normal"),new Ln(!0,y)},v=function(y){return r?(MP(y),o?u(y[0],y[1],S):u(y[0],y[1])):o?u(y,S):u(y)};if(a)c=s.iterator;else if(n)c=s;else{if(l=BP(s),!l)throw new VP($P(s)+" is not iterable");if(LP(l)){for(d=0,p=CP(s);p>d;d++)if(h=v(s[d]),h&&Mm(Lm,h))return h;return new Ln(!1)}c=DP(s,l)}for(m=a?s.next:c.next;!(b=RP(m,c)).done;){try{h=v(b.value)}catch(y){$m(c,"throw",y)}if(typeof h=="object"&&h&&Mm(Lm,h))return h}return new Ln(!1)}});var Bm=g((Z0,Dm)=>{"use strict";var _P=nt(),OP=Hi(),NP=oa();Dm.exports=function(s,e,t){_P?OP.f(s,e,NP(0,t)):s[e]=t}});var Vm=g(()=>{"use strict";var FP=Me(),UP=Cn(),qP=Bm();FP({target:"Object",stat:!0},{fromEntries:function(e){var t={};return UP(e,function(i,r){qP(t,i,r)},{AS_ENTRIES:!0}),t}})});var Om=g((iB,_m)=>{"use strict";rc();Vm();var HP=Ui();_m.exports=HP.Object.fromEntries});var Fm=g((rB,Nm)=>{"use strict";Nm.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 qm=g(()=>{"use strict";rc();var jP=Fm(),WP=Pe(),QP=Ea(),Um=Qi();for(Dn in jP)QP(WP[Dn],Dn),Um[Dn]=Um.Array;var Dn});var jm=g((nB,Hm)=>{"use strict";var zP=Om();qm();Hm.exports=zP});var sc=g((oB,Wm)=>{"use strict";var GP=jm();Wm.exports=GP});var Qm=g(()=>{"use strict"});var nc=g((lB,zm)=>{"use strict";var Pa=Pe(),YP=qi(),KP=Ni(),Bn=function(s){return YP.slice(0,s.length)===s};zm.exports=function(){return Bn("Bun/")?"BUN":Bn("Cloudflare-Workers")?"CLOUDFLARE":Bn("Deno/")?"DENO":Bn("Node.js/")?"NODE":Pa.Bun&&typeof Bun.version=="string"?"BUN":Pa.Deno&&typeof Deno.version=="object"?"DENO":KP(Pa.process)==="process"?"NODE":Pa.window&&Pa.document?"BROWSER":"REST"}()});var Vn=g((dB,Gm)=>{"use strict";var XP=nc();Gm.exports=XP==="NODE"});var Km=g((pB,Ym)=>{"use strict";var JP=Hi();Ym.exports=function(s,e,t){return JP.f(s,e,t)}});var Zm=g((hB,Jm)=>{"use strict";var ZP=zt(),ek=Km(),tk=He(),ik=nt(),Xm=tk("species");Jm.exports=function(s){var e=ZP(s);ik&&e&&!e[Xm]&&ek(e,Xm,{configurable:!0,get:function(){return this}})}});var tb=g((fB,eb)=>{"use strict";var rk=ca(),ak=TypeError;eb.exports=function(s,e){if(rk(e,s))return s;throw new ak("Incorrect invocation")}});var uc=g((mB,ib)=>{"use strict";var sk=De(),nk=ke(),oc=pa(),ok=sk(Function.toString);nk(oc.inspectSource)||(oc.inspectSource=function(s){return ok(s)});ib.exports=oc.inspectSource});var lc=g((bB,ob)=>{"use strict";var uk=De(),ck=Ce(),rb=ke(),lk=Ia(),dk=zt(),pk=uc(),ab=function(){},sb=dk("Reflect","construct"),cc=/^\s*(?:class|function)\b/,hk=uk(cc.exec),fk=!cc.test(ab),ka=function(e){if(!rb(e))return!1;try{return sb(ab,[],e),!0}catch(t){return!1}},nb=function(e){if(!rb(e))return!1;switch(lk(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return fk||!!hk(cc,pk(e))}catch(t){return!0}};nb.sham=!0;ob.exports=!sb||ck(function(){var s;return ka(ka.call)||!ka(Object)||!ka(function(){s=!0})||s})?nb:ka});var cb=g((gB,ub)=>{"use strict";var mk=lc(),bk=la(),gk=TypeError;ub.exports=function(s){if(mk(s))return s;throw new gk(bk(s)+" is not a constructor")}});var dc=g((vB,db)=>{"use strict";var lb=_t(),vk=cb(),Sk=ua(),yk=He(),Tk=yk("species");db.exports=function(s,e){var t=lb(s).constructor,i;return t===void 0||Sk(i=lb(t)[Tk])?e:vk(i)}});var hb=g((SB,pb)=>{"use strict";var Ik=De();pb.exports=Ik([].slice)});var mb=g((yB,fb)=>{"use strict";var Ek=TypeError;fb.exports=function(s,e){if(s<e)throw new Ek("Not enough arguments");return s}});var pc=g((TB,bb)=>{"use strict";var wk=qi();bb.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(wk)});var Tc=g((IB,xb)=>{"use strict";var ct=Pe(),xk=Zo(),Pk=yr(),gb=ke(),kk=Pt(),wb=Ce(),vb=Wu(),Ak=hb(),Sb=nn(),Rk=mb(),Mk=pc(),$k=Vn(),vc=ct.setImmediate,Sc=ct.clearImmediate,Lk=ct.process,hc=ct.Dispatch,Ck=ct.Function,yb=ct.MessageChannel,Dk=ct.String,fc=0,Aa={},Tb="onreadystatechange",Ra,Gi,mc,bc;wb(function(){Ra=ct.location});var yc=function(s){if(kk(Aa,s)){var e=Aa[s];delete Aa[s],e()}},gc=function(s){return function(){yc(s)}},Ib=function(s){yc(s.data)},Eb=function(s){ct.postMessage(Dk(s),Ra.protocol+"//"+Ra.host)};(!vc||!Sc)&&(vc=function(e){Rk(arguments.length,1);var t=gb(e)?e:Ck(e),i=Ak(arguments,1);return Aa[++fc]=function(){xk(t,void 0,i)},Gi(fc),fc},Sc=function(e){delete Aa[e]},$k?Gi=function(s){Lk.nextTick(gc(s))}:hc&&hc.now?Gi=function(s){hc.now(gc(s))}:yb&&!Mk?(mc=new yb,bc=mc.port2,mc.port1.onmessage=Ib,Gi=Pk(bc.postMessage,bc)):ct.addEventListener&&gb(ct.postMessage)&&!ct.importScripts&&Ra&&Ra.protocol!=="file:"&&!wb(Eb)?(Gi=Eb,ct.addEventListener("message",Ib,!1)):Tb in Sb("script")?Gi=function(s){vb.appendChild(Sb("script"))[Tb]=function(){vb.removeChild(this),yc(s)}}:Gi=function(s){setTimeout(gc(s),0)});xb.exports={set:vc,clear:Sc}});var Ab=g((EB,kb)=>{"use strict";var Pb=Pe(),Bk=nt(),Vk=Object.getOwnPropertyDescriptor;kb.exports=function(s){if(!Bk)return Pb[s];var e=Vk(Pb,s);return e&&e.value}});var Ic=g((wB,Mb)=>{"use strict";var Rb=function(){this.head=null,this.tail=null};Rb.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}}};Mb.exports=Rb});var Lb=g((xB,$b)=>{"use strict";var _k=qi();$b.exports=/ipad|iphone|ipod/i.test(_k)&&typeof Pebble!="undefined"});var Db=g((PB,Cb)=>{"use strict";var Ok=qi();Cb.exports=/web0s(?!.*chrome)/i.test(Ok)});var Ub=g((kB,Fb)=>{"use strict";var Ar=Pe(),Nk=Ab(),Bb=yr(),Ec=Tc().set,Fk=Ic(),Uk=pc(),qk=Lb(),Hk=Db(),wc=Vn(),Vb=Ar.MutationObserver||Ar.WebKitMutationObserver,_b=Ar.document,Ob=Ar.process,_n=Ar.Promise,kc=Nk("queueMicrotask"),kr,xc,Pc,On,Nb;kc||(Ma=new Fk,$a=function(){var s,e;for(wc&&(s=Ob.domain)&&s.exit();e=Ma.get();)try{e()}catch(t){throw Ma.head&&kr(),t}s&&s.enter()},!Uk&&!wc&&!Hk&&Vb&&_b?(xc=!0,Pc=_b.createTextNode(""),new Vb($a).observe(Pc,{characterData:!0}),kr=function(){Pc.data=xc=!xc}):!qk&&_n&&_n.resolve?(On=_n.resolve(void 0),On.constructor=_n,Nb=Bb(On.then,On),kr=function(){Nb($a)}):wc?kr=function(){Ob.nextTick($a)}:(Ec=Bb(Ec,Ar),kr=function(){Ec($a)}),kc=function(s){Ma.head||kr(),Ma.add(s)});var Ma,$a;Fb.exports=kc});var Hb=g((AB,qb)=>{"use strict";qb.exports=function(s,e){try{arguments.length===1?console.error(s):console.error(s,e)}catch(t){}}});var Nn=g((RB,jb)=>{"use strict";jb.exports=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}}});var Yi=g((MB,Wb)=>{"use strict";var jk=Pe();Wb.exports=jk.Promise});var Rr=g(($B,Yb)=>{"use strict";var Wk=Pe(),La=Yi(),Qk=ke(),zk=Tu(),Gk=uc(),Yk=He(),Qb=nc(),Kk=xt(),Ac=uu(),zb=La&&La.prototype,Xk=Yk("species"),Rc=!1,Gb=Qk(Wk.PromiseRejectionEvent),Jk=zk("Promise",function(){var s=Gk(La),e=s!==String(La);if(!e&&Ac===66||Kk&&!(zb.catch&&zb.finally))return!0;if(!Ac||Ac<51||!/native code/.test(s)){var t=new La(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[Xk]=i,Rc=t.then(function(){})instanceof i,!Rc)return!0}return!e&&(Qb==="BROWSER"||Qb==="DENO")&&!Gb});Yb.exports={CONSTRUCTOR:Jk,REJECTION_EVENT:Gb,SUBCLASSING:Rc}});var Mr=g((LB,Xb)=>{"use strict";var Kb=Vt(),Zk=TypeError,eA=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw new Zk("Bad Promise constructor");e=i,t=r}),this.resolve=Kb(e),this.reject=Kb(t)};Xb.exports.f=function(s){return new eA(s)}});var gg=g(()=>{"use strict";var tA=Me(),iA=xt(),Hn=Vn(),bi=Pe(),rA=Ui(),Dr=ot(),Jb=Pr(),Zb=ec(),aA=Ea(),sA=Zm(),nA=Vt(),qn=ke(),oA=Ke(),uA=tb(),cA=dc(),ag=Tc().set,Dc=Ub(),lA=Hb(),dA=Nn(),pA=Ic(),sg=Uu(),jn=Yi(),Bc=Rr(),ng=Mr(),Wn="Promise",og=Bc.CONSTRUCTOR,hA=Bc.REJECTION_EVENT,fA=Bc.SUBCLASSING,Mc=sg.getterFor(Wn),mA=sg.set,$r=jn&&jn.prototype,Ki=jn,Fn=$r,ug=bi.TypeError,$c=bi.document,Vc=bi.process,Lc=ng.f,bA=Lc,gA=!!($c&&$c.createEvent&&bi.dispatchEvent),cg="unhandledrejection",vA="rejectionhandled",eg=0,lg=1,SA=2,_c=1,dg=2,Un,tg,pg,ig,hg=function(s){var e;return oA(s)&&qn(e=s.then)?e:!1},fg=function(s,e){var t=e.value,i=e.state===lg,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,c,l;try{r?(i||(e.rejection===dg&&TA(e),e.rejection=_c),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),l=!0)),u===s.promise?n(new ug("Promise-chain cycle")):(c=hg(u))?Dr(c,u,a,n):a(u)):n(t)}catch(d){o&&!l&&o.exit(),n(d)}},mg=function(s,e){s.notified||(s.notified=!0,Dc(function(){for(var t=s.reactions,i;i=t.get();)fg(i,s);s.notified=!1,e&&!s.rejection&&yA(s)}))},bg=function(s,e,t){var i,r;gA?(i=$c.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),bi.dispatchEvent(i)):i={promise:e,reason:t},!hA&&(r=bi["on"+s])?r(i):s===cg&&lA("Unhandled promise rejection",t)},yA=function(s){Dr(ag,bi,function(){var e=s.facade,t=s.value,i=rg(s),r;if(i&&(r=dA(function(){Hn?Vc.emit("unhandledRejection",t,e):bg(cg,e,t)}),s.rejection=Hn||rg(s)?dg:_c,r.error))throw r.value})},rg=function(s){return s.rejection!==_c&&!s.parent},TA=function(s){Dr(ag,bi,function(){var e=s.facade;Hn?Vc.emit("rejectionHandled",e):bg(vA,e,s.value)})},Lr=function(s,e,t){return function(i){s(e,i,t)}},Cr=function(s,e,t){s.done||(s.done=!0,t&&(s=t),s.value=e,s.state=SA,mg(s,!0))},Cc=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw new ug("Promise can't be resolved itself");var i=hg(e);i?Dc(function(){var r={done:!1};try{Dr(i,e,Lr(Cc,r,s),Lr(Cr,r,s))}catch(a){Cr(r,a,s)}}):(s.value=e,s.state=lg,mg(s,!1))}catch(r){Cr({done:!1},r,s)}}};if(og&&(Ki=function(e){uA(this,Fn),nA(e),Dr(Un,this);var t=Mc(this);try{e(Lr(Cc,t),Lr(Cr,t))}catch(i){Cr(t,i)}},Fn=Ki.prototype,Un=function(e){mA(this,{type:Wn,done:!1,notified:!1,parent:!1,reactions:new pA,rejection:!1,state:eg,value:null})},Un.prototype=Jb(Fn,"then",function(e,t){var i=Mc(this),r=Lc(cA(this,Ki));return i.parent=!0,r.ok=qn(e)?e:!0,r.fail=qn(t)&&t,r.domain=Hn?Vc.domain:void 0,i.state===eg?i.reactions.add(r):Dc(function(){fg(r,i)}),r.promise}),tg=function(){var s=new Un,e=Mc(s);this.promise=s,this.resolve=Lr(Cc,e),this.reject=Lr(Cr,e)},ng.f=Lc=function(s){return s===Ki||s===pg?new tg(s):bA(s)},!iA&&qn(jn)&&$r!==Object.prototype)){ig=$r.then,fA||Jb($r,"then",function(e,t){var i=this;return new Ki(function(r,a){Dr(ig,i,r,a)}).then(e,t)},{unsafe:!0});try{delete $r.constructor}catch(s){}Zb&&Zb($r,Fn)}tA({global:!0,constructor:!0,wrap:!0,forced:og},{Promise:Ki});pg=rA.Promise;aA(Ki,Wn,!1,!0);sA(Wn)});var Ig=g((BB,Tg)=>{"use strict";var IA=He(),Sg=IA("iterator"),yg=!1;try{vg=0,Oc={next:function(){return{done:!!vg++}},return:function(){yg=!0}},Oc[Sg]=function(){return this},Array.from(Oc,function(){throw 2})}catch(s){}var vg,Oc;Tg.exports=function(s,e){try{if(!e&&!yg)return!1}catch(r){return!1}var t=!1;try{var i={};i[Sg]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch(r){}return t}});var Nc=g((VB,Eg)=>{"use strict";var EA=Yi(),wA=Ig(),xA=Rr().CONSTRUCTOR;Eg.exports=xA||!wA(function(s){EA.all(s).then(void 0,function(){})})});var wg=g(()=>{"use strict";var PA=Me(),kA=ot(),AA=Vt(),RA=Mr(),MA=Nn(),$A=Cn(),LA=Nc();PA({target:"Promise",stat:!0,forced:LA},{all:function(e){var t=this,i=RA.f(t),r=i.resolve,a=i.reject,n=MA(function(){var o=AA(t.resolve),u=[],c=0,l=1;$A(e,function(d){var p=c++,h=!1;l++,kA(o,t,d).then(function(m){h||(h=!0,u[p]=m,--l||r(u))},a)}),--l||r(u)});return n.error&&a(n.value),i.promise}})});var Pg=g(()=>{"use strict";var CA=Me(),DA=xt(),BA=Rr().CONSTRUCTOR,Uc=Yi(),VA=zt(),_A=ke(),OA=Pr(),xg=Uc&&Uc.prototype;CA({target:"Promise",proto:!0,forced:BA,real:!0},{catch:function(s){return this.then(void 0,s)}});!DA&&_A(Uc)&&(Fc=VA("Promise").prototype.catch,xg.catch!==Fc&&OA(xg,"catch",Fc,{unsafe:!0}));var Fc});var kg=g(()=>{"use strict";var NA=Me(),FA=ot(),UA=Vt(),qA=Mr(),HA=Nn(),jA=Cn(),WA=Nc();NA({target:"Promise",stat:!0,forced:WA},{race:function(e){var t=this,i=qA.f(t),r=i.reject,a=HA(function(){var n=UA(t.resolve);jA(e,function(o){FA(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}})});var Ag=g(()=>{"use strict";var QA=Me(),zA=Mr(),GA=Rr().CONSTRUCTOR;QA({target:"Promise",stat:!0,forced:GA},{reject:function(e){var t=zA.f(this),i=t.reject;return i(e),t.promise}})});var qc=g((WB,Rg)=>{"use strict";var YA=_t(),KA=Ke(),XA=Mr();Rg.exports=function(s,e){if(YA(s),KA(e)&&e.constructor===s)return e;var t=XA.f(s),i=t.resolve;return i(e),t.promise}});var Lg=g(()=>{"use strict";var JA=Me(),ZA=zt(),Mg=xt(),eR=Yi(),$g=Rr().CONSTRUCTOR,tR=qc(),iR=ZA("Promise"),rR=Mg&&!$g;JA({target:"Promise",stat:!0,forced:Mg||$g},{resolve:function(e){return tR(rR&&this===iR?eR:this,e)}})});var Cg=g(()=>{"use strict";gg();wg();Pg();kg();Ag();Lg()});var _g=g(()=>{"use strict";var aR=Me(),sR=xt(),Qn=Yi(),nR=Ce(),Bg=zt(),Vg=ke(),oR=dc(),Dg=qc(),uR=Pr(),jc=Qn&&Qn.prototype,cR=!!Qn&&nR(function(){jc.finally.call({then:function(){}},function(){})});aR({target:"Promise",proto:!0,real:!0,forced:cR},{finally:function(s){var e=oR(this,Bg("Promise")),t=Vg(s);return this.then(t?function(i){return Dg(e,s()).then(function(){return i})}:s,t?function(i){return Dg(e,s()).then(function(){throw i})}:s)}});!sR&&Vg(Qn)&&(Hc=Bg("Promise").prototype.finally,jc.finally!==Hc&&uR(jc,"finally",Hc,{unsafe:!0}));var Hc});var Ng=g((JB,Og)=>{"use strict";Qm();Cg();_g();var lR=di();Og.exports=lR("Promise","finally")});var Ug=g((ZB,Fg)=>{"use strict";var dR=Ng();Fg.exports=dR});var Wc=g((eV,qg)=>{"use strict";var pR=Ug();qg.exports=pR});var Kg=g(()=>{"use strict";var yR=Me(),TR=vr(),IR=wr(),ER=ma(),wR=ba();yR({target:"Array",proto:!0},{at:function(e){var t=TR(this),i=IR(t),r=ER(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});wR("at")});var Jg=g((QV,Xg)=>{"use strict";Kg();var xR=di();Xg.exports=xR("Array","at")});var ev=g((zV,Zg)=>{"use strict";var PR=Jg();Zg.exports=PR});var bt=g((GV,tv)=>{"use strict";var kR=ev();tv.exports=kR});var hl=g((WN,Dv)=>{"use strict";var qR=Ni();Dv.exports=Array.isArray||function(e){return qR(e)==="Array"}});var Vv=g((QN,Bv)=>{"use strict";var HR=TypeError,jR=9007199254740991;Bv.exports=function(s){if(s>jR)throw HR("Maximum allowed index exceeded");return s}});var Nv=g((zN,Ov)=>{"use strict";var WR=hl(),QR=wr(),zR=Vv(),GR=yr(),_v=function(s,e,t,i,r,a,n,o){for(var u=r,c=0,l=n?GR(n,o):!1,d,p;c<i;)c in t&&(d=l?l(t[c],c,e):t[c],a>0&&WR(d)?(p=QR(d),u=_v(s,e,d,p,u,a-1)-1):(zR(u+1),s[u]=d),u++),c++;return u};Ov.exports=_v});var Hv=g((GN,qv)=>{"use strict";var Fv=hl(),YR=lc(),KR=Ke(),XR=He(),JR=XR("species"),Uv=Array;qv.exports=function(s){var e;return Fv(s)&&(e=s.constructor,YR(e)&&(e===Uv||Fv(e.prototype))?e=void 0:KR(e)&&(e=e[JR],e===null&&(e=void 0))),e===void 0?Uv:e}});var Wv=g((YN,jv)=>{"use strict";var ZR=Hv();jv.exports=function(s,e){return new(ZR(s))(e===0?0:e)}});var Qv=g(()=>{"use strict";var eM=Me(),tM=Nv(),iM=Vt(),rM=vr(),aM=wr(),sM=Wv();eM({target:"Array",proto:!0},{flatMap:function(e){var t=rM(this),i=aM(t),r;return iM(e),r=sM(t,0),r.length=tM(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var zv=g(()=>{"use strict";var nM=ba();nM("flatMap")});var Yv=g((eF,Gv)=>{"use strict";Qv();zv();var oM=di();Gv.exports=oM("Array","flatMap")});var Xv=g((tF,Kv)=>{"use strict";var uM=Yv();Kv.exports=uM});var Wa=g((iF,Jv)=>{"use strict";var cM=Xv();Jv.exports=cM});var za=g((SF,iS)=>{"use strict";var dM=Ia(),pM=String;iS.exports=function(s){if(dM(s)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return pM(s)}});var ml=g((yF,rS)=>{"use strict";rS.exports=`
7
- \v\f\r                 \u2028\u2029\uFEFF`});var nS=g((TF,sS)=>{"use strict";var hM=De(),fM=li(),mM=za(),gl=ml(),aS=hM("".replace),bM=RegExp("^["+gl+"]+"),gM=RegExp("(^|[^"+gl+"])["+gl+"]+$"),bl=function(s){return function(e){var t=mM(fM(e));return s&1&&(t=aS(t,bM,"")),s&2&&(t=aS(t,gM,"$1")),t}};sS.exports={start:bl(1),end:bl(2),trim:bl(3)}});var lS=g((IF,cS)=>{"use strict";var vM=ju().PROPER,SM=Ce(),oS=ml(),uS="​…᠎";cS.exports=function(s){return SM(function(){return!!oS[s]()||uS[s]()!==uS||vM&&oS[s].name!==s})}});var vl=g((EF,dS)=>{"use strict";var yM=nS().start,TM=lS();dS.exports=TM("trimStart")?function(){return yM(this)}:"".trimStart});var hS=g(()=>{"use strict";var IM=Me(),pS=vl();IM({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==pS},{trimLeft:pS})});var mS=g(()=>{"use strict";hS();var EM=Me(),fS=vl();EM({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==fS},{trimStart:fS})});var gS=g((AF,bS)=>{"use strict";mS();var wM=di();bS.exports=wM("String","trimLeft")});var SS=g((RF,vS)=>{"use strict";var xM=gS();vS.exports=xM});var TS=g((MF,yS)=>{"use strict";var PM=SS();yS.exports=PM});var ES=g(()=>{"use strict"});var wS=g(()=>{"use strict"});var PS=g((cU,xS)=>{"use strict";var kM=Ke(),AM=Ni(),RM=He(),MM=RM("match");xS.exports=function(s){var e;return kM(s)&&((e=s[MM])!==void 0?!!e:AM(s)==="RegExp")}});var RS=g((lU,AS)=>{"use strict";var $M=Pe(),LM=Ce(),kS=$M.RegExp,CM=!LM(function(){var s=!0;try{kS(".","d")}catch(u){s=!1}var e={},t="",i=s?"dgimsy":"gimsy",r=function(u,c){Object.defineProperty(e,u,{get:function(){return t+=c,!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(kS.prototype,"flags").get.call(e);return o!==i||t!==i});AS.exports={correct:CM}});var $S=g((dU,MS)=>{"use strict";var DM=_t();MS.exports=function(){var s=DM(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 DS=g((pU,CS)=>{"use strict";var BM=ot(),VM=Pt(),_M=ca(),LS=RS(),OM=$S(),NM=RegExp.prototype;CS.exports=LS.correct?function(s){return s.flags}:function(s){return!LS.correct&&_M(NM,s)&&!VM(s,"flags")?BM(OM,s):s.flags}});var VS=g((hU,BS)=>{"use strict";var Il=De(),FM=vr(),UM=Math.floor,yl=Il("".charAt),qM=Il("".replace),Tl=Il("".slice),HM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,jM=/\$([$&'`]|\d{1,2})/g;BS.exports=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=jM;return r!==void 0&&(r=FM(r),u=HM),qM(a,u,function(c,l){var d;switch(yl(l,0)){case"$":return"$";case"&":return s;case"`":return Tl(e,0,t);case"'":return Tl(e,n);case"<":d=r[Tl(l,1,-1)];break;default:var p=+l;if(p===0)return c;if(p>o){var h=UM(p/10);return h===0?c:h<=o?i[h-1]===void 0?yl(l,1):i[h-1]+yl(l,1):c}d=i[p-1]}return d===void 0?"":d})}});var NS=g(()=>{"use strict";var WM=Me(),QM=ot(),wl=De(),_S=li(),zM=ke(),GM=Ke(),YM=PS(),qr=za(),KM=da(),XM=DS(),JM=VS(),ZM=He(),e$=xt(),t$=ZM("replace"),i$=TypeError,El=wl("".indexOf),r$=wl("".replace),OS=wl("".slice),a$=Math.max;WM({target:"String",proto:!0},{replaceAll:function(e,t){var i=_S(this),r,a,n,o,u,c,l,d,p,h,m=0,b="";if(GM(e)){if(r=YM(e),r&&(a=qr(_S(XM(e))),!~El(a,"g")))throw new i$("`.replaceAll` does not allow non-global regexes");if(n=KM(e,t$),n)return QM(n,e,i,t);if(e$&&r)return r$(qr(i),e,t)}for(o=qr(i),u=qr(e),c=zM(t),c||(t=qr(t)),l=u.length,d=a$(1,l),p=El(o,u);p!==-1;)h=c?qr(t(u,p,o)):JM(u,o,p,[],void 0,t),b+=OS(o,m,p)+h,m=p+l,p=p+d>o.length?-1:El(o,u,p+d);return m<o.length&&(b+=OS(o,m)),b}})});var US=g((bU,FS)=>{"use strict";ES();wS();NS();var s$=di();FS.exports=s$("String","replaceAll")});var HS=g((gU,qS)=>{"use strict";var n$=US();qS.exports=n$});var WS=g((vU,jS)=>{"use strict";var o$=HS();jS.exports=o$});var zS=g((SU,QS)=>{"use strict";var u$=ma(),c$=za(),l$=li(),d$=RangeError;QS.exports=function(e){var t=c$(l$(this)),i="",r=u$(e);if(r<0||r===1/0)throw new d$("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var JS=g((yU,XS)=>{"use strict";var KS=De(),p$=Au(),GS=za(),h$=zS(),f$=li(),m$=KS(h$),b$=KS("".slice),g$=Math.ceil,YS=function(s){return function(e,t,i){var r=GS(f$(e)),a=p$(t),n=r.length,o=i===void 0?" ":GS(i),u,c;return a<=n||o===""?r:(u=a-n,c=m$(o,g$(u/o.length)),c.length>u&&(c=b$(c,0,u)),s?r+c:c+r)}};XS.exports={start:YS(!1),end:YS(!0)}});var ey=g((TU,ZS)=>{"use strict";var v$=qi();ZS.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(v$)});var ty=g(()=>{"use strict";var S$=Me(),y$=JS().start,T$=ey();S$({target:"String",proto:!0,forced:T$},{padStart:function(e){return y$(this,e,arguments.length>1?arguments[1]:void 0)}})});var ry=g((wU,iy)=>{"use strict";ty();var I$=di();iy.exports=I$("String","padStart")});var sy=g((xU,ay)=>{"use strict";var E$=ry();ay.exports=E$});var oy=g((PU,ny)=>{"use strict";var w$=sy();ny.exports=w$});var fL={};ET(fL,{ChromecastState:()=>gr,HttpConnectionType:()=>tn,Observable:()=>Ht.Observable,PlaybackState:()=>qe,Player:()=>Os,PredefinedQualityLimits:()=>aa,SDK_VERSION:()=>hL,Subject:()=>Ht.Subject,Subscription:()=>Ht.Subscription,Surface:()=>rn,VERSION:()=>Xo,ValueSubject:()=>Ht.ValueSubject,VideoCodec:()=>en,VideoFormat:()=>Bt,VideoQuality:()=>Ht.VideoQuality,WebmCodecStrategy:()=>Ya,areValidLiveRecordSources:()=>cf,clientChecker:()=>H,isMobile:()=>hi});module.exports=wT(fL);var Xo="2.0.154";var qe=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(qe||{}),Bt=(w=>(w.MPEG="MPEG",w.DASH="DASH",w.DASH_SEP="DASH_SEP",w.DASH_SEP_VK="DASH_SEP",w.DASH_WEBM="DASH_WEBM",w.DASH_WEBM_AV1="DASH_WEBM_AV1",w.DASH_STREAMS="DASH_STREAMS",w.DASH_WEBM_VK="DASH_WEBM",w.DASH_ONDEMAND="DASH_ONDEMAND",w.DASH_ONDEMAND_VK="DASH_ONDEMAND",w.DASH_LIVE="DASH_LIVE",w.DASH_LIVE_CMAF="DASH_LIVE_CMAF",w.DASH_LIVE_WEBM="DASH_LIVE_WEBM",w.HLS="HLS",w.HLS_ONDEMAND="HLS_ONDEMAND",w.HLS_JS="HLS",w.HLS_FMP4="HLS_FMP4",w.HLS_LIVE="HLS_LIVE",w.HLS_LIVE_CMAF="HLS_LIVE_CMAF",w.WEB_RTC_LIVE="WEB_RTC_LIVE",w))(Bt||{}),en=(r=>(r.AV1="av1",r.VP9="vp9",r.AVC1="avc1",r.HEV1="hev1",r))(en||{});var gr=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(gr||{}),tn=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(tn||{});var rn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(rn||{}),aa=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(aa||{});var Kl=G(ji(),1),lT=G(Xe(),1);var re=require("@vkontakte/videoplayer-shared/es2018");var Xh=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 dn=class{constructor(e){this.connection$=new re.ValueSubject(void 0);this.castState$=new re.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new re.Subject;this.realCastState$=new re.ValueSubject("NOT_AVAILABLE");this.subscription=new re.Subscription;this.isDestroyed=!1;var a;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=(0,re.isNonNullable)((a=window.chrome)==null?void 0:a.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||Xh("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:re.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,a;(a=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,re.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,re.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,re.isNullable)(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((0,re.fromEvent)(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(a=i.getCurrentSession())==null?void 0:a.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return(0,re.assertNever)(r.sessionState)}})).add((0,re.merge)((0,re.fromEvent)(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,re.tap)(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),(0,re.map)(r=>r.castState)),(0,re.observableFrom)([i.getCastState()])).pipe((0,re.filterChanged)(),(0,re.map)(Sw),(0,re.tap)(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let a=r==="CONNECTED",n=(0,re.isNonNullable)(this.connection$.getValue());if(a&&!n){let c=i.getCurrentSession();(0,re.assertNonNullable)(c);let l=c.getCastDevice(),d=(u=(o=c.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;((0,re.isNullable)(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:c,castDevice:l}))}else!a&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?(0,re.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;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(a){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:re.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},Sw=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(0,re.assertNever)(s)}};var se=require("@vkontakte/videoplayer-shared/es2018");var Be=require("@vkontakte/videoplayer-shared/es2018");var Du=require("@vkontakte/videoplayer-shared/es2018");var Ae=(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:(0,Du.assertNever)(t)}return s},pi=(s,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(s);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(s);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:(0,Du.assertNever)(e)}};var hn=s=>{var d;let{source:e,format:t,meta:i,output:r}=s,a,n,o;switch(t){case"MPEG":{let p=e[t];(0,Be.assertNonNullable)(p);let h=(0,Be.getHighestQuality)(Object.keys(p));(0,Be.assertNonNullable)(h);let m=p[h];(0,Be.assertNonNullable)(m),a=m,n="video/mp4",o=pn();break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let p=e[t];(0,Be.assertNonNullable)(p),a=p.url,n="application/x-mpegurl",o=pn();break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let p=e[t];(0,Be.assertNonNullable)(p),a=p.url,n="application/dash+xml",o=pn();break}case"DASH_LIVE_CMAF":{let p=e[t];(0,Be.assertNonNullable)(p),a=p.url,n="application/dash+xml",o=Jh();break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let p=e[t];(0,Be.assertNonNullable)(p),a=Ae(p.url),n="application/x-mpegurl",o=Jh();break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let p="Unsupported format for Chromecast",h=new Error(p);throw r.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Be.ErrorCategory.VIDEO_PIPELINE,message:p,thrown:h}),h}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${t} is no longer supported`);default:return(0,Be.assertNever)(t)}let u=yw((d=i.videoId)!=null?d:a,n);u.contentUrl=a,u.streamType=o,u.metadata=Tw();let{title:c,subtitle:l}=i;return(0,Be.isNonNullable)(c)&&(u.metadata.title=c),(0,Be.isNonNullable)(l)&&(u.metadata.subtitle=l),u};function pn(){var s,e,t,i;return(i=(t=(e=(s=chrome.cast)==null?void 0:s.media)==null?void 0:e.StreamType)==null?void 0:t.BUFFERED)!=null?i:"BUFFERED"}function Jh(){var s,e,t,i;return(i=(t=(e=(s=chrome.cast)==null?void 0:s.media)==null?void 0:e.StreamType)==null?void 0:t.LIVE)!=null?i:"LIVE"}function yw(s,e){var t,i;return(i=(t=chrome.cast)==null?void 0:t.media)!=null&&i.MediaInfo?new chrome.cast.media.MediaInfo(s,e):{contentId:s,contentType:e,metadata:{title:"",subtitle:""},streamType:pn()}}function Tw(){var s,e;return(e=(s=chrome.cast)==null?void 0:s.media)!=null&&e.GenericMediaMetadata?new chrome.cast.media.GenericMediaMetadata:{images:[],metadataType:0,releaseDate:"",subtitle:"",title:"",releaseYear:1970,type:0}}var B=(s,e,t=!1)=>{let i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};var fn=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)}};var Vu=require("@vkontakte/videoplayer-shared/es2018");var In=require("@vkontakte/videoplayer-shared/es2018");var Zh=G(Xe(),1),ef=require("@vkontakte/videoplayer-shared/es2018");var mn=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isChromiumBased(){return(0,Zh.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,c=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||c||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}=(0,ef.getWindow)().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 tf=G(Xe(),1),fi=require("@vkontakte/videoplayer-shared/es2018");var hi=()=>{var s,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((s=navigator.appVersion)!=null?s:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var bn=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,tf.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 e=(0,fi.getWindow)();if(!(0,fi.isBrowserWindow)(e))return;let{userAgent:t}=e.navigator;try{this._isMobile=hi()}catch(i){console.error("DeviceChecker: calling isMobile error - ",i)}this.detectDevice(t),this.detectOS(t),this.detectDeviceDetails(t),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let e=(0,fi.getWindow)();if(!(0,fi.isBrowserWindow)(e))return;let{userAgentData:t}=e.navigator;if(t!=null&&t.getHighEntropyValues){let i=await t.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=i,i.platform&&(this._os.name=this.normalizeOSName(i.platform),i.platformVersion&&(this._os.version=this.normalizeOSVersion(i.platformVersion),this._os.full=`${this._os.name} ${this._os.version}`)),i.model&&(this._details.model=i.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",c="Unknown";if(n){let l=r[0];typeof l=="number"?l<a.length&&a[l]!==void 0&&(u=a[l]):u=l}if(o){let l=r[1];typeof l=="number"?l<a.length&&a[l]!==void 0&&(c=a[l]):l!==void 0&&(c=l)}else a[2]!==void 0?c=a[2]:a[1]!==void 0&&n&&typeof r[0]=="string"&&(c=a[1]);u=this.normalizeOSName(u),c=this.normalizeOSVersion(c,u),u==="iOS"&&/ipad/i.test(e)?u="iPadOS":u==="iPadOS"&&/ip(hone|od)/i.test(e)&&(u="iOS"),this._os={name:u,version:c||"Unknown",full:c&&c!=="Unknown"?`${u} ${c}`: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),c="Unknown";typeof o=="number"?c=a[o]!==void 0?a[o]:"Unknown":o!==void 0?c=o:a[1]!==void 0?c=a[1]:a[0]!==void 0&&(c=a[0]),c=this.normalizeModelName(c,u),this.details.vendor=u,this.details.model=c;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{let e=(0,fi.getWindow)();if(!(0,fi.isBrowserWindow)(e))return;if(this._highEntropyValues.platformVersion){let i=this._highEntropyValues.platformVersion.split(".").slice(0,2).join(".");this._iosVersion=parseFloat(i);return}if(this._os.version!=="Unknown"){let i=this._os.version.split("."),r=i.length>=2?`${i[0]}.${i[1]}`:i[0];this._iosVersion=parseFloat(r);return}let t=e.navigator.userAgent.match(/OS (\d+(_\d+)?)/i);t!=null&&t[1]&&(this._iosVersion=parseFloat(t[1].replace(/_/g,".")))}catch(e){console.error("DeviceChecker: iOS version detection error - ",e)}}};var ga=require("@vkontakte/videoplayer-shared/es2018"),gn=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in(0,ga.getWindow)()}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(){var a;let e=(0,ga.getWindow)();if(!(0,ga.isBrowserWindow)(e))return;let{navigator:t,screen:i}=e,{maxTouchPoints:r}=t;try{this._maxTouchPoints=r!=null?r:0,this._isHdr=!!((a=e.matchMedia("(dynamic-range: high)"))!=null&&a.matches),this._colorDepth=i.colorDepth}catch(n){console.error(n)}try{this._pixelRatio=e.devicePixelRatio||1,this._height=i.height,this._width=i.width,this._height=i.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(n){console.error(n)}}};var Wi=require("@vkontakte/videoplayer-shared/es2018");var ut=()=>window.ManagedMediaSource||window.MediaSource,xr=()=>{var s,e;return!!(window.ManagedMediaSource&&((e=(s=window.ManagedSourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},rf=()=>{var s,e;return!!(window.MediaSource&&((e=(s=window.SourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},vn=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var af,Iw=(af=(0,Wi.getWindow)().document)==null?void 0:af.createElement("video"),Ew='video/mp4; codecs="avc1.42000a,mp4a.40.2"',ww='video/mp4; codecs="hev1.1.6.L93.B0"',sf='video/webm; codecs="vp09.00.10.08"',nf='video/webm; codecs="av01.0.00M.08"',xw='audio/mp4; codecs="mp4a.40.2"',Pw='audio/webm; codecs="opus"',of,kw=async()=>{let s=(0,Wi.getWindow)();if(!(0,Wi.isBrowserWindow)(s))return;let e={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[t,i]=await Promise.all([s.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:nf}}),s.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:sf}})]);of={DASH_WEBM_AV1:t,DASH_WEBM:i}};kw().catch(s=>{console.log(Iw),console.error(s)});var Sn=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 of}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var i,r,a,n,o,u,c,l,d,p,h,m,b,S,v,y,x,w,M,_;let e=(0,Wi.getWindow)();if(!(0,Wi.isBrowserWindow)(e))return;let t=e.document;this._video=t.createElement("video");try{this._protocols={mms:xr(),mse:rf(),hls:!!((r=(i=this._video).canPlayType)!=null&&r.call(i,"application/x-mpegurl")||(n=(a=this._video).canPlayType)!=null&&n.call(a,"vnd.apple.mpegURL")),webrtc:!!e.RTCPeerConnection,ws:!!e.WebSocket},this._containers={mp4:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/mp4")),webm:!!((l=(c=this._video).canPlayType)!=null&&l.call(c,"video/webm")),cmaf:!0};let q=!!((p=(d=ut())==null?void 0:d.isTypeSupported)!=null&&p.call(d,Ew)),O=!!((m=(h=ut())==null?void 0:h.isTypeSupported)!=null&&m.call(h,ww)),j=!!((S=(b=ut())==null?void 0:b.isTypeSupported)!=null&&S.call(b,xw));this._codecs={h264:q,h265:O,vp9:!!((y=(v=ut())==null?void 0:v.isTypeSupported)!=null&&y.call(v,sf)),av1:!!((w=(x=ut())==null?void 0:x.isTypeSupported)!=null&&w.call(x,nf)),aac:j,opus:!!((_=(M=ut())==null?void 0:M.isTypeSupported)!=null&&_.call(M,Pw)),mpeg:(q||O)&&j},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(q){console.error(q)}try{this.destroyVideoElement()}catch(q){console.error("Error destroying video element:",q)}}destroyVideoElement(){var t;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);(t=this._video.parentNode)==null||t.replaceChild(e,this._video),this._video=null}};var Tn=require("@vkontakte/videoplayer-shared/es2018");var uf="audio/mpeg",yn=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var i,r,a,n;let e=(0,Tn.getWindow)();if(!(0,Tn.isBrowserWindow)(e))return;let t=e.document;this._audio=t.createElement("audio");try{this._containers={mpeg:!!((r=(i=this._audio).canPlayType)!=null&&r.call(i,uf))},this._codecs={mp3:!!((n=(a=ut())==null?void 0:a.isTypeSupported)!=null&&n.call(a,uf))}}catch(o){console.error(o)}try{this.destroyAudioElement()}catch(o){console.error("Error destroying audio element:",o)}}destroyAudioElement(){var t;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);(t=this._audio.parentNode)==null||t.replaceChild(e,this._audio),this._audio=null}};var Bu=class{constructor(){this.isInited$=new In.ValueSubject(!1);this._displayChecker=new gn,this._deviceChecker=new bn(this._displayChecker),this._browserChecker=new mn,this._videoChecker=new Sn(this._deviceChecker,this._browserChecker),this._audioChecker=new yn,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(){(0,In.isBrowserWindow)()&&(this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0))}},H=new Bu;var _u=s=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=H.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(0,Vu.assertNever)(o)}})},va=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(0,Vu.assertNever)(s)}},cf=s=>{let t=Object.keys(s).filter(i=>!va(i));return _u(t).length>0};var Sa=class{constructor(e){this.subscription=new se.Subscription;this.sessionId$=new se.ValueSubject(null);this.mediaSessionId$=new se.ValueSubject(null);this.contentId$=new se.ValueSubject(null);this.isMobile=hi();this.mobileVolumeState={muted:!1,volume:0};this.media=null;this.lastRequestedVolume=null;this.syncMediaState=e=>{var a,n,o;if((0,se.isNullable)(e))return;this.media=e,this.mediaSessionId$.next((a=e.mediaSessionId)!=null?a:null);let t=(n=e.media)==null?void 0:n.contentId;t&&this.contentId$.next(t),this.syncPlaybackState(e);let i=(o=e.media)==null?void 0:o.duration;(0,se.isNonNullable)(i)&&this.params.output.duration$.next(Math.max(0,i));let r=e.currentTime;if((0,se.isNonNullable)(r)){this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.params.output.position$.next(r);let c=this.params.output.isLive$.getValue();e.playerState==="PLAYING"&&!c?this.progressTicker.start(r):this.progressTicker.pause()}};this.params=e,this.progressTicker=new fn(e),this.log=this.params.dependencies.logger.createComponentLog("ChromecastPresentationApiProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(va(e.format)),this.subscribe()}subscribe(){let e=r=>{var a;this.params.output.error$.next({category:se.ErrorCategory.WTF,id:"ChromecastPresentationApiProvider",message:(a=r==null?void 0:r.message)!=null?a:"Unknown error",thrown:r})};this.subscription.add(this.params.chromecastConnector.message$.pipe((0,se.filter)(r=>!!r)).subscribe(r=>{this.handleMessage(r)},e)),this.subscription.add(this.sessionId$.pipe((0,se.filter)(se.isNonNullable),(0,se.filterChanged)(),(0,se.debounce)(0)).subscribe(()=>{this.loadMedia()},e));let t=this.contentId$.pipe((0,se.filterChanged)(),(0,se.map)(Boolean));this.subscription.add((0,se.combine)({seekState:this.params.desiredState.seekState.stateChangeEnded$,mediaLoaded:t}).pipe((0,se.filter)(({mediaLoaded:r})=>r)).subscribe(()=>{let r=this.params.desiredState.seekState.getState();r.state==="requested"&&this.seek(r.position/1e3)},e));let i=(0,se.combine)({playbackState:this.params.desiredState.playbackState.stateChangeStarted$,mediaLoaded:t});this.subscription.add(i.pipe((0,se.filter)(({mediaLoaded:r})=>r),(0,se.debounce)(0)).subscribe(()=>{this.syncPlayback()},e)),this.subscription.add(i.pipe((0,se.filter)(({mediaLoaded:r,playbackState:{from:a,to:n}})=>!r&&a==="stopped"&&n==="playing")).subscribe(()=>{this.loadMedia()},e)),this.subscription.add((0,se.combine)({volumeState:this.params.desiredState.volume.stateChangeStarted$.pipe((0,se.debounce)(30)),mediaLoaded:t}).pipe((0,se.filter)(({mediaLoaded:r})=>r)).subscribe(({volumeState:r})=>{let{muted:a,volume:n}=r.to;this.setVolume(n,a)},e))}handleMessage(e){var t,i,r,a,n,o;switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId);let u=(i=(t=e.message)==null?void 0:t.media)==null?void 0:i[0];this.syncMediaState(u);let c=(r=e.message)==null?void 0:r.receiver.volume;this.syncVolumeState(c)}break;case"v2_message":{switch((a=e.message)==null?void 0:a.type){case"MEDIA_STATUS":{let u=(o=(n=e.message)==null?void 0:n.status)==null?void 0:o[0];this.syncMediaState(u);break}}break}}}loadMedia(){var o;let e=hn(this.params),t=(o=this.media)==null?void 0:o.currentTime,i=this.params.desiredState.seekState.getState(),r=t!=null?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();(0,se.assertNonNullable)(e,"play on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PLAY",mediaSessionId:e,customData:null})}pause(){let e=this.mediaSessionId$.getValue();(0,se.assertNonNullable)(e,"pause on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PAUSE",mediaSessionId:e,customData:null})}seek(e){let t=this.mediaSessionId$.getValue();(0,se.assertNonNullable)(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":B(this.params.desiredState.playbackState,"paused");break;case"PLAYING":B(this.params.desiredState.playbackState,"playing");break;case"IDLE":{t==="FINISHED"?(this.params.output.endedEvent$.next(),B(this.params.desiredState.playbackState,"stopped"),this.contentId$.next(null)):B(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((0,se.isNullable)(e))return;let{level:t,muted:i}=e,r={muted:i!=null?i:!1,volume:t!=null?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()}};var he=require("@vkontakte/videoplayer-shared/es2018");var lf=s=>({castDevice:{friendlyName:s},remotePlayer:{},remotePlayerController:{},session:{}}),df=()=>String(Date.now())+String(Math.floor(Math.random()*1e5));var ya=class{constructor(e){this.capabilities=["WEB"];this.presentationRequest$=new he.ValueSubject(null);this.sessionId$=new he.ValueSubject(null);this.broadcastChannel=new BroadcastChannel("vk_player_chromecast_events");this.subscription=new he.Subscription;this.subscriptionEvents=new he.Subscription;this.isDestroyed=!1;this.sequenceNumber=0;this.presentationAvailable$=new he.ValueSubject(!1);this.presentationConnection$=new he.ValueSubject(null);this.message$=new he.ValueSubject(null);this.friendlyName$=new he.ValueSubject(null);this.errorEvent$=new he.Subject;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((0,he.fromEvent)(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(){var e;this.log({message:"connect"});try{this.presentationRequest$.getValue()||(this.log({message:"reinitPresentation"}),this.reinitPresentation(!1));let t=this.presentationRequest$.getValue();(0,he.assertNonNullable)(t,"connect with null presentationRequest");let i=await t.start();this.handleConnection(i)}catch(t){switch(t==null?void 0:t.name){case"AbortError":case"NotAllowedError":break;default:this.errorEvent$.next({category:he.ErrorCategory.WTF,id:"ChromecastPresentationApiConnector",message:(e=t==null?void 0:t.message)!=null?e:"connect error",thrown:t});break}}}subscribe(){this.subscription.add((0,he.fromEvent)(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((0,he.tap)(e=>{this.log({message:`presentationConnection$: ${!!e}`})}),(0,he.filter)(e=>!!e)).subscribe(e=>{let t=(0,he.fromEvent)(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=(0,he.fromEvent)(e,"connect").subscribe(()=>{this.send("client_connect")}),r=(0,he.fromEvent)(e,"close").subscribe(a=>{switch(a.reason){case"error":this.errorEvent$.next({category:he.ErrorCategory.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==null?void 0:t.state)==="connected"&&(t==null||t.send(e))}catch(t){this.errorEvent$.next({category:he.ErrorCategory.WTF,id:"ChromecastPresentationApiConnector",message:"PresentationConnection send error",data:{message:e},thrown:t})}}handleMessage(e){var t;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":((t=e.message)==null?void 0:t.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]||df()}resetSubscriptionEvents(){this.subscriptionEvents.unsubscribe(),this.subscriptionEvents=new he.Subscription}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))}};var je=require("@vkontakte/videoplayer-shared/es2018");var Gt=class s{constructor(e){this.subscription=new je.Subscription;this.connection$=new je.ValueSubject(void 0);this.castState$=new je.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new je.Subject;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 ya({appId:e.receiverApplicationId,logger:e.dependencies.logger}),this.subscribe())}static isSupported(){return"chrome"in window&&"presentation"in navigator&&"BroadcastChannel"in window}subscribe(){(0,je.assertNonNullable)(this.chromecastConnector,"subscribe with null chromecastConnector"),this.subscription.add(this.chromecastConnector.errorEvent$.subscribe(this.errorEvent$));let e=(0,je.combine)({connection:this.chromecastConnector.presentationConnection$,available:this.chromecastConnector.presentationAvailable$,friendlyName:this.chromecastConnector.friendlyName$.pipe((0,je.filterChanged)())});this.subscription.add(e.pipe((0,je.map)(({connection:t,friendlyName:i})=>!!(t&&i)),(0,je.filterChanged)()).subscribe(t=>{var r,a;let i=(a=(r=this.chromecastConnector)==null?void 0:r.friendlyName$.getValue())!=null?a:"";this.connection$.next(t?lf(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(){var e;this.log({message:"connect"}),(e=this.chromecastConnector)==null||e.connect()}disconnect(){var e;this.log({message:"disconnect"}),(e=this.chromecastConnector)==null||e.disconnect()}async stopMedia(){var e;this.log({message:"stopMedia"}),(e=this.chromecastConnector)==null||e.stopMedia()}toggleConnection(){var t;let e=!!((t=this.chromecastConnector)!=null&&t.presentationConnection$.getValue());this.log({message:`toggleConnection: isConnected - ${e}`}),e?this.disconnect():this.connect()}setVolume(e){}setMuted(e){}destroy(){var e;this.log({message:"destroy"}),(e=this.chromecastConnector)==null||e.destroy(),this.subscription.unsubscribe()}};var Wl=G(Xe(),1),Ql=G(mi(),1),Xy=G(sc(),1);var jg=G(Wc(),1);var Nt=require("@vkontakte/videoplayer-shared/es2018"),ae=class{constructor(e){this.transitionStarted$=new Nt.Subject;this.transitionEnded$=new Nt.Subject;this.transitionUpdated$=new Nt.Subject;this.forceChanged$=new Nt.Subject;this.stateChangeStarted$=(0,Nt.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,Nt.merge)(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||(0,Nt.isNonNullable)(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};var ue=require("@vkontakte/videoplayer-shared/es2018");var hR=5,fR=5,mR=500,Hg=7e3,Ca=class{constructor(e){this.subscription=new ue.Subscription;this.loadMediaTimeoutSubscription=new ue.Subscription;this.videoState=new ae("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==null?void 0: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:(0,ue.assertNever)(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,ue.assertNever)(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,ue.assertNever)(e)}break}default:(0,ue.assertNever)(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(va(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 ue.Subscription;this.subscription.add(e),this.subscription.add((0,ue.merge)(this.videoState.stateChangeStarted$.pipe((0,ue.map)(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe((0,ue.map)(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 ue.Subject;e.add(r.pipe((0,ue.debounce)(mR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add((0,ue.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-a)>hR)&&r.next(o),a=o})),e.add((0,ue.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,ue.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,ue.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,ue.fromEvent)(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<fR&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),B(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:(0,ue.assertNever)(n)}}),t((0,ue.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t((0,ue.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=(0,ue.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,ue.observableFrom)(["init"])).pipe((0,ue.debounce)(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),B(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=hn(this.params),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),B(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&B(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,a;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(a=e.muted)!=null?a: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((0,ue.timeout)(Hg).subscribe(()=>a(`timeout(${Hg})`)))});(0,jg.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:ue.ErrorCategory.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var nl=G(Xe(),1);var Da=require("@vkontakte/videoplayer-shared/es2018");var Wg=require("@vkontakte/videoplayer-shared/es2018"),Qg=(s,e)=>{try{s.pause(),s.playbackRate=0,(0,Wg.clearVideoElement)(s,e),s.remove()}catch(t){console.error(t)}};var Gn=require("@vkontakte/videoplayer-shared/es2018"),Qc=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)}},zn=(0,Da.getWindow)(),zc=zn.WeakMap?new zn.WeakMap:new Qc,Gc=zn.WeakMap?new zn.WeakMap:new Map,bR=(s,e=20)=>{let t=0;return(0,Gn.fromEvent)(s,"ratechange").subscribe(i=>{t++,t>=e&&(s.currentTime=s.currentTime,t=0)})},Je=(s,{audioVideoSyncRate:e,disableYandexPiP:t,clearVideoElementInnerHTML:i})=>{let r=s.querySelector("video"),a=!!r;r?(0,Da.clearVideoElement)(r,i):(r=document.createElement("video"),s.appendChild(r)),zc.set(r,a);let n=new Gn.Subscription;return n.add(bR(r,e)),Gc.set(r,n),r.setAttribute("crossorigin","anonymous"),r.setAttribute("playsinline","playsinline"),t&&r.setAttribute("x-yandex-pip","false"),r.controls=!1,r.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),r},Ze=(s,e=!1,t=!1)=>{let i=Gc.get(s);i==null||i.unsubscribe(),Gc.delete(s);let r=zc.get(s);zc.delete(s),r||e?(0,Da.clearVideoElement)(s,t):Qg(s,t)};var Yc=G(ji(),1),z=require("@vkontakte/videoplayer-shared/es2018");var gi=require("@vkontakte/videoplayer-shared/es2018"),Yn=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{let n=s.getState(),o=e(),u=(0,gi.isNullable)(r),c=new gi.Subscription;return r&&c.add(r.subscribe(l=>{let d=s.getState();i(l,d)&&s.setState(l)},a)),i(o,n)||(t(n),u&&s.setState(n)),c.add(s.stateChangeStarted$.subscribe(l=>{t(l.to),u&&s.setState(l.to)},a)),c},Ft=(s,e,t)=>Yn(e,()=>s.loop,i=>{(0,gi.isNonNullable)(i)&&(s.loop=i)},{onError:t}),et=(s,e,t,i)=>Yn(e,()=>({muted:s.muted,volume:s.volume}),r=>{(0,gi.isNonNullable)(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),ft=(s,e,t,i)=>Yn(e,()=>s.playbackRate,r=>{(0,gi.isNonNullable)(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Ba=Yn;var gR=s=>["__",s.language,s.label].join("|"),vR=(s,e)=>{if(s.id===e)return!0;let[t,i,r]=e.split("|");return s.language===i&&s.label===r},Kc=class s{constructor(e){this.available$=new z.Subject;this.current$=new z.ValueSubject(void 0);this.error$=new z.Subject;this.subscription=new z.Subscription;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:z.ErrorCategory.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(Ba(t.internalTextTracks,()=>(0,Yc.default)(this.internalTracks),a=>{(0,z.isNonNullable)(a)&&this.setInternal(a)},{equal:(a,n)=>(0,z.isNonNullable)(a)&&(0,z.isNonNullable)(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,z.map)(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Ba(t.externalTextTracks,()=>(0,Yc.default)(this.externalTracks),a=>{(0,z.isNonNullable)(a)&&this.setExternal(a)},{equal:(a,n)=>(0,z.isNonNullable)(a)&&(0,z.isNonNullable)(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,z.map)(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Ba(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(Ba(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){(0,z.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,z.fromEvent)(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add((0,z.merge)((0,z.fromEvent)(e,"addtrack"),(0,z.fromEvent)(e,"removetrack"),(0,z.observableFrom)(["init"])).pipe((0,z.map)(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),(0,z.filterChanged)((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add((0,z.merge)((0,z.fromEvent)(e,"change"),(0,z.observableFrom)(["init"])).pipe((0,z.map)(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),(0,z.map)(i=>i&&this.htmlTextTrackToITextTrack(i).id),(0,z.filterChanged)()).subscribe(this.current$));let t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)==null?void 0:r.activeCues)!=null?a:null)};this.subscription.add((0,z.fromEvent)(e,"addtrack").subscribe(i=>{var a,n;(a=i.track)==null||a.addEventListener("cuechange",t);let r=o=>{var c,l,d,p,h;let u=(l=(c=o.target)==null?void 0:c.cues)!=null?l:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add((0,z.fromEvent)(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.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;(0,z.isNonNullable)(t.align)&&(r.align=t.align),(0,z.isNonNullable)(t.position)&&(r.position=t.position),(0,z.isNonNullable)(t.size)&&(r.size=t.size),(0,z.isNonNullable)(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,z.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(s.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,c,l,d;let{language:t,label:i}=e,r=e.id?e.id:gR(e),a=this.externalTracks.has(r),n=(c=a?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?c:r.includes("auto");return a?{id:r,type:"external",isAuto:n,language:t,label:i,url:(l=this.externalTracks.get(r))==null?void 0:l.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(d=this.internalTracks.get(r))==null?void 0:d.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){(0,z.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,z.isNullable)(e)||!vR(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){(0,z.assertNonNullable)(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){(0,z.assertNonNullable)(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},mt=Kc;var Xi=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 zg=s=>{let e=s;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},Xc=s=>{let e=zg(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},Gg=s=>{let e=zg(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};var L=require("@vkontakte/videoplayer-shared/es2018");var SR=3,Yg=(s,e,t=SR)=>{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 tt=s=>{let e=V=>(0,L.fromEvent)(s,V).pipe((0,L.mapTo)(void 0),(0,L.shareReplay)(1)),t=new L.Subscription,i=()=>t.unsubscribe(),r=(0,L.merge)((0,L.fromEvent)(s,"progress"),(0,L.fromEvent)(s,"timeupdate")).pipe((0,L.map)(()=>Yg(s.buffered,s.currentTime)),(0,L.shareReplay)(1)),a=H.browser.isSafari?(0,L.combine)({play:e("play").pipe((0,L.once)()),playing:e("playing")}).pipe((0,L.mapTo)(void 0),(0,L.shareReplay)(1)):e("playing"),n=(0,L.fromEvent)(s,"volumechange").pipe((0,L.map)(()=>({muted:s.muted,volume:s.volume})),(0,L.shareReplay)(1)),o=(0,L.fromEvent)(s,"ratechange").pipe((0,L.map)(()=>s.playbackRate),(0,L.shareReplay)(1)),u=(0,L.fromEvent)(s,"error").pipe((0,L.filter)(()=>!!(s.error||s.played.length)),(0,L.map)(()=>{var Q;let V=s.error;return{id:V?`MediaError#${V.code}`:"HtmlVideoError",category:L.ErrorCategory.VIDEO_PIPELINE,message:V?V.message:"Error event from HTML video element",thrown:(Q=s.error)!=null?Q:void 0}}),(0,L.shareReplay)(1)),c=(0,L.fromEvent)(s,"timeupdate").pipe((0,L.map)(()=>s.currentTime),(0,L.shareReplay)(1)),l=["waiting","seeking","seeked","timeupdate"],d=new L.Subject,p=.3,h;t.add((0,L.merge)(...l.map(V=>(0,L.fromEvent)(s,V))).subscribe(V=>{let Q=s.currentTime;s.loop&&(0,L.isNonNullable)(h)&&(0,L.isNonNullable)(Q)&&h>=s.duration-p&&Q<=p&&d.next(h),h=Q}));let m=e("pause").pipe((0,L.filter)(()=>!s.error&&h!==s.duration),(0,L.shareReplay)(1)),b=(0,L.fromEvent)(s,"enterpictureinpicture").pipe((0,L.shareReplay)(1)),S=(0,L.fromEvent)(s,"leavepictureinpicture").pipe((0,L.shareReplay)(1)),v=new L.ValueSubject(Gg(s));t.add(b.subscribe(()=>v.next(!0))),t.add(S.subscribe(()=>v.next(!1)));let y=new L.ValueSubject(Xc(s)),x=(0,L.fromEvent)(s,"fullscreenchange").pipe((0,L.shareReplay)(1));t.add(x.pipe((0,L.map)(()=>Xc(s))).subscribe(y));let w=.1,M=1e3,_=(0,L.fromEvent)(s,"timeupdate").pipe((0,L.map)(V=>s.duration-s.currentTime<w),(0,L.filterChanged)(),(0,L.shareReplay)(1)),q=(0,L.merge)(_.pipe((0,L.filter)(V=>!s.loop&&V)),(0,L.fromEvent)(s,"ended")).pipe((0,L.throttle)(M),(0,L.mapTo)(void 0),(0,L.shareReplay)(1)),j=(0,L.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(V=>(0,L.fromEvent)(s,V)),_.pipe((0,L.map)(V=>({type:V?"ended":"unknown"})))).pipe((0,L.map)(V=>H.browser.isFirefox&&V.type==="ended"?s.readyState<2:s.readyState<3),(0,L.filterChanged)(),(0,L.shareReplay)(1));return{playing$:a,pause$:m,canplay$:e("canplay"),ended$:q,looped$:d,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:(0,L.fromEvent)(s,"durationchange").pipe((0,L.map)(()=>s.duration),(0,L.shareReplay)(1)),isBuffering$:j,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:v,inFullscreen$:y,enterPip$:b,leavePip$:S,destroy:i}};var Kt=require("@vkontakte/videoplayer-shared/es2018"),vi=s=>{switch(s){case"mobile":return Kt.VideoQuality.Q_144P;case"lowest":return Kt.VideoQuality.Q_240P;case"low":return Kt.VideoQuality.Q_360P;case"sd":case"medium":return Kt.VideoQuality.Q_480P;case"hd":case"high":return Kt.VideoQuality.Q_720P;case"fullhd":case"full":return Kt.VideoQuality.Q_1080P;case"quadhd":case"quad":return Kt.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return Kt.VideoQuality.Q_2160P}};var Ge=G(bt(),1),Zc=G(Xe(),1),Ji=G(mi(),1),D=require("@vkontakte/videoplayer-shared/es2018");var Jc=!1,Xt={},iv=s=>{Jc=s},rv=()=>{Xt={}},av=s=>{s(Xt)},Va=(s,e)=>{var t;Jc&&(Xt.meta=(t=Xt.meta)!=null?t:{},Xt.meta[s]=e)},ze=class{constructor(e){this.name=e}next(e){var i,r;if(!Jc)return;Xt.series=(i=Xt.series)!=null?i:{};let t=(r=Xt.series[this.name])!=null?r:[];t.push([Date.now(),e]),Xt.series[this.name]=t}};var $e=require("@vkontakte/videoplayer-shared/es2018");function sv(s,e,t){return!s.max&&s.min===e?"high_quality":!s.min&&s.max===t?"traffic_saving":"unknown"}function Br(s,e,t){return(0,$e.isNullable)(s)||(0,$e.isNonNullable)(s.min)&&(0,$e.isNonNullable)(s.max)&&(0,$e.isLower)(s.max,s.min)||(0,$e.isNonNullable)(s.min)&&e&&(0,$e.isHigher)(s.min,e)||(0,$e.isNonNullable)(s.max)&&t&&(0,$e.isLower)(s.max,t)}function nv({limits:s,highestAvailableHeight:e,lowestAvailableHeight:t}){return Br({max:s!=null&&s.max?(0,$e.videoHeightToQuality)(s.max):void 0,min:s!=null&&s.min?(0,$e.videoHeightToQuality)(s.min):void 0},e?(0,$e.videoHeightToQuality)(e):void 0,t?(0,$e.videoHeightToQuality)(t):void 0)}var dv=new ze("best_bitrate"),Xn=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;var Vr=s=>(e,t)=>s*(Number(e.bitrate)-Number(t.bitrate)),Si=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,D.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Jn='Assertion "ABR Tracks is empty array" failed',Kn=new WeakMap,ov=new WeakMap,uv=new WeakMap,_a=(s,e,t,i)=>{var u;let r=[...e].sort(Vr(1)),a=[...t].sort(Vr(1)),n=a.filter(c=>(0,D.isNonNullable)(c.bitrate)&&(0,D.isNonNullable)(s.bitrate)?s.bitrate/c.bitrate>i:!0),o=(u=(0,Ge.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,Ge.default)(a,-1);return o&&(0,Zc.default)(n,o)?o:n.length?(0,Ge.default)(n,-1):(0,Ge.default)(a,0)},Oa=(s,e,t,i)=>{var u;let r=Kn.get(e);r||(r=[...e].sort(Vr(1)),Kn.set(e,r));let a=Kn.get(t);a||(a=[...t].sort(Vr(1)),Kn.set(t,a));let n=uv.get(s);n||(n=a.filter(c=>(0,D.isNonNullable)(c.bitrate)&&(0,D.isNonNullable)(s.bitrate)?s.bitrate/c.bitrate>i:!0),uv.set(s,n));let o=(u=(0,Ge.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,Ge.default)(a,-1);return o&&(0,Zc.default)(n,o)?o:n.length?(0,Ge.default)(n,-1):(0,Ge.default)(a,0)},cv=s=>"quality"in s,Zn=(s,e,t,i)=>{var n;let r=(0,D.isNonNullable)((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&(0,D.isNonNullable)(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?s.trackCooldownIncreaseQuality:s.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&(0,D.now)()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!a&&i.recordSelection(t),a&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=cv(o)?"video":"audio",c=cv(o)?o.quality:o.bitrate;return e({message:`
7
+ \v\f\r                 \u2028\u2029\uFEFF`});var nS=g((TF,sS)=>{"use strict";var hM=De(),fM=li(),mM=za(),gl=ml(),aS=hM("".replace),bM=RegExp("^["+gl+"]+"),gM=RegExp("(^|[^"+gl+"])["+gl+"]+$"),bl=function(s){return function(e){var t=mM(fM(e));return s&1&&(t=aS(t,bM,"")),s&2&&(t=aS(t,gM,"$1")),t}};sS.exports={start:bl(1),end:bl(2),trim:bl(3)}});var lS=g((IF,cS)=>{"use strict";var vM=ju().PROPER,SM=Ce(),oS=ml(),uS="​…᠎";cS.exports=function(s){return SM(function(){return!!oS[s]()||uS[s]()!==uS||vM&&oS[s].name!==s})}});var vl=g((EF,dS)=>{"use strict";var yM=nS().start,TM=lS();dS.exports=TM("trimStart")?function(){return yM(this)}:"".trimStart});var hS=g(()=>{"use strict";var IM=Me(),pS=vl();IM({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==pS},{trimLeft:pS})});var mS=g(()=>{"use strict";hS();var EM=Me(),fS=vl();EM({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==fS},{trimStart:fS})});var gS=g((AF,bS)=>{"use strict";mS();var wM=di();bS.exports=wM("String","trimLeft")});var SS=g((RF,vS)=>{"use strict";var xM=gS();vS.exports=xM});var TS=g((MF,yS)=>{"use strict";var PM=SS();yS.exports=PM});var ES=g(()=>{"use strict"});var wS=g(()=>{"use strict"});var PS=g((cU,xS)=>{"use strict";var kM=Ke(),AM=Ni(),RM=He(),MM=RM("match");xS.exports=function(s){var e;return kM(s)&&((e=s[MM])!==void 0?!!e:AM(s)==="RegExp")}});var RS=g((lU,AS)=>{"use strict";var $M=Pe(),LM=Ce(),kS=$M.RegExp,CM=!LM(function(){var s=!0;try{kS(".","d")}catch(u){s=!1}var e={},t="",i=s?"dgimsy":"gimsy",r=function(u,c){Object.defineProperty(e,u,{get:function(){return t+=c,!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(kS.prototype,"flags").get.call(e);return o!==i||t!==i});AS.exports={correct:CM}});var $S=g((dU,MS)=>{"use strict";var DM=_t();MS.exports=function(){var s=DM(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 DS=g((pU,CS)=>{"use strict";var BM=ot(),VM=Pt(),_M=ca(),LS=RS(),OM=$S(),NM=RegExp.prototype;CS.exports=LS.correct?function(s){return s.flags}:function(s){return!LS.correct&&_M(NM,s)&&!VM(s,"flags")?BM(OM,s):s.flags}});var VS=g((hU,BS)=>{"use strict";var Il=De(),FM=vr(),UM=Math.floor,yl=Il("".charAt),qM=Il("".replace),Tl=Il("".slice),HM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,jM=/\$([$&'`]|\d{1,2})/g;BS.exports=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=jM;return r!==void 0&&(r=FM(r),u=HM),qM(a,u,function(c,l){var d;switch(yl(l,0)){case"$":return"$";case"&":return s;case"`":return Tl(e,0,t);case"'":return Tl(e,n);case"<":d=r[Tl(l,1,-1)];break;default:var p=+l;if(p===0)return c;if(p>o){var h=UM(p/10);return h===0?c:h<=o?i[h-1]===void 0?yl(l,1):i[h-1]+yl(l,1):c}d=i[p-1]}return d===void 0?"":d})}});var NS=g(()=>{"use strict";var WM=Me(),QM=ot(),wl=De(),_S=li(),zM=ke(),GM=Ke(),YM=PS(),qr=za(),KM=da(),XM=DS(),JM=VS(),ZM=He(),e$=xt(),t$=ZM("replace"),i$=TypeError,El=wl("".indexOf),r$=wl("".replace),OS=wl("".slice),a$=Math.max;WM({target:"String",proto:!0},{replaceAll:function(e,t){var i=_S(this),r,a,n,o,u,c,l,d,p,h,m=0,b="";if(GM(e)){if(r=YM(e),r&&(a=qr(_S(XM(e))),!~El(a,"g")))throw new i$("`.replaceAll` does not allow non-global regexes");if(n=KM(e,t$),n)return QM(n,e,i,t);if(e$&&r)return r$(qr(i),e,t)}for(o=qr(i),u=qr(e),c=zM(t),c||(t=qr(t)),l=u.length,d=a$(1,l),p=El(o,u);p!==-1;)h=c?qr(t(u,p,o)):JM(u,o,p,[],void 0,t),b+=OS(o,m,p)+h,m=p+l,p=p+d>o.length?-1:El(o,u,p+d);return m<o.length&&(b+=OS(o,m)),b}})});var US=g((bU,FS)=>{"use strict";ES();wS();NS();var s$=di();FS.exports=s$("String","replaceAll")});var HS=g((gU,qS)=>{"use strict";var n$=US();qS.exports=n$});var WS=g((vU,jS)=>{"use strict";var o$=HS();jS.exports=o$});var zS=g((SU,QS)=>{"use strict";var u$=ma(),c$=za(),l$=li(),d$=RangeError;QS.exports=function(e){var t=c$(l$(this)),i="",r=u$(e);if(r<0||r===1/0)throw new d$("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var JS=g((yU,XS)=>{"use strict";var KS=De(),p$=Au(),GS=za(),h$=zS(),f$=li(),m$=KS(h$),b$=KS("".slice),g$=Math.ceil,YS=function(s){return function(e,t,i){var r=GS(f$(e)),a=p$(t),n=r.length,o=i===void 0?" ":GS(i),u,c;return a<=n||o===""?r:(u=a-n,c=m$(o,g$(u/o.length)),c.length>u&&(c=b$(c,0,u)),s?r+c:c+r)}};XS.exports={start:YS(!1),end:YS(!0)}});var ey=g((TU,ZS)=>{"use strict";var v$=qi();ZS.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(v$)});var ty=g(()=>{"use strict";var S$=Me(),y$=JS().start,T$=ey();S$({target:"String",proto:!0,forced:T$},{padStart:function(e){return y$(this,e,arguments.length>1?arguments[1]:void 0)}})});var ry=g((wU,iy)=>{"use strict";ty();var I$=di();iy.exports=I$("String","padStart")});var sy=g((xU,ay)=>{"use strict";var E$=ry();ay.exports=E$});var oy=g((PU,ny)=>{"use strict";var w$=sy();ny.exports=w$});var fL={};ET(fL,{ChromecastState:()=>gr,HttpConnectionType:()=>tn,Observable:()=>Ht.Observable,PlaybackState:()=>qe,Player:()=>Os,PredefinedQualityLimits:()=>aa,SDK_VERSION:()=>hL,Subject:()=>Ht.Subject,Subscription:()=>Ht.Subscription,Surface:()=>rn,VERSION:()=>Xo,ValueSubject:()=>Ht.ValueSubject,VideoCodec:()=>en,VideoFormat:()=>Bt,VideoQuality:()=>Ht.VideoQuality,WebmCodecStrategy:()=>Ya,areValidLiveRecordSources:()=>cf,clientChecker:()=>H,isMobile:()=>hi});module.exports=wT(fL);var Xo="2.0.155";var qe=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(qe||{}),Bt=(w=>(w.MPEG="MPEG",w.DASH="DASH",w.DASH_SEP="DASH_SEP",w.DASH_SEP_VK="DASH_SEP",w.DASH_WEBM="DASH_WEBM",w.DASH_WEBM_AV1="DASH_WEBM_AV1",w.DASH_STREAMS="DASH_STREAMS",w.DASH_WEBM_VK="DASH_WEBM",w.DASH_ONDEMAND="DASH_ONDEMAND",w.DASH_ONDEMAND_VK="DASH_ONDEMAND",w.DASH_LIVE="DASH_LIVE",w.DASH_LIVE_CMAF="DASH_LIVE_CMAF",w.DASH_LIVE_WEBM="DASH_LIVE_WEBM",w.HLS="HLS",w.HLS_ONDEMAND="HLS_ONDEMAND",w.HLS_JS="HLS",w.HLS_FMP4="HLS_FMP4",w.HLS_LIVE="HLS_LIVE",w.HLS_LIVE_CMAF="HLS_LIVE_CMAF",w.WEB_RTC_LIVE="WEB_RTC_LIVE",w))(Bt||{}),en=(r=>(r.AV1="av1",r.VP9="vp9",r.AVC1="avc1",r.HEV1="hev1",r))(en||{});var gr=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(gr||{}),tn=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(tn||{});var rn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(rn||{}),aa=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(aa||{});var Kl=G(ji(),1),lT=G(Xe(),1);var re=require("@vkontakte/videoplayer-shared/es2018");var Xh=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 dn=class{constructor(e){this.connection$=new re.ValueSubject(void 0);this.castState$=new re.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new re.Subject;this.realCastState$=new re.ValueSubject("NOT_AVAILABLE");this.subscription=new re.Subscription;this.isDestroyed=!1;var a;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=(0,re.isNonNullable)((a=window.chrome)==null?void 0:a.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||Xh("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:re.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,a;(a=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,re.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,re.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,re.isNullable)(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((0,re.fromEvent)(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(a=i.getCurrentSession())==null?void 0:a.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return(0,re.assertNever)(r.sessionState)}})).add((0,re.merge)((0,re.fromEvent)(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,re.tap)(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),(0,re.map)(r=>r.castState)),(0,re.observableFrom)([i.getCastState()])).pipe((0,re.filterChanged)(),(0,re.map)(Sw),(0,re.tap)(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let a=r==="CONNECTED",n=(0,re.isNonNullable)(this.connection$.getValue());if(a&&!n){let c=i.getCurrentSession();(0,re.assertNonNullable)(c);let l=c.getCastDevice(),d=(u=(o=c.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;((0,re.isNullable)(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:c,castDevice:l}))}else!a&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?(0,re.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;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(a){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:re.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},Sw=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(0,re.assertNever)(s)}};var se=require("@vkontakte/videoplayer-shared/es2018");var Be=require("@vkontakte/videoplayer-shared/es2018");var Du=require("@vkontakte/videoplayer-shared/es2018");var Ae=(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:(0,Du.assertNever)(t)}return s},pi=(s,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(s);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(s);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:(0,Du.assertNever)(e)}};var hn=s=>{var d;let{source:e,format:t,meta:i,output:r}=s,a,n,o;switch(t){case"MPEG":{let p=e[t];(0,Be.assertNonNullable)(p);let h=(0,Be.getHighestQuality)(Object.keys(p));(0,Be.assertNonNullable)(h);let m=p[h];(0,Be.assertNonNullable)(m),a=m,n="video/mp4",o=pn();break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let p=e[t];(0,Be.assertNonNullable)(p),a=p.url,n="application/x-mpegurl",o=pn();break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let p=e[t];(0,Be.assertNonNullable)(p),a=p.url,n="application/dash+xml",o=pn();break}case"DASH_LIVE_CMAF":{let p=e[t];(0,Be.assertNonNullable)(p),a=p.url,n="application/dash+xml",o=Jh();break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let p=e[t];(0,Be.assertNonNullable)(p),a=Ae(p.url),n="application/x-mpegurl",o=Jh();break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let p="Unsupported format for Chromecast",h=new Error(p);throw r.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Be.ErrorCategory.VIDEO_PIPELINE,message:p,thrown:h}),h}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${t} is no longer supported`);default:return(0,Be.assertNever)(t)}let u=yw((d=i.videoId)!=null?d:a,n);u.contentUrl=a,u.streamType=o,u.metadata=Tw();let{title:c,subtitle:l}=i;return(0,Be.isNonNullable)(c)&&(u.metadata.title=c),(0,Be.isNonNullable)(l)&&(u.metadata.subtitle=l),u};function pn(){var s,e,t,i;return(i=(t=(e=(s=chrome.cast)==null?void 0:s.media)==null?void 0:e.StreamType)==null?void 0:t.BUFFERED)!=null?i:"BUFFERED"}function Jh(){var s,e,t,i;return(i=(t=(e=(s=chrome.cast)==null?void 0:s.media)==null?void 0:e.StreamType)==null?void 0:t.LIVE)!=null?i:"LIVE"}function yw(s,e){var t,i;return(i=(t=chrome.cast)==null?void 0:t.media)!=null&&i.MediaInfo?new chrome.cast.media.MediaInfo(s,e):{contentId:s,contentType:e,metadata:{title:"",subtitle:""},streamType:pn()}}function Tw(){var s,e;return(e=(s=chrome.cast)==null?void 0:s.media)!=null&&e.GenericMediaMetadata?new chrome.cast.media.GenericMediaMetadata:{images:[],metadataType:0,releaseDate:"",subtitle:"",title:"",releaseYear:1970,type:0}}var B=(s,e,t=!1)=>{let i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};var fn=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)}};var Vu=require("@vkontakte/videoplayer-shared/es2018");var In=require("@vkontakte/videoplayer-shared/es2018");var Zh=G(Xe(),1),ef=require("@vkontakte/videoplayer-shared/es2018");var mn=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isChromiumBased(){return(0,Zh.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,c=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||c||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}=(0,ef.getWindow)().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 tf=G(Xe(),1),fi=require("@vkontakte/videoplayer-shared/es2018");var hi=()=>{var s,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((s=navigator.appVersion)!=null?s:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var bn=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,tf.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 e=(0,fi.getWindow)();if(!(0,fi.isBrowserWindow)(e))return;let{userAgent:t}=e.navigator;try{this._isMobile=hi()}catch(i){console.error("DeviceChecker: calling isMobile error - ",i)}this.detectDevice(t),this.detectOS(t),this.detectDeviceDetails(t),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let e=(0,fi.getWindow)();if(!(0,fi.isBrowserWindow)(e))return;let{userAgentData:t}=e.navigator;if(t!=null&&t.getHighEntropyValues){let i=await t.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=i,i.platform&&(this._os.name=this.normalizeOSName(i.platform),i.platformVersion&&(this._os.version=this.normalizeOSVersion(i.platformVersion),this._os.full=`${this._os.name} ${this._os.version}`)),i.model&&(this._details.model=i.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",c="Unknown";if(n){let l=r[0];typeof l=="number"?l<a.length&&a[l]!==void 0&&(u=a[l]):u=l}if(o){let l=r[1];typeof l=="number"?l<a.length&&a[l]!==void 0&&(c=a[l]):l!==void 0&&(c=l)}else a[2]!==void 0?c=a[2]:a[1]!==void 0&&n&&typeof r[0]=="string"&&(c=a[1]);u=this.normalizeOSName(u),c=this.normalizeOSVersion(c,u),u==="iOS"&&/ipad/i.test(e)?u="iPadOS":u==="iPadOS"&&/ip(hone|od)/i.test(e)&&(u="iOS"),this._os={name:u,version:c||"Unknown",full:c&&c!=="Unknown"?`${u} ${c}`: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),c="Unknown";typeof o=="number"?c=a[o]!==void 0?a[o]:"Unknown":o!==void 0?c=o:a[1]!==void 0?c=a[1]:a[0]!==void 0&&(c=a[0]),c=this.normalizeModelName(c,u),this.details.vendor=u,this.details.model=c;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{let e=(0,fi.getWindow)();if(!(0,fi.isBrowserWindow)(e))return;if(this._highEntropyValues.platformVersion){let i=this._highEntropyValues.platformVersion.split(".").slice(0,2).join(".");this._iosVersion=parseFloat(i);return}if(this._os.version!=="Unknown"){let i=this._os.version.split("."),r=i.length>=2?`${i[0]}.${i[1]}`:i[0];this._iosVersion=parseFloat(r);return}let t=e.navigator.userAgent.match(/OS (\d+(_\d+)?)/i);t!=null&&t[1]&&(this._iosVersion=parseFloat(t[1].replace(/_/g,".")))}catch(e){console.error("DeviceChecker: iOS version detection error - ",e)}}};var ga=require("@vkontakte/videoplayer-shared/es2018"),gn=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in(0,ga.getWindow)()}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(){var a;let e=(0,ga.getWindow)();if(!(0,ga.isBrowserWindow)(e))return;let{navigator:t,screen:i}=e,{maxTouchPoints:r}=t;try{this._maxTouchPoints=r!=null?r:0,this._isHdr=!!((a=e.matchMedia("(dynamic-range: high)"))!=null&&a.matches),this._colorDepth=i.colorDepth}catch(n){console.error(n)}try{this._pixelRatio=e.devicePixelRatio||1,this._height=i.height,this._width=i.width,this._height=i.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(n){console.error(n)}}};var Wi=require("@vkontakte/videoplayer-shared/es2018");var ut=()=>window.ManagedMediaSource||window.MediaSource,xr=()=>{var s,e;return!!(window.ManagedMediaSource&&((e=(s=window.ManagedSourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},rf=()=>{var s,e;return!!(window.MediaSource&&((e=(s=window.SourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},vn=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var af,Iw=(af=(0,Wi.getWindow)().document)==null?void 0:af.createElement("video"),Ew='video/mp4; codecs="avc1.42000a,mp4a.40.2"',ww='video/mp4; codecs="hev1.1.6.L93.B0"',sf='video/webm; codecs="vp09.00.10.08"',nf='video/webm; codecs="av01.0.00M.08"',xw='audio/mp4; codecs="mp4a.40.2"',Pw='audio/webm; codecs="opus"',of,kw=async()=>{let s=(0,Wi.getWindow)();if(!(0,Wi.isBrowserWindow)(s))return;let e={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[t,i]=await Promise.all([s.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:nf}}),s.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:sf}})]);of={DASH_WEBM_AV1:t,DASH_WEBM:i}};kw().catch(s=>{console.log(Iw),console.error(s)});var Sn=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 of}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var i,r,a,n,o,u,c,l,d,p,h,m,b,S,v,y,x,w,M,_;let e=(0,Wi.getWindow)();if(!(0,Wi.isBrowserWindow)(e))return;let t=e.document;this._video=t.createElement("video");try{this._protocols={mms:xr(),mse:rf(),hls:!!((r=(i=this._video).canPlayType)!=null&&r.call(i,"application/x-mpegurl")||(n=(a=this._video).canPlayType)!=null&&n.call(a,"vnd.apple.mpegURL")),webrtc:!!e.RTCPeerConnection,ws:!!e.WebSocket},this._containers={mp4:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/mp4")),webm:!!((l=(c=this._video).canPlayType)!=null&&l.call(c,"video/webm")),cmaf:!0};let q=!!((p=(d=ut())==null?void 0:d.isTypeSupported)!=null&&p.call(d,Ew)),O=!!((m=(h=ut())==null?void 0:h.isTypeSupported)!=null&&m.call(h,ww)),j=!!((S=(b=ut())==null?void 0:b.isTypeSupported)!=null&&S.call(b,xw));this._codecs={h264:q,h265:O,vp9:!!((y=(v=ut())==null?void 0:v.isTypeSupported)!=null&&y.call(v,sf)),av1:!!((w=(x=ut())==null?void 0:x.isTypeSupported)!=null&&w.call(x,nf)),aac:j,opus:!!((_=(M=ut())==null?void 0:M.isTypeSupported)!=null&&_.call(M,Pw)),mpeg:(q||O)&&j},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(q){console.error(q)}try{this.destroyVideoElement()}catch(q){console.error("Error destroying video element:",q)}}destroyVideoElement(){var t;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);(t=this._video.parentNode)==null||t.replaceChild(e,this._video),this._video=null}};var Tn=require("@vkontakte/videoplayer-shared/es2018");var uf="audio/mpeg",yn=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var i,r,a,n;let e=(0,Tn.getWindow)();if(!(0,Tn.isBrowserWindow)(e))return;let t=e.document;this._audio=t.createElement("audio");try{this._containers={mpeg:!!((r=(i=this._audio).canPlayType)!=null&&r.call(i,uf))},this._codecs={mp3:!!((n=(a=ut())==null?void 0:a.isTypeSupported)!=null&&n.call(a,uf))}}catch(o){console.error(o)}try{this.destroyAudioElement()}catch(o){console.error("Error destroying audio element:",o)}}destroyAudioElement(){var t;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);(t=this._audio.parentNode)==null||t.replaceChild(e,this._audio),this._audio=null}};var Bu=class{constructor(){this.isInited$=new In.ValueSubject(!1);this._displayChecker=new gn,this._deviceChecker=new bn(this._displayChecker),this._browserChecker=new mn,this._videoChecker=new Sn(this._deviceChecker,this._browserChecker),this._audioChecker=new yn,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(){(0,In.isBrowserWindow)()&&(this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0))}},H=new Bu;var _u=s=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=H.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(0,Vu.assertNever)(o)}})},va=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(0,Vu.assertNever)(s)}},cf=s=>{let t=Object.keys(s).filter(i=>!va(i));return _u(t).length>0};var Sa=class{constructor(e){this.subscription=new se.Subscription;this.sessionId$=new se.ValueSubject(null);this.mediaSessionId$=new se.ValueSubject(null);this.contentId$=new se.ValueSubject(null);this.isMobile=hi();this.mobileVolumeState={muted:!1,volume:0};this.media=null;this.lastRequestedVolume=null;this.syncMediaState=e=>{var a,n,o;if((0,se.isNullable)(e))return;this.media=e,this.mediaSessionId$.next((a=e.mediaSessionId)!=null?a:null);let t=(n=e.media)==null?void 0:n.contentId;t&&this.contentId$.next(t),this.syncPlaybackState(e);let i=(o=e.media)==null?void 0:o.duration;(0,se.isNonNullable)(i)&&this.params.output.duration$.next(Math.max(0,i));let r=e.currentTime;if((0,se.isNonNullable)(r)){this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.params.output.position$.next(r);let c=this.params.output.isLive$.getValue();e.playerState==="PLAYING"&&!c?this.progressTicker.start(r):this.progressTicker.pause()}};this.params=e,this.progressTicker=new fn(e),this.log=this.params.dependencies.logger.createComponentLog("ChromecastPresentationApiProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(va(e.format)),this.subscribe()}subscribe(){let e=r=>{var a;this.params.output.error$.next({category:se.ErrorCategory.WTF,id:"ChromecastPresentationApiProvider",message:(a=r==null?void 0:r.message)!=null?a:"Unknown error",thrown:r})};this.subscription.add(this.params.chromecastConnector.message$.pipe((0,se.filter)(r=>!!r)).subscribe(r=>{this.handleMessage(r)},e)),this.subscription.add(this.sessionId$.pipe((0,se.filter)(se.isNonNullable),(0,se.filterChanged)(),(0,se.debounce)(0)).subscribe(()=>{this.loadMedia()},e));let t=this.contentId$.pipe((0,se.filterChanged)(),(0,se.map)(Boolean));this.subscription.add((0,se.combine)({seekState:this.params.desiredState.seekState.stateChangeEnded$,mediaLoaded:t}).pipe((0,se.filter)(({mediaLoaded:r})=>r)).subscribe(()=>{let r=this.params.desiredState.seekState.getState();r.state==="requested"&&this.seek(r.position/1e3)},e));let i=(0,se.combine)({playbackState:this.params.desiredState.playbackState.stateChangeStarted$,mediaLoaded:t});this.subscription.add(i.pipe((0,se.filter)(({mediaLoaded:r})=>r),(0,se.debounce)(0)).subscribe(()=>{this.syncPlayback()},e)),this.subscription.add(i.pipe((0,se.filter)(({mediaLoaded:r,playbackState:{from:a,to:n}})=>!r&&a==="stopped"&&n==="playing")).subscribe(()=>{this.loadMedia()},e)),this.subscription.add((0,se.combine)({volumeState:this.params.desiredState.volume.stateChangeStarted$.pipe((0,se.debounce)(30)),mediaLoaded:t}).pipe((0,se.filter)(({mediaLoaded:r})=>r)).subscribe(({volumeState:r})=>{let{muted:a,volume:n}=r.to;this.setVolume(n,a)},e))}handleMessage(e){var t,i,r,a,n,o;switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId);let u=(i=(t=e.message)==null?void 0:t.media)==null?void 0:i[0];this.syncMediaState(u);let c=(r=e.message)==null?void 0:r.receiver.volume;this.syncVolumeState(c)}break;case"v2_message":{switch((a=e.message)==null?void 0:a.type){case"MEDIA_STATUS":{let u=(o=(n=e.message)==null?void 0:n.status)==null?void 0:o[0];this.syncMediaState(u);break}}break}}}loadMedia(){var o;let e=hn(this.params),t=(o=this.media)==null?void 0:o.currentTime,i=this.params.desiredState.seekState.getState(),r=t!=null?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();(0,se.assertNonNullable)(e,"play on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PLAY",mediaSessionId:e,customData:null})}pause(){let e=this.mediaSessionId$.getValue();(0,se.assertNonNullable)(e,"pause on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PAUSE",mediaSessionId:e,customData:null})}seek(e){let t=this.mediaSessionId$.getValue();(0,se.assertNonNullable)(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":B(this.params.desiredState.playbackState,"paused");break;case"PLAYING":B(this.params.desiredState.playbackState,"playing");break;case"IDLE":{t==="FINISHED"?(this.params.output.endedEvent$.next(),B(this.params.desiredState.playbackState,"stopped"),this.contentId$.next(null)):B(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((0,se.isNullable)(e))return;let{level:t,muted:i}=e,r={muted:i!=null?i:!1,volume:t!=null?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()}};var he=require("@vkontakte/videoplayer-shared/es2018");var lf=s=>({castDevice:{friendlyName:s},remotePlayer:{},remotePlayerController:{},session:{}}),df=()=>String(Date.now())+String(Math.floor(Math.random()*1e5));var ya=class{constructor(e){this.capabilities=["WEB"];this.presentationRequest$=new he.ValueSubject(null);this.sessionId$=new he.ValueSubject(null);this.broadcastChannel=new BroadcastChannel("vk_player_chromecast_events");this.subscription=new he.Subscription;this.subscriptionEvents=new he.Subscription;this.isDestroyed=!1;this.sequenceNumber=0;this.presentationAvailable$=new he.ValueSubject(!1);this.presentationConnection$=new he.ValueSubject(null);this.message$=new he.ValueSubject(null);this.friendlyName$=new he.ValueSubject(null);this.errorEvent$=new he.Subject;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((0,he.fromEvent)(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(){var e;this.log({message:"connect"});try{this.presentationRequest$.getValue()||(this.log({message:"reinitPresentation"}),this.reinitPresentation(!1));let t=this.presentationRequest$.getValue();(0,he.assertNonNullable)(t,"connect with null presentationRequest");let i=await t.start();this.handleConnection(i)}catch(t){switch(t==null?void 0:t.name){case"AbortError":case"NotAllowedError":break;default:this.errorEvent$.next({category:he.ErrorCategory.WTF,id:"ChromecastPresentationApiConnector",message:(e=t==null?void 0:t.message)!=null?e:"connect error",thrown:t});break}}}subscribe(){this.subscription.add((0,he.fromEvent)(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((0,he.tap)(e=>{this.log({message:`presentationConnection$: ${!!e}`})}),(0,he.filter)(e=>!!e)).subscribe(e=>{let t=(0,he.fromEvent)(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=(0,he.fromEvent)(e,"connect").subscribe(()=>{this.send("client_connect")}),r=(0,he.fromEvent)(e,"close").subscribe(a=>{switch(a.reason){case"error":this.errorEvent$.next({category:he.ErrorCategory.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==null?void 0:t.state)==="connected"&&(t==null||t.send(e))}catch(t){this.errorEvent$.next({category:he.ErrorCategory.WTF,id:"ChromecastPresentationApiConnector",message:"PresentationConnection send error",data:{message:e},thrown:t})}}handleMessage(e){var t;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":((t=e.message)==null?void 0:t.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]||df()}resetSubscriptionEvents(){this.subscriptionEvents.unsubscribe(),this.subscriptionEvents=new he.Subscription}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))}};var je=require("@vkontakte/videoplayer-shared/es2018");var Gt=class s{constructor(e){this.subscription=new je.Subscription;this.connection$=new je.ValueSubject(void 0);this.castState$=new je.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new je.Subject;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 ya({appId:e.receiverApplicationId,logger:e.dependencies.logger}),this.subscribe())}static isSupported(){return"chrome"in window&&"presentation"in navigator&&"BroadcastChannel"in window}subscribe(){(0,je.assertNonNullable)(this.chromecastConnector,"subscribe with null chromecastConnector"),this.subscription.add(this.chromecastConnector.errorEvent$.subscribe(this.errorEvent$));let e=(0,je.combine)({connection:this.chromecastConnector.presentationConnection$,available:this.chromecastConnector.presentationAvailable$,friendlyName:this.chromecastConnector.friendlyName$.pipe((0,je.filterChanged)())});this.subscription.add(e.pipe((0,je.map)(({connection:t,friendlyName:i})=>!!(t&&i)),(0,je.filterChanged)()).subscribe(t=>{var r,a;let i=(a=(r=this.chromecastConnector)==null?void 0:r.friendlyName$.getValue())!=null?a:"";this.connection$.next(t?lf(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(){var e;this.log({message:"connect"}),(e=this.chromecastConnector)==null||e.connect()}disconnect(){var e;this.log({message:"disconnect"}),(e=this.chromecastConnector)==null||e.disconnect()}async stopMedia(){var e;this.log({message:"stopMedia"}),(e=this.chromecastConnector)==null||e.stopMedia()}toggleConnection(){var t;let e=!!((t=this.chromecastConnector)!=null&&t.presentationConnection$.getValue());this.log({message:`toggleConnection: isConnected - ${e}`}),e?this.disconnect():this.connect()}setVolume(e){}setMuted(e){}destroy(){var e;this.log({message:"destroy"}),(e=this.chromecastConnector)==null||e.destroy(),this.subscription.unsubscribe()}};var Wl=G(Xe(),1),Ql=G(mi(),1),Xy=G(sc(),1);var jg=G(Wc(),1);var Nt=require("@vkontakte/videoplayer-shared/es2018"),ae=class{constructor(e){this.transitionStarted$=new Nt.Subject;this.transitionEnded$=new Nt.Subject;this.transitionUpdated$=new Nt.Subject;this.forceChanged$=new Nt.Subject;this.stateChangeStarted$=(0,Nt.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,Nt.merge)(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||(0,Nt.isNonNullable)(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};var ue=require("@vkontakte/videoplayer-shared/es2018");var hR=5,fR=5,mR=500,Hg=7e3,Ca=class{constructor(e){this.subscription=new ue.Subscription;this.loadMediaTimeoutSubscription=new ue.Subscription;this.videoState=new ae("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==null?void 0: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:(0,ue.assertNever)(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,ue.assertNever)(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,ue.assertNever)(e)}break}default:(0,ue.assertNever)(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(va(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 ue.Subscription;this.subscription.add(e),this.subscription.add((0,ue.merge)(this.videoState.stateChangeStarted$.pipe((0,ue.map)(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe((0,ue.map)(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 ue.Subject;e.add(r.pipe((0,ue.debounce)(mR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add((0,ue.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-a)>hR)&&r.next(o),a=o})),e.add((0,ue.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,ue.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,ue.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,ue.fromEvent)(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<fR&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),B(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:(0,ue.assertNever)(n)}}),t((0,ue.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t((0,ue.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=(0,ue.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,ue.observableFrom)(["init"])).pipe((0,ue.debounce)(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),B(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=hn(this.params),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),B(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&B(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,a;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(a=e.muted)!=null?a: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((0,ue.timeout)(Hg).subscribe(()=>a(`timeout(${Hg})`)))});(0,jg.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:ue.ErrorCategory.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var nl=G(Xe(),1);var Da=require("@vkontakte/videoplayer-shared/es2018");var Wg=require("@vkontakte/videoplayer-shared/es2018"),Qg=(s,e)=>{try{s.pause(),s.playbackRate=0,(0,Wg.clearVideoElement)(s,e),s.remove()}catch(t){console.error(t)}};var Gn=require("@vkontakte/videoplayer-shared/es2018"),Qc=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)}},zn=(0,Da.getWindow)(),zc=zn.WeakMap?new zn.WeakMap:new Qc,Gc=zn.WeakMap?new zn.WeakMap:new Map,bR=(s,e=20)=>{let t=0;return(0,Gn.fromEvent)(s,"ratechange").subscribe(i=>{t++,t>=e&&(s.currentTime=s.currentTime,t=0)})},Je=(s,{audioVideoSyncRate:e,disableYandexPiP:t,clearVideoElementInnerHTML:i})=>{let r=s.querySelector("video"),a=!!r;r?(0,Da.clearVideoElement)(r,i):(r=document.createElement("video"),s.appendChild(r)),zc.set(r,a);let n=new Gn.Subscription;return n.add(bR(r,e)),Gc.set(r,n),r.setAttribute("crossorigin","anonymous"),r.setAttribute("playsinline","playsinline"),t&&r.setAttribute("x-yandex-pip","false"),r.controls=!1,r.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),r},Ze=(s,e=!1,t=!1)=>{let i=Gc.get(s);i==null||i.unsubscribe(),Gc.delete(s);let r=zc.get(s);zc.delete(s),r||e?(0,Da.clearVideoElement)(s,t):Qg(s,t)};var Yc=G(ji(),1),z=require("@vkontakte/videoplayer-shared/es2018");var gi=require("@vkontakte/videoplayer-shared/es2018"),Yn=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{let n=s.getState(),o=e(),u=(0,gi.isNullable)(r),c=new gi.Subscription;return r&&c.add(r.subscribe(l=>{let d=s.getState();i(l,d)&&s.setState(l)},a)),i(o,n)||(t(n),u&&s.setState(n)),c.add(s.stateChangeStarted$.subscribe(l=>{t(l.to),u&&s.setState(l.to)},a)),c},Ft=(s,e,t)=>Yn(e,()=>s.loop,i=>{(0,gi.isNonNullable)(i)&&(s.loop=i)},{onError:t}),et=(s,e,t,i)=>Yn(e,()=>({muted:s.muted,volume:s.volume}),r=>{(0,gi.isNonNullable)(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),ft=(s,e,t,i)=>Yn(e,()=>s.playbackRate,r=>{(0,gi.isNonNullable)(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Ba=Yn;var gR=s=>["__",s.language,s.label].join("|"),vR=(s,e)=>{if(s.id===e)return!0;let[t,i,r]=e.split("|");return s.language===i&&s.label===r},Kc=class s{constructor(e){this.available$=new z.Subject;this.current$=new z.ValueSubject(void 0);this.error$=new z.Subject;this.subscription=new z.Subscription;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:z.ErrorCategory.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(Ba(t.internalTextTracks,()=>(0,Yc.default)(this.internalTracks),a=>{(0,z.isNonNullable)(a)&&this.setInternal(a)},{equal:(a,n)=>(0,z.isNonNullable)(a)&&(0,z.isNonNullable)(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,z.map)(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Ba(t.externalTextTracks,()=>(0,Yc.default)(this.externalTracks),a=>{(0,z.isNonNullable)(a)&&this.setExternal(a)},{equal:(a,n)=>(0,z.isNonNullable)(a)&&(0,z.isNonNullable)(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,z.map)(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Ba(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(Ba(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){(0,z.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,z.fromEvent)(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add((0,z.merge)((0,z.fromEvent)(e,"addtrack"),(0,z.fromEvent)(e,"removetrack"),(0,z.observableFrom)(["init"])).pipe((0,z.map)(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),(0,z.filterChanged)((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add((0,z.merge)((0,z.fromEvent)(e,"change"),(0,z.observableFrom)(["init"])).pipe((0,z.map)(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),(0,z.map)(i=>i&&this.htmlTextTrackToITextTrack(i).id),(0,z.filterChanged)()).subscribe(this.current$));let t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)==null?void 0:r.activeCues)!=null?a:null)};this.subscription.add((0,z.fromEvent)(e,"addtrack").subscribe(i=>{var a,n;(a=i.track)==null||a.addEventListener("cuechange",t);let r=o=>{var c,l,d,p,h;let u=(l=(c=o.target)==null?void 0:c.cues)!=null?l:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add((0,z.fromEvent)(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.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;(0,z.isNonNullable)(t.align)&&(r.align=t.align),(0,z.isNonNullable)(t.position)&&(r.position=t.position),(0,z.isNonNullable)(t.size)&&(r.size=t.size),(0,z.isNonNullable)(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,z.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(s.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,c,l,d;let{language:t,label:i}=e,r=e.id?e.id:gR(e),a=this.externalTracks.has(r),n=(c=a?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?c:r.includes("auto");return a?{id:r,type:"external",isAuto:n,language:t,label:i,url:(l=this.externalTracks.get(r))==null?void 0:l.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(d=this.internalTracks.get(r))==null?void 0:d.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){(0,z.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,z.isNullable)(e)||!vR(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){(0,z.assertNonNullable)(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){(0,z.assertNonNullable)(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},mt=Kc;var Xi=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 zg=s=>{let e=s;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},Xc=s=>{let e=zg(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},Gg=s=>{let e=zg(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};var L=require("@vkontakte/videoplayer-shared/es2018");var SR=3,Yg=(s,e,t=SR)=>{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 tt=s=>{let e=V=>(0,L.fromEvent)(s,V).pipe((0,L.mapTo)(void 0),(0,L.shareReplay)(1)),t=new L.Subscription,i=()=>t.unsubscribe(),r=(0,L.merge)((0,L.fromEvent)(s,"progress"),(0,L.fromEvent)(s,"timeupdate")).pipe((0,L.map)(()=>Yg(s.buffered,s.currentTime)),(0,L.shareReplay)(1)),a=H.browser.isSafari?(0,L.combine)({play:e("play").pipe((0,L.once)()),playing:e("playing")}).pipe((0,L.mapTo)(void 0),(0,L.shareReplay)(1)):e("playing"),n=(0,L.fromEvent)(s,"volumechange").pipe((0,L.map)(()=>({muted:s.muted,volume:s.volume})),(0,L.shareReplay)(1)),o=(0,L.fromEvent)(s,"ratechange").pipe((0,L.map)(()=>s.playbackRate),(0,L.shareReplay)(1)),u=(0,L.fromEvent)(s,"error").pipe((0,L.filter)(()=>!!(s.error||s.played.length)),(0,L.map)(()=>{var Q;let V=s.error;return{id:V?`MediaError#${V.code}`:"HtmlVideoError",category:L.ErrorCategory.VIDEO_PIPELINE,message:V?V.message:"Error event from HTML video element",thrown:(Q=s.error)!=null?Q:void 0}}),(0,L.shareReplay)(1)),c=(0,L.fromEvent)(s,"timeupdate").pipe((0,L.map)(()=>s.currentTime),(0,L.shareReplay)(1)),l=["waiting","seeking","seeked","timeupdate"],d=new L.Subject,p=.3,h;t.add((0,L.merge)(...l.map(V=>(0,L.fromEvent)(s,V))).subscribe(V=>{let Q=s.currentTime;s.loop&&(0,L.isNonNullable)(h)&&(0,L.isNonNullable)(Q)&&h>=s.duration-p&&Q<=p&&d.next(h),h=Q}));let m=e("pause").pipe((0,L.filter)(()=>!s.error&&h!==s.duration),(0,L.shareReplay)(1)),b=(0,L.fromEvent)(s,"enterpictureinpicture").pipe((0,L.shareReplay)(1)),S=(0,L.fromEvent)(s,"leavepictureinpicture").pipe((0,L.shareReplay)(1)),v=new L.ValueSubject(Gg(s));t.add(b.subscribe(()=>v.next(!0))),t.add(S.subscribe(()=>v.next(!1)));let y=new L.ValueSubject(Xc(s)),x=(0,L.fromEvent)(s,"fullscreenchange").pipe((0,L.shareReplay)(1));t.add(x.pipe((0,L.map)(()=>Xc(s))).subscribe(y));let w=.1,M=1e3,_=(0,L.fromEvent)(s,"timeupdate").pipe((0,L.map)(V=>s.duration-s.currentTime<w),(0,L.filterChanged)(),(0,L.shareReplay)(1)),q=(0,L.merge)(_.pipe((0,L.filter)(V=>!s.loop&&V)),(0,L.fromEvent)(s,"ended")).pipe((0,L.throttle)(M),(0,L.mapTo)(void 0),(0,L.shareReplay)(1)),j=(0,L.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(V=>(0,L.fromEvent)(s,V)),_.pipe((0,L.map)(V=>({type:V?"ended":"unknown"})))).pipe((0,L.map)(V=>H.browser.isFirefox&&V.type==="ended"?s.readyState<2:s.readyState<3),(0,L.filterChanged)(),(0,L.shareReplay)(1));return{playing$:a,pause$:m,canplay$:e("canplay"),ended$:q,looped$:d,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:(0,L.fromEvent)(s,"durationchange").pipe((0,L.map)(()=>s.duration),(0,L.shareReplay)(1)),isBuffering$:j,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:v,inFullscreen$:y,enterPip$:b,leavePip$:S,destroy:i}};var Kt=require("@vkontakte/videoplayer-shared/es2018"),vi=s=>{switch(s){case"mobile":return Kt.VideoQuality.Q_144P;case"lowest":return Kt.VideoQuality.Q_240P;case"low":return Kt.VideoQuality.Q_360P;case"sd":case"medium":return Kt.VideoQuality.Q_480P;case"hd":case"high":return Kt.VideoQuality.Q_720P;case"fullhd":case"full":return Kt.VideoQuality.Q_1080P;case"quadhd":case"quad":return Kt.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return Kt.VideoQuality.Q_2160P}};var Ge=G(bt(),1),Zc=G(Xe(),1),Ji=G(mi(),1),D=require("@vkontakte/videoplayer-shared/es2018");var Jc=!1,Xt={},iv=s=>{Jc=s},rv=()=>{Xt={}},av=s=>{s(Xt)},Va=(s,e)=>{var t;Jc&&(Xt.meta=(t=Xt.meta)!=null?t:{},Xt.meta[s]=e)},ze=class{constructor(e){this.name=e}next(e){var i,r;if(!Jc)return;Xt.series=(i=Xt.series)!=null?i:{};let t=(r=Xt.series[this.name])!=null?r:[];t.push([Date.now(),e]),Xt.series[this.name]=t}};var $e=require("@vkontakte/videoplayer-shared/es2018");function sv(s,e,t){return!s.max&&s.min===e?"high_quality":!s.min&&s.max===t?"traffic_saving":"unknown"}function Br(s,e,t){return(0,$e.isNullable)(s)||(0,$e.isNonNullable)(s.min)&&(0,$e.isNonNullable)(s.max)&&(0,$e.isLower)(s.max,s.min)||(0,$e.isNonNullable)(s.min)&&e&&(0,$e.isHigher)(s.min,e)||(0,$e.isNonNullable)(s.max)&&t&&(0,$e.isLower)(s.max,t)}function nv({limits:s,highestAvailableHeight:e,lowestAvailableHeight:t}){return Br({max:s!=null&&s.max?(0,$e.videoHeightToQuality)(s.max):void 0,min:s!=null&&s.min?(0,$e.videoHeightToQuality)(s.min):void 0},e?(0,$e.videoHeightToQuality)(e):void 0,t?(0,$e.videoHeightToQuality)(t):void 0)}var dv=new ze("best_bitrate"),Xn=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;var Vr=s=>(e,t)=>s*(Number(e.bitrate)-Number(t.bitrate)),Si=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,D.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Jn='Assertion "ABR Tracks is empty array" failed',Kn=new WeakMap,ov=new WeakMap,uv=new WeakMap,_a=(s,e,t,i)=>{var u;let r=[...e].sort(Vr(1)),a=[...t].sort(Vr(1)),n=a.filter(c=>(0,D.isNonNullable)(c.bitrate)&&(0,D.isNonNullable)(s.bitrate)?s.bitrate/c.bitrate>i:!0),o=(u=(0,Ge.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,Ge.default)(a,-1);return o&&(0,Zc.default)(n,o)?o:n.length?(0,Ge.default)(n,-1):(0,Ge.default)(a,0)},Oa=(s,e,t,i)=>{var u;let r=Kn.get(e);r||(r=[...e].sort(Vr(1)),Kn.set(e,r));let a=Kn.get(t);a||(a=[...t].sort(Vr(1)),Kn.set(t,a));let n=uv.get(s);n||(n=a.filter(c=>(0,D.isNonNullable)(c.bitrate)&&(0,D.isNonNullable)(s.bitrate)?s.bitrate/c.bitrate>i:!0),uv.set(s,n));let o=(u=(0,Ge.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,Ge.default)(a,-1);return o&&(0,Zc.default)(n,o)?o:n.length?(0,Ge.default)(n,-1):(0,Ge.default)(a,0)},cv=s=>"quality"in s,Zn=(s,e,t,i)=>{var n;let r=(0,D.isNonNullable)((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&(0,D.isNonNullable)(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?s.trackCooldownIncreaseQuality:s.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&(0,D.now)()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!a&&i.recordSelection(t),a&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=cv(o)?"video":"audio",c=cv(o)?o.quality:o.bitrate;return e({message:`
8
8
  [last ${u} selected] ${c}
9
9
  `}),o}return i==null||i.recordSwitch(t),t},AR=(s,e)=>Math.log(e)/Math.log(s),pv=({tuning:s,container:e,limits:t,panelSize:i})=>{let r=s.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(s.usePixelRatio&&H.display.pixelRatio){let a=H.display.pixelRatio;if(s.pixelRatioMultiplier)r*=s.pixelRatioMultiplier*(a-1)+1;else{let n=s.pixelRatioLogBase,[o=0,u=0,c=0]=s.pixelRatioLogCoefficients,l=AR(n,o*a+u)+c;Number.isFinite(l)&&(r*=l)}}return(0,D.isNonNullable)(t==null?void 0:t.min)&&(0,D.isHigherOrEqual)(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}},lv=new WeakMap,Ut=(s,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:c,visible:l,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:m,panelSize:b})=>{var ie,le,oe,A,$;(0,D.assertNotEmptyArray)(s,Jn);let{containerSizeFactor:S,containerSizeLimit:v}=pv({container:e,tuning:i,limits:r,panelSize:b}),y=i.considerPlaybackRate&&(0,D.isNonNullable)(o)?o:1,x=lv.get(s);x||(x=s.filter(k=>!(0,D.isInvariantQuality)(k.quality)).sort((k,R)=>(0,D.isHigher)(k.quality,R.quality)?-1:1),lv.set(s,x));let w=(ie=(0,Ge.default)(x,-1))==null?void 0:ie.quality,M=(le=(0,Ge.default)(x,0))==null?void 0:le.quality,_=Br(r,M,w),q=y*Xn(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),O={},j=null;for(let k of x){if(k.tvDisabled){O[k.quality]="TvDisabled";continue}let R=!0;if(v)if(k.size)R=k.size.width<=v.width&&k.size.height<=v.height;else{let st=v&&(0,D.videoSizeToQuality)(v);R=st?(0,D.isLowerOrEqual)(k.quality,st):!0}if(!R){O[k.quality]="FitsContainer";continue}let Z=h||t,K=(0,D.isNonNullable)(Z)&&isFinite(Z)&&(0,D.isNonNullable)(k.bitrate)?Z-a>=k.bitrate*q:!0,$t=(r==null?void 0:r.min)===k.quality;if(!K&&!$t){O[k.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&(0,D.isNonNullable)(i.minBufferToSwitchUp)&&u&&!(0,D.isInvariantQuality)(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&(0,D.isHigher)(k.quality,u.quality)){O[k.quality]="Buffer";continue}if(!!d&&(0,D.isHigherOrEqual)(k.quality,d)&&!$t){O[k.quality]="DroppedFramesLimit";continue}if(!!p&&(0,D.isHigherOrEqual)(k.quality,p)&&!$t){O[k.quality]="StallsLimit";continue}let Fe=_||((0,D.isNullable)(r==null?void 0:r.max)||(0,D.isLowerOrEqual)(k.quality,r.max))&&((0,D.isNullable)(r==null?void 0:r.min)||(0,D.isHigherOrEqual)(k.quality,r.min)),Ue=(0,D.isNonNullable)(l)&&!l?(0,D.isLowerOrEqual)(k.quality,i.backgroundVideoQualityLimit):!0;if(!Fe||!Ue){O[k.quality]="FitsQualityLimits";continue}j||(j=k)}j&&j.bitrate&&dv.next(j.bitrate);let V=(oe=j!=null?j:(0,Ge.default)(x,-1))!=null?oe:s[0],Q=c==null?void 0:c.last,U=Zn(i,m,V,c);return(0,D.isNonNullable)(c)&&U.quality!==(Q==null?void 0:Q.quality)&&m({message:`
10
10
  [VIDEO TRACKS ABR]
@@ -175,7 +175,7 @@ void main(void) {
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(l,"i")}var dy=s=>{if(!(s!=null&&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==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},At=(s,e)=>{let t=s;t=(0,Pl.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,py.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Pl.default)(t,n,(o,u)=>(0,Ga.isNullable)(a)?o:(0,Ga.isNullable)(u)?a:(0,hy.default)(a,parseInt(u,10),"0"))}return t},So=(s,e)=>{var j,V,Q,U,ie,le,oe,A,$,k,R,Z,K,$t,Lt,pe,Ne,Fe,Ue,st,jt,Wt,$i,lr,Li,Xl,Jl,Zl,ed,td,id,rd,ad,sd,nd,od,ud,cd,ld,dd,pd,hd,fd,md,bd,gd,vd,Sd,yd,Td,Id,Ed,wd,xd,Pd,kd,Ad,Rd,Md,$d,Ld;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(Tt=>{var ve,Ci;return(Ci=(ve=Tt.textContent)==null?void 0:ve.trim())!=null?Ci:""}),o=(j=(0,fy.default)(n,0))!=null?j:"",u=a.getAttribute("type")==="dynamic",c=a.getAttribute("availabilityStartTime"),l=a.getAttribute("publishTime"),d=a.getElementsByTagName("vk:Attrs")[0],p=d==null?void 0:d.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=d==null?void 0:d.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=d==null?void 0:d.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=d==null?void 0:d.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,S;u&&(S={availabilityStartTime:c?new Date(c).getTime():0,publishTime:l?new Date(l).getTime():0,latestSegmentPublishTime:p?new Date(p).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:m==="yes"});let v,y=a.getAttribute("mediaPresentationDuration"),x=[...a.getElementsByTagName("Period")],w=x.reduce((Tt,ve)=>({...Tt,[ve.id]:ve.children}),{}),M=x.reduce((Tt,ve)=>({...Tt,[ve.id]:ve.getAttribute("duration")}),{});y?v=dy(y):(0,kl.default)(M).filter(Tt=>Tt).length&&!u?v=(0,kl.default)(M).reduce((Tt,ve)=>{var Ci;return Tt+((Ci=dy(ve))!=null?Ci:0)},0):b&&(v=parseInt(b,10));let _=0,q=(Q=(V=a.getAttribute("profiles"))==null?void 0:V.split(","))!=null?Q:[];for(let Tt of x.map(ve=>ve.id))for(let ve of w[Tt]){let Ci=(U=ve.getAttribute("id"))!=null?U:"id"+(_++).toString(10),Zr=(ie=ve.getAttribute("mimeType"))!=null?ie:"",Qo=(le=ve.getAttribute("codecs"))!=null?le:"",zo=(oe=ve.getAttribute("contentType"))!=null?oe:Zr==null?void 0:Zr.split("/")[0],dT=($=(A=ve.getAttribute("profiles"))==null?void 0:A.split(","))!=null?$:[],Cd=(R=ly((k=ve.getAttribute("lang"))!=null?k:""))!=null?R:{},Ns=($t=(K=(Z=ve.querySelector("Label"))==null?void 0:Z.textContent)==null?void 0:K.trim())!=null?$t:void 0,pT=ve.querySelectorAll("Representation"),hT=ve.querySelector("SegmentTemplate"),fT=(pe=(Lt=ve.querySelector("Role"))==null?void 0:Lt.getAttribute("value"))!=null?pe:void 0,dr=zo,Re={id:Ci,language:Cd.language,isDefault:fT==="main",label:Ns,codecs:Qo,hdr:dr==="video"&&xl(Qo),mime:Zr,representations:[]};for(let me of pT){let ai=(Ne=me.getAttribute("lang"))!=null?Ne:void 0,Fs=(Ue=(Fe=Ns!=null?Ns:ve.getAttribute("label"))!=null?Fe:me.getAttribute("label"))!=null?Ue:void 0,Us=(Wt=(jt=(st=me.querySelector("BaseURL"))==null?void 0:st.textContent)==null?void 0:jt.trim())!=null?Wt:"",Di=new URL(Us||o,e).toString(),si=($i=me.getAttribute("mimeType"))!=null?$i:Zr,qs=(Li=(lr=me.getAttribute("codecs"))!=null?lr:Qo)!=null?Li:"",Hs;if(zo==="text"){let ni=me.getAttribute("id")||"",js=((Xl=Cd.privateuse)==null?void 0:Xl.includes("x-auto"))||ni.includes("_auto"),Bi=me.querySelector("SegmentTemplate");if(Bi){let ea={representationId:(Jl=me.getAttribute("id"))!=null?Jl:void 0,bandwidth:(Zl=me.getAttribute("bandwidth"))!=null?Zl:void 0},Ws=parseInt((ed=me.getAttribute("bandwidth"))!=null?ed:"",10)/1e3,Qs=(id=parseInt((td=Bi.getAttribute("startNumber"))!=null?td:"",10))!=null?id:1,pr=parseInt((rd=Bi.getAttribute("timescale"))!=null?rd:"",10),Go=(ad=Bi.querySelectorAll("SegmentTimeline S"))!=null?ad:[],hr=Bi.getAttribute("media");if(!hr)continue;let zs=[],Gs=0,Ys="",fr=0,ta=Qs,Qe=0;for(let It of Go){let Vi=parseInt((sd=It.getAttribute("d"))!=null?sd:"",10),ht=parseInt((nd=It.getAttribute("r"))!=null?nd:"",10)||0,oi=parseInt((od=It.getAttribute("t"))!=null?od:"",10);Qe=Number.isFinite(oi)?oi:Qe;let _i=Vi/pr*1e3,ui=Qe/pr*1e3;for(let Ct=0;Ct<ht+1;Ct++){let ci=At(hr,{...ea,segmentNumber:ta.toString(10),segmentTime:(Qe+Ct*Vi).toString(10)}),mr=(ui!=null?ui:0)+Ct*_i,ra=mr+_i;ta++,zs.push({time:{from:mr,to:ra},url:ci})}Qe+=(ht+1)*Vi,Gs+=(ht+1)*_i}fr=Qe/pr*1e3,Ys=At(hr,{...ea,segmentNumber:ta.toString(10),segmentTime:Qe.toString(10)});let ia={time:{from:fr,to:1/0},url:Ys},Qt={type:"template",baseUrl:Di,segmentTemplateUrl:hr,initUrl:"",totalSegmentsDurationMs:Gs,segments:zs,nextSegmentBeyondManifest:ia,timescale:pr};Hs={id:ni,kind:"text",segmentReference:Qt,profiles:[],duration:v,bitrate:Ws,mime:"",codecs:"",width:0,height:0,isAuto:js}}else Hs={id:ni,isAuto:js,kind:"text",url:Di}}else{let ni=(cd=(ud=me.getAttribute("contentType"))!=null?ud:si==null?void 0:si.split("/")[0])!=null?cd:zo,js=(dd=(ld=ve.getAttribute("profiles"))==null?void 0:ld.split(","))!=null?dd:[],Bi=parseInt((pd=me.getAttribute("width"))!=null?pd:"",10),ea=parseInt((hd=me.getAttribute("height"))!=null?hd:"",10),Ws=parseInt((fd=me.getAttribute("bandwidth"))!=null?fd:"",10)/1e3,Qs=(md=me.getAttribute("frameRate"))!=null?md:"",pr=(bd=me.getAttribute("quality"))!=null?bd:void 0,Go=Qs?cy(Qs):void 0,hr=(gd=me.getAttribute("id"))!=null?gd:"id"+(_++).toString(10),zs=ni==="video"?`${ea}p`:ni==="audio"?`${Ws}Kbps`:qs,Gs=`${hr}@${zs}`,Ys=[...q,...dT,...js],fr,ta=me.querySelector("SegmentBase"),Qe=(vd=me.querySelector("SegmentTemplate"))!=null?vd:hT;if(ta){let Qt=(yd=(Sd=me.querySelector("SegmentBase Initialization"))==null?void 0:Sd.getAttribute("range"))!=null?yd:"",[It,Vi]=Qt.split("-").map(ci=>parseInt(ci,10)),ht={from:It,to:Vi},oi=(Td=me.querySelector("SegmentBase"))==null?void 0:Td.getAttribute("indexRange"),[_i,ui]=oi?oi.split("-").map(ci=>parseInt(ci,10)):[],Ct=oi?{from:_i,to:ui}:void 0;fr={type:"byteRange",url:Di,initRange:ht,indexRange:Ct}}else if(Qe){let Qt={representationId:(Id=me.getAttribute("id"))!=null?Id:void 0,bandwidth:(Ed=me.getAttribute("bandwidth"))!=null?Ed:void 0},It=parseInt((wd=Qe.getAttribute("timescale"))!=null?wd:"",10),Vi=(xd=Qe.getAttribute("initialization"))!=null?xd:"",ht=Qe.getAttribute("media"),oi=(kd=parseInt((Pd=Qe.getAttribute("startNumber"))!=null?Pd:"",10))!=null?kd:1,_i=At(Vi,Qt);if(!ht)throw new ReferenceError("No media attribute in SegmentTemplate");let ui=(Ad=Qe.querySelectorAll("SegmentTimeline S"))!=null?Ad:[],Ct=[],ci=0,mr="",ra=0;if(ui.length){let Ks=oi,Et=0;for(let br of ui){let Dt=parseInt((Rd=br.getAttribute("d"))!=null?Rd:"",10),Oi=parseInt((Md=br.getAttribute("r"))!=null?Md:"",10)||0,Xs=parseInt(($d=br.getAttribute("t"))!=null?$d:"",10);Et=Number.isFinite(Xs)?Xs:Et;let Yo=Dt/It*1e3,Ko=Et/It*1e3;for(let Js=0;Js<Oi+1;Js++){let bT=At(ht,{...Qt,segmentNumber:Ks.toString(10),segmentTime:(Et+Js*Dt).toString(10)}),Dd=(Ko!=null?Ko:0)+Js*Yo,gT=Dd+Yo;Ks++,Ct.push({time:{from:Dd,to:gT},url:bT})}Et+=(Oi+1)*Dt,ci+=(Oi+1)*Yo}ra=Et/It*1e3,mr=At(ht,{...Qt,segmentNumber:Ks.toString(10),segmentTime:Et.toString(10)})}else if((0,Ga.isNonNullable)(v)){let Et=parseInt((Ld=Qe.getAttribute("duration"))!=null?Ld:"",10)/It*1e3,br=Math.ceil(v/Et),Dt=0;for(let Oi=1;Oi<br;Oi++){let Xs=At(ht,{...Qt,segmentNumber:Oi.toString(10),segmentTime:Dt.toString(10)});Ct.push({time:{from:Dt,to:Dt+Et},url:Xs}),Dt+=Et}ra=Dt,mr=At(ht,{...Qt,segmentNumber:br.toString(10),segmentTime:Dt.toString(10)})}let mT={time:{from:ra,to:1/0},url:mr};fr={type:"template",baseUrl:Di,segmentTemplateUrl:ht,initUrl:_i,totalSegmentsDurationMs:ci,segments:Ct,nextSegmentBeyondManifest:mT,timescale:It}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ni||!si)continue;let ia={video:"video",audio:"audio",text:"text"}[ni];if(!ia)continue;dr||(dr=ia),Hs={id:Gs,kind:ia,segmentReference:fr,profiles:Ys,duration:v,bitrate:Ws,mime:si,codecs:qs,width:Bi,height:ea,fps:Go,quality:pr}}Re.language||(Re.language=ai),Re.label||(Re.label=Fs),Re.mime||(Re.mime=si),Re.codecs||(Re.codecs=qs),Re.hdr||(Re.hdr=dr==="video"&&xl(qs)),Re.representations.push(Hs)}if(dr){let me=r[dr].find(ai=>ai.id===Re.id);if(me&&Re.representations.every(ai=>ai.segmentReference.type==="template"))for(let ai of me.representations){let Fs=Re.representations.find(si=>si.id===ai.id);if(!Fs)continue;let Us=Fs.segmentReference,Di=ai.segmentReference;Di.segments.push(...Us.segments),Di.nextSegmentBeyondManifest=Us.nextSegmentBeyondManifest}else r[dr].push(Re)}}return{duration:v,streams:r,baseUrls:n,live:S}};var To=G(bt(),1),Al=G(Xe(),1),Ka=require("@vkontakte/videoplayer-shared/es2018");var Ya=(a=>(a.VP9="vp9",a.AV1="av1",a.NONE="none",a.SMOOTH="smooth",a.POWER_EFFICIENT="power_efficient",a))(Ya||{});var yo=s=>{let{webmDecodingInfo:e}=H.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:(0,Ka.assertNever)(s)}},my=({webmCodec:s,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...yo(s),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],a=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(H.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",...yo(s),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...yo(s),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...yo(s),...a,"HLS","HLS_ONDEMAND"];default:(0,Ka.assertNever)(e)}if(H.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:(0,Ka.assertNever)(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},by=({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=H.device.isMac&&H.browser.isSafari;if(H.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:(0,Ka.assertNever)(s)}else H.video.nativeHlsSupported&&!u&&!H.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"]},Rl=s=>s?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Io=s=>{if(s.size===0)return;if(s.size===1){let t=s.values().next();return(0,To.default)(t.value.split("."),0)}for(let t of s){let i=(0,To.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=s.values().next();return(0,To.default)(e.value.split("."),0)},Eo=s=>{let e=s.map(i=>Ei(i)),{codecs:t}=H.video;return A$().filter(i=>{if((0,Al.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})},wo=s=>{let e=s.map(i=>Ei(i)),{codecs:t}=H.video;return R$().filter(i=>{if((0,Al.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},Ei=s=>s.split(".")[0].replace("0",""),A$=()=>["av1","vp9","hev1","avc1"],R$=()=>["opus","mp4a"];var $y=G(bt(),1);var M$=(s,e={})=>{let i=e.timeout||1,r=performance.now();return Le.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},$$=s=>Le.clearTimeout(s),gy=s=>typeof s=="function"&&(s==null?void 0:s.toString().endsWith("{ [native code] }")),vy=!gy(Le.requestIdleCallback)||!gy(Le.cancelIdleCallback),ir=vy?M$:Le.requestIdleCallback,rr=vy?$$:Le.cancelIdleCallback;var C=require("@vkontakte/videoplayer-shared/es2018");var yy=G(bt(),1);var xo=s=>s.valid,ce=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 Hr=class extends ce{};var Sy=require("@vkontakte/videoplayer-shared/es2018");var Xa=class extends ce{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:(0,Sy.assertNever)(e)}}};var Ja=class extends ce{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 Za=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ie=class extends ce{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 es=class extends Ie{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 ts=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var is=class extends ce{constructor(e,t){super(e,t),this.data=this.content}};var ar=class extends Ie{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,c=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:c})}}}};var rs=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var as=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ss=class extends Ie{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 ns=class extends Ie{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var os=class extends Ie{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 us=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var cs=class extends Ie{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var ls=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ds=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ps=class extends Ie{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var hs=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var fs=class extends Ie{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var ms=class extends Ie{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 bs=class extends Ie{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 gs=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var vs=class extends Ie{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 Ss=class extends ce{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 C$={ftyp:Ja,moov:Za,mvhd:es,moof:ts,mdat:is,sidx:ar,trak:rs,mdia:us,mfhd:ps,tkhd:cs,traf:hs,tfhd:fs,tfdt:ms,trun:bs,minf:ls,sv3d:as,st3d:ss,prhd:ns,proj:ds,equi:os,uuid:Xa,stbl:gs,stsd:vs,avc1:Ss,unknown:Hr},Zt=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||!xo(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=C$[e];return i?new i(t,new s):new Hr(t,new s)}};var wi=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,a;xo(t)&&((a=(i=this.index)[r=t.type])!=null||(i[r]=[]),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 B$=new TextDecoder("ascii"),V$=s=>B$.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",_$=s=>{let e=new ar(s,new Zt),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})},O$=(s,e)=>{let i=new Zt().parse(s),r=new wi(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],c=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(s.buffer,c,d)},N$=s=>{let t=new Zt().parse(s),i=new wi(t),r={},a=i.findAll("uuid"),n=(0,yy.default)(a,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},F$=s=>{var r;let t=new Zt().parse(s);return(r=new wi(t).find("sidx"))==null?void 0:r.timescale},U$=(s,e)=>{let i=new Zt().parse(s),a=new wi(i).findAll("traf"),n=a[a.length-1].children.find(d=>d.type==="tfhd"),o=a[a.length-1].children.find(d=>d.type==="tfdt"),u=a[a.length-1].children.find(d=>d.type==="trun"),c=0;return u.sampleDuration.length?c=u.sampleDuration.reduce((d,p)=>d+p,0):c=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+c)/e*1e3},q$=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 Zt().parse(s),r=new wi(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},Ty={validateData:V$,parseInit:q$,getIndexRange:()=>{},parseSegments:_$,parseFeedableSegmentChunk:O$,getChunkEndTime:U$,getServerLatencyTimestamps:N$,getTimescaleFromIndex:F$};var Ts=G(Xe(),1),ei=require("@vkontakte/videoplayer-shared/es2018");var Ey=require("@vkontakte/videoplayer-shared/es2018");var Iy={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"}},wy=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=ys(s,t),r=i in Iy,a=r?Iy[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),c=n&255>>o,l=ys(u),d=c*2**((o-1)*8)+l,p=t+o,h;return p+d>s.byteLength?h=new DataView(s.buffer,s.byteOffset+p):h=new DataView(s.buffer,s.byteOffset+p,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},ys=(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},Rt=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return ys(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:(0,Ey.assertNever)(e)}},sr=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=wy(i);if(!e(r))return;r.type==="master"&&sr(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},xy=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=wy(s);return sr(r.value,({tag:a,type:n,value:o})=>(a===17143?e=Rt(o,n):a===17026?t=Rt(o,n):a===17029&&(i=Rt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Py=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],H$=[231,22612,22743,167,171,163,160,175],j$=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,c,l=!1,d=0;return sr(s,({tag:p,type:h,value:m,valueSize:b})=>{if(p===21419){let S=Rt(m,h);c=ys(S)}else p!==21420&&(c=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+b):p===357149030?a=!0:p===290298740?n=!0:p===2807729?i=Rt(m,h):p===17545?r=Rt(m,h):p===21420&&c===475249515?u=Rt(m,h):p===374648427?sr(m,({tag:S,type:v,value:y})=>S===30321?(l=Rt(y,v)===1,!1):!0):a&&n&&(0,Ts.default)(Py,p)&&(o=!0),!o}),(0,ei.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,ei.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,ei.assertNonNullable)(r,"Failed to parse webm Segment duration"),i=i!=null?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:l,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},W$=s=>{if((0,ei.isNullable)(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Q$=(s,e)=>{let t=!1,i=!1,r=o=>(0,ei.isNonNullable)(o.time)&&(0,ei.isNonNullable)(o.position),a=[],n;return sr(s,({tag:o,type:u,value:c})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=Rt(c,u));break;case 183:break;case 241:n&&(n.position=Rt(c,u));break;default:t&&(0,Ts.default)(Py,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:c,position:l}=o,d=a[u+1];return{status:"none",time:{from:c,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},z$=s=>{let e=0,t=!1;try{sr(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,Ts.default)(H$,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,Ts.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},ky={validateData:xy,parseInit:j$,getIndexRange:W$,parseSegments:Q$,parseFeedableSegmentChunk:z$};var nr=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return ky;case"mp4":return Ty}}throw new ReferenceError(`Unsupported mime type ${s}`)};var Ml=G(bt(),1);var Ay=require("@vkontakte/videoplayer-shared/es2018"),xi=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n,tvDisabled:o})=>{var c;let u=(c=a?vi(a):void 0)!=null?c:(0,Ay.videoSizeToQuality)({width:e,height:t});return u&&{id:s,quality:u,bitrate:i,size:{width:e,height:t},fps:r,streamId:n,tvDisabled:o}},Is=({id:s,bitrate:e})=>({id:s,bitrate:e}),Ry=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),My=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),$l=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,Ml.default)(i.split("."),0),isDefault:r}),Ll=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,Ml.default)(r.split("."),0)}),Cl=s=>"url"in s,dt=s=>s.type==="template";var jr=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,getCurrentStallDuration:o,manifest:u}){this.error$=new C.Subject;this.playingRepresentation$=new C.ValueSubject(void 0);this.playingRepresentationInit$=new C.ValueSubject(void 0);this.currentSegmentLength$=new C.ValueSubject(0);this.onLastSegment$=new C.ValueSubject(!1);this.fullyBuffered$=new C.ValueSubject(!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 ye;this.downloadAbortController=new ye;this.subscription=new C.Subscription;this.startWith=(0,C.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,C.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.containerParser=nr(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);(0,C.assertNonNullable)(i,"No init buffer for starting representation"),(0,C.assertNonNullable)(r,"No segments for starting representation"),await this.nativeBufferManager.addInitSegment(i),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a)}.bind(this));this.switchTo=(0,C.abortable)(this.destroyAbortController.signal,async function*(e,t=!0){var d;if((0,C.isNullable)(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);(0,C.assertNonNullable)(r,`No such representation ${e}`),(0,C.assertNonNullable)(i,`No such representation ${this.downloadingRepresentationId}`),yield this.loadInitIfNeeded(r,"high");let a=this.initData.get(r.id),n=this.segments.get(r.id);(0,C.assertNonNullable)(a,"No init buffer for switching representation"),(0,C.assertNonNullable)(n,"No segments for switching representation");let o=(d=this.getCurrentPosition())!=null?d:0,u=p=>p.segment.bufferStatus!=="fed",c=p=>{let h=this.representations.get(p.representationId);return(0,C.assertNonNullable)(h,"No itemRepresentation for previous track before switch"),p.segment.networkStatus!=="downloaded"||this.forceSwitchCondition(h,r)},l=p=>t?u(p)&&c(p):u(p);this.bufferPlaybackQueue.filter(l).forEach(p=>p.segment.bufferStatus="none"),this.bufferPlaybackQueue=this.bufferPlaybackQueue.filter(p=>!l(p)),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=(0,C.abortable)(this.downloadAbortController.signal,async function*(){let e=(0,C.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(t=>{let i=(0,C.getWindow)();this.loadByteRangeSegmentsTimeoutId=i.setTimeout(t,e),this.subscription.add((0,C.fromEvent)(i,"online").pipe((0,C.once)()).subscribe(()=>{t(),i.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}))})}.bind(this));var c;this.kind=e,this.nativeBufferManager=t,this.fetcher=r,this.tuning=a,this.getCurrentPosition=n,this.getCurrentStallDuration=o,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.baseUrls=(c=u==null?void 0:u.baseUrls)!=null?c:[],this.representations=new Map(i.map(l=>[l.id,l]))}async seek(e){await this.abort(),await this.clearBuffer(),await this.maintain(e)}async maintain(e=this.getCurrentPosition()){(0,C.isNullable)(e)||(await this.maintainPlaybackBuffer(e),await this.maintainNativeBuffer(),this.actualizeLastSegmentInfo(e))}getForwardPlaybackBufferDuration(e=this.getCurrentPosition()){let t=this.bufferPlaybackQueue.filter(a=>a.segment.networkStatus==="downloaded"),i=t[t.length-1],r=(0,C.isNonNullable)(e)&&(0,C.isNonNullable)(i)?i.segment.time.to-e:0;return Math.max(r,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){var a,n;let t=(n=(a=this.downloadingRepresentationId)!=null?a:this.playingRepresentationId)!=null?n:"",i=this.segments.get(t),r=i==null?void 0:i.find(o=>o.time.from<=e&&o.time.to>=e);return r==null?void 0:r.time.from}getRepresentationInitialTime(){var t;if((0,C.isNullable)(this.playingRepresentationId))return 0;let e=this.segments.get(this.playingRepresentationId);return((t=e==null?void 0:e[0].time.from)!=null?t:0)/1e3}calculateDurationFromSegments(e){var i;let t=this.segments.get(e);return(t?(i=(0,$y.default)(t,-1))==null?void 0:i.time.to:0)||0}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){let e=(0,C.getWindow)();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(),e.__polyfill_cancelIdleCallback_gnfi078k7d27)for(let t of this.idleCallbacks.values())e.__polyfill_cancelIdleCallback_gnfi078k7d27(t);this.idleCallbacks.clear(),e.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}forceSwitchCondition(e,t){let i=!0;if(this.kind==="video"){let r=xi(e),a=xi(t);i=(0,C.isNonNullable)(r)&&(0,C.isNonNullable)(a)&&(0,C.isHigher)(a.quality,r.quality)}else if(this.kind==="audio"){let r=Is(e),a=Is(t);i=(0,C.isNonNullable)(r==null?void 0:r.bitrate)&&(0,C.isNonNullable)(a==null?void 0: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 ye,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,ir(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():(0,C.isNonNullable)(r)?a=r:a=this.loadInit(e,t,i),await a}async loadInit(e,t="auto",i=!1){var r;try{let a=this.tuning.dash.useFetchPriorityHints?t:"auto",n=this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,a);this.initDataPromises.set(e.id,n);let{initMetadata:o,initDataView:u,segments:c}=(r=await n)!=null?r:{};if(this.initDataPromises.delete(e.id),(0,C.isNullable)(u)||(0,C.isNullable)(c))return;o&&this.parsedInitData.set(e.id,o);let l=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,l),this.segments.set(e.id,c),this.failedDownloads=0}catch(a){i&&this.error$.next({id:"LoadInits",category:C.ErrorCategory.WTF,message:"loadInit threw",thrown:a})}}async maintainNativeBuffer(){var h,m,b;let e=this.getCurrentPosition(),t=this.segments.get((h=this.downloadingRepresentationId)!=null?h:""),i=t==null?void 0:t[(t==null?void 0:t.length)-1];if((0,C.isNullable)(e)||(0,C.isNullable)(i)||this.maintainNativeBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex||this.preloadOnly)return;this.maintainNativeBufferMutex=!0;let r=this.bufferPlaybackQueue.find(S=>this.withinInterval(e,S.segment.time)),a=this.bufferPlaybackQueue.find(S=>S.segment.bufferStatus!=="fed"),n=this.initData.get((m=a==null?void 0:a.representationId)!=null?m:""),o=this.bufferPlaybackQueue[0],u=this.downloadAbortController.signal,l=((b=this.getCurrentStallDuration())!=null?b:0)>0;this.tuning.dash.useBufferHoldingOnlyOnStall&&l&&(l=e>0);let d=Math.min(this.tuning.dash.minSafeBufferToPlay,i.time.to-e),p=l?this.getForwardPlaybackBufferDuration()>=d:!0;(0,C.isNonNullable)(n)&&(0,C.isNonNullable)(a)&&(0,C.isNonNullable)(r)&&this.playingRepresentationId!==a.representationId&&this.withinAppendInterval(e,a.segment.time)&&(a===r||r.segment.bufferStatus==="fed")&&(await this.abortNativeBuffer(),await this.nativeBufferManager.addInitSegment(n,this.downloadAbortController.signal),this.playingRepresentationId=a.representationId,this.playingRepresentation$.next(this.playingRepresentationId)),(0,C.isNonNullable)(a)&&this.withinAppendInterval(e,a.segment.time)&&p&&(a.segment.loadedBytes===a.segment.size&&a.segment.bufferStatus==="none"?await this.appendSegmentFully(a,u):await this.appendSegmentPartially(a,u)),(0,C.isNonNullable)(o)&&this.withinRemoveInterval(e,o.segment.time)&&await this.removeSegment(o,u),this.pruneVirtualBuffer(e),this.maintainNativeBufferMutex=!1}async maintainPlaybackBuffer(e){(0,C.assertNonNullable)(this.downloadingRepresentationId);let t=this.segments.get(this.downloadingRepresentationId),i=this.representations.get(this.downloadingRepresentationId);if((0,C.isNullable)(t)||(0,C.isNullable)(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);(0,C.isNonNullable)(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0: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){var r;let t=this.segments.get((r=this.downloadingRepresentationId)!=null?r:"");if((0,C.isNullable)(t)||t.length===0)return;let i=t[(t==null?void 0:t.length)-1];(0,C.isNullable)(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){(0,C.assertNonNullable)(this.downloadingRepresentationId);let i=this.getPlaybackBufferState(),r,a;(0,C.isNonNullable)(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(0,C.isNonNullable)(e)?e+r>=t&&e<i:!1}withinAppendInterval(e,{from:t,to:i}){let{actionTimeShiftFromSegment:r}=this.tuning.dash;return(0,C.isNonNullable)(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(0,C.isNonNullable)(e)?e-i>t:!1}async appendSegmentFully(e,t){if((0,C.isNullable)(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((0,C.isNullable)(e.segment.data)||(0,C.isNullable)(e.segment.loadedBytes)||(0,C.isNullable)(e.segment.feedingBytes)||(0,C.isNullable)(e.segment.fedBytes)||(0,C.isNullable)(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!=null&&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||(0,C.isNonNullable)(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)(0,C.isNonNullable)(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())(0,C.isNonNullable)(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)}};var St=require("@vkontakte/videoplayer-shared/es2018"),Po=class extends jr{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=(0,St.now)(),this.failedDownloads=0}catch(o){this.abortDownloadingItems(),(0,St.isAbortError)(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(_e(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=(0,St.now)(),await this.onSomeDataLoaded({downloadingItems:e,dataView:o,loaded:u,signal:i,globalFrom:a?a.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:St.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}},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||(0,St.isNullable)(o)||(0,St.isNullable)(r)||n.aborted))for(let u of e){let{segment:c}=u,l=c.byte.from-r,d=c.byte.to-r,p=d-l+1,h=l<a,m=d<=a;c.size=p,h&&(c.networkStatus==="downloading"&&c.bufferStatus==="none"&&m?(c.data=new DataView(t.buffer,t.byteOffset+l,p),this.currentVirtualBufferSize+=c.size,this.onItemFullyDownloaded(u),c.loadedBytes=Math.min(p,a-l),await this.onDownloadItem(u)):(0,St.isNonNullable)(c.feedingBytes)&&this.tuning.dash.enableSubSegmentBufferFeeding&&c.networkStatus==="downloading"&&(c.loadedBytes=Math.min(p,a-l),m&&(this.currentVirtualBufferSize+=c.size,this.onItemFullyDownloaded(u)),c.loadedBytes>c.feedingBytes&&(c.data=new DataView(t.buffer,t.byteOffset+l,c.loadedBytes),await this.onDownloadItem(u))))}}updateRepresentationBaseUrl(e,t){if(_e(e.segmentReference))throw new Error("Representation is not byte range type");e.segmentReference.url=t}};var Mt=require("@vkontakte/videoplayer-shared/es2018"),Wr=class extends jr{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=(0,Mt.now)(),(0,Mt.isNullable)(o))return;let u=e[0],c=new DataView(o);u.segment.size=c.byteLength,u.segment.loadedBytes=c.byteLength,u.segment.data=c,this.onItemFullyDownloaded(u),await this.onDownloadItem(u),this.failedDownloads=0}catch(o){this.abortDownloadingItems(),(0,Mt.isAbortError)(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=(0,Mt.now)(),await this.onSomeDataLoaded({downloadingItems:e,dataView:n,loaded:o,signal:r,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:Mt.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}},signal:r,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}getFetchUrl(e,t){if(!_e(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||(0,Mt.isNullable)(u)||(0,Mt.isNullable)(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(!_e(e.segmentReference))throw new Error("Representation is not template type");e.segmentReference.baseUrl=t}};var Dl=G(Wa(),1),Ly=G(bt(),1);var Oe=require("@vkontakte/videoplayer-shared/es2018");var ko=class extends Wr{constructor(t,i,r,a){super(t,i,r,a);this.currentLiveSegmentServerLatency$=new Oe.ValueSubject(0);this.currentLowLatencySegmentLength$=new Oe.ValueSubject(0);this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.isActiveLowLatency=a.isActiveLowLatency}updateManifest(t){var r,a,n;if(!t||[...this.segments.values()].every(o=>!o.length))return;let i=(0,Dl.default)(t.streams[this.kind],o=>o.representations);for(let o of i){if((0,Oe.isNullable)(o)||!_e(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>({...h,networkStatus:"none",bufferStatus:"none",size:void 0})),c=100,l=(r=this.segments.get(o.id))!=null?r:[],d=(n=(a=(0,Ly.default)(l,-1))==null?void 0:a.time.to)!=null?n:0,p=u==null?void 0:u.findIndex(h=>d>=h.time.from+c&&d<=h.time.to+c);if(p===-1){let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(p+1);this.segments.set(o.id,[...l,...h])}this.representations.set(o.id,o)}}proceedLowLatencyLive(){let t=this.downloadingRepresentationId;(0,Oe.assertNonNullable)(t);let i=this.segments.get(t);if(i!=null&&i.length){let r={representationId:t,segmentIndex:i.length-1,segment:i[i.length-1]};this.updateLowLatencyLive(r)}}getLiveSegmentsToLoadState(t){let i=t==null?void 0:t.streams[this.kind],r=(0,Dl.default)(i,n=>n.representations).find(n=>n.id===this.downloadingRepresentationId);if((0,Oe.isNullable)(r))return;let a=this.segments.get(r.id);if(a!=null&&a.length)return{from:a[0].time.from,to:a[a.length-1].time.to}}getRepresentationInitialTime(){var r;if((0,Oe.isNullable)(this.playingRepresentationId))return 0;let t=(r=this.representations.get(this.playingRepresentationId))==null?void 0:r.segmentReference;return(0,Oe.isNullable)(t)||!_e(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),(0,Oe.isNullable)(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){var n;let i=t.segment.data,r=(n=this.representations.get(t.representationId))==null?void 0:n.segmentReference;if((0,Oe.isNullable)(t.segment.data)||(0,Oe.isNullable)(r)||!_e(r))return;let a=this.containerParser;if(t.segment.isCurrentLowLatency){let{timescale:o}=r;t.segment.time.to=a.getChunkEndTime(i,o)}}updateLowLatencyLive(t){var r;let i=0;for(let a of this.representations.values()){let n=a.segmentReference;if(!_e(n))return;let o=(r=this.segments.get(a.id))!=null?r:[],u=o.find(l=>Math.floor(l.time.from)===Math.floor(t.segment.time.from));if(u!=null&&u.isCurrentLowLatency&&(u.time.to=t.segment.time.to,i=u.time.to-u.time.from,u.isCurrentLowLatency=!1),!!!o.find(l=>Math.floor(l.time.from)===Math.floor(t.segment.time.to))&&this.isActiveLowLatency()){let l=Math.round(t.segment.time.to*n.timescale/1e3).toString(10),d=At(n.segmentTemplateUrl,{segmentTime:l});o.push({networkStatus:"none",bufferStatus:"none",time:{from:t.segment.time.to,to:t.segment.time.to+this.tuning.dash.bufferTolerance},url:d,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){var a;try{let n=this.tuning.dash.useFetchPriorityHints?i:"auto",o=this.fetcher.fetchRepresentation(t.segmentReference,this.containerParser,n);this.initDataPromises.set(t.id,o);let{initMetadata:u,initDataView:c,segments:l}=(a=await o)!=null?a:{};if(this.initDataPromises.delete(t.id),(0,Oe.isNullable)(c)||(0,Oe.isNullable)(l))return;u&&this.parsedInitData.set(t.id,u);let d=this.getActualLiveStartingSegments(t.segmentReference);this.segments.has(t.id)||this.segments.set(t.id,d);let p=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);this.initData.set(t.id,p),this.failedDownloads=0}catch(n){r&&this.error$.next({id:"LoadInits",category:Oe.ErrorCategory.WTF,message:"loadInit threw",thrown:n})}}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 Es=class{static getBufferManager(e,t,i,r){var a;return(a=r.manifest)!=null&&a.live?new ko(e,t,i,r):_e(i[0].segmentReference)?new Wr(e,t,i,r):new Po(e,t,i,r)}};var Ye=require("@vkontakte/videoplayer-shared/es2018");var Pi=require("@vkontakte/videoplayer-shared/es2018");var G$=18,Cy=!1;try{Cy=H.browser.isSafari&&!!H.browser.safariVersion&&H.browser.safariVersion<=G$}catch(s){console.error(s)}var Bl=class{constructor(e,t=!1){this.bufferFull$=new Pi.Subject;this.error$=new Pi.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Pi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};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)};Cy&&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(){var r;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((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Pi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:(0,Pi.assertNever)(t)}}},Dy=Bl;var ki=(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 ws=class{constructor(e){this.error$=new Ye.Subject;this.subscription=new Ye.Subscription;this.mediaSource=e}init(e,t,i=!1){this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e}; codecs="${t}"`),this.sourceBufferTaskQueue=new Dy(this.sourceBuffer,i),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(r=>this.error$.next(r))),this.subscription.add((0,Ye.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Ye.ErrorCategory.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((0,Ye.isNullable)(t))return Promise.resolve(!1);let i=!0;await this.sourceBufferTaskQueue.abort();for(let r of t)i&&(i=await this.sourceBufferTaskQueue.remove(r.from,r.to,e));return i}warmUpMediaSource(){!(0,Ye.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}getBufferState(){if((0,Ye.isNullable)(this.sourceBuffer)||!Se(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(0,Ye.isNullable)(this.sourceBuffer)||!Se(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,Ye.isNullable)(e)?0:ki(this.sourceBuffer.buffered,e)}async abortBuffer(e){return(0,Ye.isNullable)(this.sourceBuffer)?!1:this.sourceBufferTaskQueue.abort(e)}destroy(){var e;if(this.subscription.unsubscribe(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null}};var Ao=(s,e)=>{s.video.forEach(t=>{t.representations.forEach(i=>{var c;let{height:r,codecs:a,fps:n}=i,o=(c=e.find(([l,d,p])=>l===`${r}p`&&Ei(a)===p))==null?void 0:c[1],u=By(o)&&By(n)&&n>o;i.tvDisabled=u})})};function By(s){return typeof s=="number"&&Number.isInteger(s)}var Y$=["timeupdate","progress","play","seeked","stalled","waiting"],Vy=["timeupdate","progress","loadeddata","playing","seeked"],Qr=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.nativeBufferManagers=[];this.subscription=new I.Subscription;this.subscriptionRemovable=new I.SubscriptionRemovable;this.representationSubscription=new I.Subscription;this.forceEnded$=new I.Subject;this.destroyController=new ye;this.state$=new ae("none");this.currentVideoRepresentation$=new I.ValueSubject(void 0);this.currentVideoRepresentationInit$=new I.ValueSubject(void 0);this.currentAudioRepresentation$=new I.ValueSubject(void 0);this.currentVideoSegmentLength$=new I.ValueSubject(0);this.currentAudioSegmentLength$=new I.ValueSubject(0);this.error$=new I.Subject;this.manifestRequested=new I.Subject;this.manifestReceived=new I.Subject;this.firstBytesRequested=new I.Subject;this.firstBytesReceived=new I.Subject;this.lastConnectionType$=new I.ValueSubject(void 0);this.lastConnectionReused$=new I.ValueSubject(void 0);this.lastRequestFirstBytes$=new I.ValueSubject(void 0);this.lastConnectionMetrics$=new I.ValueSubject(void 0);this.lastDownloadMetrics$=new I.ValueSubject(void 0);this.currentLiveTextRepresentation$=new I.ValueSubject(null);this.isLive$=new I.ValueSubject(!1);this.isActiveLive$=new I.ValueSubject(!1);this.isLowLatency$=new I.ValueSubject(!1);this.liveDuration$=new I.ValueSubject(0);this.liveSeekableDuration$=new I.ValueSubject(0);this.liveAvailabilityStartTime$=new I.ValueSubject(0);this.liveStreamStatus$=new I.ValueSubject(void 0);this.currentBuffer$=new I.ValueSubject({from:0,to:0});this.bufferLength$=new I.ValueSubject(0);this.nativeBufferLength$=new I.ValueSubject(0);this.liveLatency$=new I.ValueSubject(void 0);this.liveLoadBufferLength$=new I.ValueSubject(0);this.livePositionFromPlayer$=new I.ValueSubject(0);this.currentStallDuration$=new I.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new I.ValueSubject(0);this.fetcherRecoverableError$=new I.Subject;this.fetcherError$=new I.Subject;this.initRepresentations=(0,I.abortable)(this.destroyController.signal,async function*(e,t,i){var a;this.tracer.log("initRepresentationsStart",(0,I.flattenObject)({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,getCurrentStallDuration:()=>this.currentStallDuration$.getValue(),isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest};this.createBuffers(r,e,t,i),this.initRepresentationSubscriptions(),yield this.waitStreamToOpen(),this.setSourceDuration(),(0,I.assertNonNullable)(this.videoBufferManager),yield Promise.all([this.videoBufferManager.startWith(e),t?(a=this.audioBufferManager)==null?void 0:a.startWith(t):Promise.resolve()]),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.fetchManifest=(0,I.abortable)(this.destroyController.signal,async function*(){try{return yield this.fetcher.fetchManifest(this.manifestUrlString)}catch(e){(0,I.isNullable)(this.manifest)&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:I.ErrorCategory.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 bo({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){var r;this.tracer.log("initManifest"),this.state$.startTransitionTo("manifest_ready"),this.element=e,this.manifestUrlString=this.prepareManifestUrlString(t,i),this.manifest=await this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:I.ErrorCategory.PARSER,message:"No playable video representations"})}initBuffer(){var t,i;(0,I.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,I.merge)(...Y$.map(r=>(0,I.fromEvent)(this.element,r)),(0,I.fromEvent)((0,I.getWindow)(),"online"),(0,I.interval)(this.tuning.dash.tickMaintainInterval)).subscribe(()=>this.tick(),r=>this.error$.next({id:"DashVKPlayer",category:I.ErrorCategory.WTF,message:"Internal logic error",thrown:r})));let e=[...(i=(t=this.source)==null?void 0:t.activeSourceBuffers)!=null?i:[]];this.subscription.add((0,I.merge)(...e.map(r=>(0,I.fromEvent)(r,"updateend"))).subscribe(r=>this.reinitDecoderIfNeeded())),this.subscription.add((0,I.fromEvent)(this.element,"waiting").subscribe(r=>{this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=(0,I.interval)(this.tuning.dash.stallWatchdogInterval).subscribe(()=>this.stallWatchdogIntervalCallback(),a=>this.error$.next({id:"StallWatchdogCallback",category:I.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:a})),this.subscriptionRemovable.add(this.stallWatchdogSubscription)}))}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return r==null?void 0:r.switchTo(t,i)}async seek(e,t=!1){var r,a,n,o,u;(0,I.assertNonNullable)(this.element),(0,I.assertNonNullable)(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),this.element.currentTime=i/1e3,H.browser.isSafari?(await((o=this.audioBufferManager)==null?void 0:o.seek(i)),await this.videoBufferManager.seek(i)):(await this.videoBufferManager.seek(i),await((u=this.audioBufferManager)==null?void 0:u.seek(i))),this.tracer.log("seek",(0,I.flattenObject)({requestedPosition:e,forcePrecise:t,position:i}))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){(0,I.isNonNullable)(this.element)&&(0,I.isNonNullable)(this.source)&&(0,I.isNonNullable)(e)&&this.isStreamEnded&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.nativeBufferManagers.forEach(i=>i.warmUpMediaSource())}calculateDurationFromSegments(e){var t,i;return Math.max(((t=this.videoBufferManager)==null?void 0:t.calculateDurationFromSegments(e))||0,((i=this.audioBufferManager)==null?void 0:i.calculateDurationFromSegments(e))||0)}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}getCodecs(){var e;return(e=this.manifest)==null?void 0:e.codecs}setBufferTarget(e){this.bufferManagers.forEach(t=>t.setTarget(e))}setPreloadOnly(e){this.bufferManagers.forEach(t=>t.setPreloadOnly(e))}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.nativeBufferManagers.forEach(r=>r.destroy()),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&(0,I.getWindow)().clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),(0,I.isNonNullable)(this.source)&&this.isStreamNotOpen&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}get isStreamNotOpen(){var e;return((e=this.source)==null?void 0:e.readyState)!=="open"}async reinitDecoderIfNeeded(e=!1){var r,a;let t=(a=(r=this.videoNativeBufferManager)==null?void 0:r.getBufferState())!=null?a:[];if((0,I.isNullable)(this.element)||!t.length)return;let i=this.element.currentTime*1e3;this.element.readyState<3&&t.some(n=>i>=n.from&&i<=n.to)&&(e?await this.seek(i):this.element.currentTime=this.element.currentTime)}async stallWatchdogIntervalCallback(){(0,I.assertNonNullable)(this.element),(0,I.assertNonNullable)(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)){if(this.tuning.dash.useNewStallExitPolicy)return this.seek(this.element.currentTime*1e3);throw new Error(`Stall timeout exceeded: ${t} ms`)}await this.restoreAfterDeepStall(i),this.tracer.log("stallIntervalCallback",(0,I.flattenObject)(i))}isStallExceeded(e){var p,h,m,b,S,v,y,x;let{crashOnStallTimeout:t,crashOnStallTWithoutDataTimeout:i}=this.tuning.dash,r=(0,I.now)(),a=100,n=(h=(p=this.videoBufferManager)==null?void 0:p.lastDataObtainedTimestamp)!=null?h:0;this.videoLastDataObtainedTimestamp$.next(n);let o=(b=(m=this.audioBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?b:0,u=(v=(S=this.videoBufferManager)==null?void 0:S.getForwardPlaybackBufferDuration())!=null?v:0,c=(x=(y=this.audioBufferManager)==null?void 0:y.getForwardPlaybackBufferDuration())!=null?x:0,l=(0,I.isNonNullable)(this.videoBufferManager)&&u<a&&r-n>i,d=(0,I.isNonNullable)(this.audioBufferManager)&&c<a&&r-o>i;return(l||d)&&e>i||e>=t}async updateManifest(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=await this.fetchManifest();if((0,I.isNullable)(e))return null;let t=this.parseManifest(e);if(!t)return null;let i=this.getResultManifest(t);return this.tracer.log("updateManifestEnd",(0,I.flattenObject)(i)),i}parseManifest(e){var t;try{return So(e!=null?e:"",this.manifestUrlString)}catch(i){let r=(t=ho(e))!=null?t:{id:"ManifestParsing",category:I.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:i};this.error$.next(r)}}getResultManifest(e){let t={text:e.streams.text,video:[],audio:[]},i=(o,u,c)=>{var l,d,p,h;return!!((d=(l=this.element)==null?void 0:l.canPlayType)!=null&&d.call(l,u)&&((h=(p=ut())==null?void 0:p.isTypeSupported)!=null&&h.call(p,`${u}; codecs="${c}"`))||o==="text")},r,a;for(let o of["video","audio"]){let c=e.streams[o].filter(({mime:d,codecs:p})=>i(o,d,p));t[o]=c;let l;if(this.tuning.dash.codecsPrioritizeEnabled){let d=c.map(({codecs:p})=>p);o==="audio"&&(a=wo(d),l=a[0]),o==="video"&&(r=Eo(d),this.forceVideoCodec&&(0,_y.default)(r,this.forceVideoCodec)?l=this.forceVideoCodec:l=r[0]),l&&(t[o]=c.filter(({codecs:p})=>Ei(p)===l))}else{let d=new Set(c.map(({codecs:p})=>p));l=Io(d),l&&(t[o]=c.filter(({codecs:p})=>p.startsWith(l)))}if(o==="video"){let d=this.tuning.preferHDR,p=t.video.some(b=>b.hdr),h=t.video.some(b=>!b.hdr);H.display.isHDR&&d&&p?t.video=t.video.filter(b=>b.hdr):h&&(t.video=t.video.filter(b=>!b.hdr));let{videoStreamRepresentaionsFilter:m}=this.tuning.dash;m.length&&Ao(t,m)}}let n={...e,streams:t};return this.tuning.dash.codecsPrioritizeEnabled&&(n.codecs={video:r,audio:a}),n}stopStallWatchdogSubscription(){var e;(e=this.stallWatchdogSubscription)==null||e.unsubscribe(),this.currentStallDuration$.next(0)}createBuffers(e,t,i,r){(0,I.assertNonNullable)(this.manifest),(0,I.assertNonNullable)(this.element);let a=c=>{this.representationSubscription.add((0,I.fromEvent)(c,"error").pipe((0,I.filter)(l=>{var d;return!!((d=this.element)!=null&&d.played.length)})).subscribe(l=>{this.error$.next({id:"VideoSource",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:l})}))};this.source=vn();let n=(0,I.getWindow)().document,o=n.createElement("source");if(a(o),o.src=URL.createObjectURL(this.source),this.element.appendChild(o),xr())if(r){let c=n.createElement("source");a(c),c.type="application/x-mpegurl",c.src=r.url,this.element.appendChild(c)}else this.element.disableRemotePlayback=!0;let u=this.manifest.streams.video.reduce((c,l)=>[...c,...l.representations],[]);if(this.videoNativeBufferManager=new ws(this.source),this.videoBufferManager=Es.getBufferManager("video",this.videoNativeBufferManager,u,e),this.bufferManagers=[this.videoBufferManager],this.nativeBufferManagers=[this.videoNativeBufferManager],(0,I.isNonNullable)(i)){this.audioNativeBufferManager=new ws(this.source);let c=this.manifest.streams.audio.reduce((l,d)=>[...l,...d.representations],[]);this.audioBufferManager=Es.getBufferManager("audio",this.audioNativeBufferManager,c,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=>{var i;e&&(this.timeoutSourceOpenId=(0,I.getWindow)().setTimeout(()=>{if(this.isStreamNotOpen){t();return}this.error$.next({id:"OpenOfStream",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(i=this.source)==null||i.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&(0,I.getWindow)().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(this.fetcher.lastConnectionMetrics$.subscribe(this.lastConnectionMetrics$)),this.representationSubscription.add(this.fetcher.lastDownloadMetrics$.subscribe(this.lastDownloadMetrics$)),this.representationSubscription.add((0,I.merge)(...this.bufferManagers.map(e=>e.error$)).subscribe(this.error$)),(0,I.assertNonNullable)(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((0,I.merge)(...Vy.map(e=>(0,I.fromEvent)(this.element,e))).pipe((0,I.map)(e=>{var t;return(t=this.videoBufferManager)==null?void 0:t.getPlaybackBufferState()}),(0,I.filter)(I.isNonNullable),(0,I.map)(({from:e,to:t})=>({from:e/1e3,to:t/1e3}))).subscribe(this.currentBuffer$)),this.representationSubscription.add((0,I.merge)(...Vy.map(e=>(0,I.fromEvent)(this.element,e))).pipe((0,I.map)(e=>{var t,i,r,a,n,o;return Math.min((i=(t=this.videoBufferManager)==null?void 0:t.getForwardPlaybackBufferDuration())!=null?i:0,(a=(r=this.audioBufferManager)==null?void 0:r.getForwardPlaybackBufferDuration())!=null?a:0,(o=(n=this.audioBufferManager)==null?void 0:n.getForwardPlaybackBufferDuration())!=null?o:0)}),(0,I.filterChanged)()).subscribe(this.bufferLength$)),this.representationSubscription.add(this.nativeBufferLength$.pipe((0,I.filter)(e=>e>this.tuning.dash.bufferEmptinessTolerance)).subscribe(e=>this.stopStallWatchdogSubscription()))}initTracerSubscription(){let e=(0,I.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}async tick(){var r,a,n;if((0,I.isNullable)(this.element)||(0,I.isNullable)(this.videoBufferManager)||this.isStreamNotOpen)return;let e=this.element.currentTime*1e3,i=((a=(r=this.videoNativeBufferManager)==null?void 0:r.getBufferState())!=null?a:[]).find(o=>e>=o.from&&e<=o.to);this.nativeBufferLength$.next(i?i.to-e:0),await this.videoBufferManager.maintain(e),await((n=this.audioBufferManager)==null?void 0:n.maintain(e))}};var fe=require("@vkontakte/videoplayer-shared/es2018");var Ro=class extends Qr{constructor(e){super(e)}prepareManifestUrlString(e,t){return e}initRepresentationSubscriptions(){super.initRepresentationSubscriptions(),this.initDisableStallWatchdogSubscription(),this.initEndOfVideoSubscription()}setSourceDuration(){var t;(0,fe.assertNonNullable)(this.manifest),(0,fe.assertNonNullable)(this.source);let e=[(t=this.manifest.duration)!=null?t:0,...(0,Vl.default)((0,Vl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],i=>i.representations),i=>{let r=[];return i.duration&&r.push(i.duration),_e(i.segmentReference)&&i.segmentReference.totalSegmentsDurationMs&&r.push(i.segmentReference.totalSegmentsDurationMs),r})];this.source.duration=Math.max(...e)/1e3}async restoreAfterDeepStall(e){var i,r;(0,fe.assertNonNullable)(this.element);let t=this.element.currentTime*1e3;await Promise.all([(i=this.videoBufferManager)==null?void 0:i.maintain(t),(r=this.audioBufferManager)==null?void 0:r.maintain(t)]),e.position=t}initDisableStallWatchdogSubscription(){(0,fe.assertNonNullable)(this.element);let e=(0,fe.merge)((0,fe.fromEvent)(this.element,"ended"),this.forceEnded$),t=this.nativeBufferLength$.pipe((0,fe.filter)(i=>i>this.tuning.dash.bufferEmptinessTolerance));this.representationSubscription.add((0,fe.merge)(e,t).subscribe(i=>this.stopStallWatchdogSubscription()))}initEndOfVideoSubscription(){let e=(0,fe.merge)(...this.bufferManagers.map(a=>a.fullyBuffered$)).pipe((0,fe.map)(()=>this.bufferManagers.every(a=>a.fullyBuffered$.getValue()))),t=(0,fe.merge)(...this.bufferManagers.map(a=>a.onLastSegment$)).pipe((0,fe.map)(()=>this.bufferManagers.some(a=>a.onLastSegment$.getValue()))),i=(0,fe.combine)({allBuffersFull:e,someBufferEnded:t}).pipe((0,fe.filterChanged)(),(0,fe.map)(({allBuffersFull:a,someBufferEnded:n})=>a&&n),(0,fe.filter)(a=>a)),r=()=>{var a;try{(a=this.source)==null||a.endOfStream()}catch(n){this.error$.next({id:"EndOfStream",category:fe.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:n})}};this.representationSubscription.add((0,fe.merge)(this.forceEnded$,i).pipe((0,fe.filter)(a=>(0,fe.isNonNullable)(this.source)&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(n=>!n.updating))).subscribe(r))}};var xs=class extends Zi{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,zr.filterChanged)(),(0,zr.filter)(a=>(0,zr.isNonNullable)(a))).subscribe(a=>{let n=this.player.calculateDurationFromSegments(a);n&&this.params.output.duration$.next(n/1e3)},r))}getPlayer(){return new Ro({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)}};var be=require("@vkontakte/videoplayer-shared/es2018");var Ps=require("@vkontakte/videoplayer-shared/es2018"),Ai=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Ps.ValueSubject(e.initial),this.debounced$=new Ps.ValueSubject(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ze(`raw_${t}`),this.smoothedSeries$=new ze(`smoothed_${t}`),this.reportedSeries$=new ze(`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)&&((0,Ps.isNullable)(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var Mo=class extends Ai{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Jt(this.slow,e,this.params.emaAlphaSlow),this.fast=Jt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var $o=class extends Ai{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=ll(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Jt(this.emaSmoothed,e,this.params.emaAlpha);let i=Lv(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Lo=class extends Ai{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?Jt(this.smoothed,t,this.params.emaAlpha):t}};var ti=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Mo({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new $o({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 Lo({initial:e,label:"liveEdgeDelay",...t})}};var Y=require("@vkontakte/videoplayer-shared/es2018");var Gr=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)};var Co=require("@vkontakte/videoplayer-shared/es2018");var ks=class s{constructor(e,t){this.currentRepresentation$=new Co.ValueSubject(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!(0,Co.isNullable)(e))for(let i of this.representations)for(let r of i){let a=r.segmentReference,n=a.segments.length,o=a.segments[0].time.from,u=a.segments[n-1].time.to;if(e<o||e>u)continue;let c=a.segments.find(l=>l.time.from<=e&&l.time.to>=e);!c||((t=this.currentSegment)==null?void 0:t.time.from)===c.time.from&&this.currentSegment.time.to===c.time.to||(this.currentSegment=c,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(c.url,a.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?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!=null&&e.some(t=>s.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&_e(t.segmentReference))}};var Do=class extends Qr{constructor(t){super(t);this.liveStreamEndTimestamp=0;this.liveWasInterrupted=!1;this.liveBuffer=ti.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...t.tuning.dashCmafLive.lowLatency.bufferEstimator})}async seek(t){(0,Y.assertNonNullable)(this.element),this.updateManifestUrlWithTimeOffset(t),this.manifest=await this.updateManifest(),await this.forcePositionToRepresentationInitialTime()}initBuffer(){super.initBuffer(),this.forcePositionToRepresentationInitialTime()}async forcePositionToRepresentationInitialTime(){var r;let t=this.videoBufferManager,i=(r=t==null?void 0:t.getRepresentationInitialTime())!=null?r:0;await super.seek(i,!1)}async tick(){var i,r,a;await super.tick();let t=((r=(i=this.element)==null?void 0:i.currentTime)!=null?r:0)*1e3;(a=this.liveTextManager)==null||a.maintain(t)}setSourceDuration(){(0,Y.assertNonNullable)(this.source),this.source.duration=Number.MAX_SAFE_INTEGER}isStallExceeded(t){let{keepSilentStallWatchdogWhenNotActive:i}=this.tuning.dashCmafLive,a=this.liveStreamStatus$.getValue()==="active";return(!i||a)&&super.isStallExceeded(t)}async restoreAfterDeepStall(t){let{liveStallReinitInterval:i}=this.tuning.dash,{keepSilentStallWatchdogWhenNotActive:r}=this.tuning.dashCmafLive,a=this.currentStallDuration$.getValue(),o=this.liveStreamStatus$.getValue()==="active";if(a%i===0){let u=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);t.liveLastOffset=u,!o&&r?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(u),this.manifest=await this.updateManifest(),await this.forcePositionToRepresentationInitialTime()):this.seek(u).catch(c=>{this.error$.next({id:"stallIntervalCallback",category:Y.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:c})})}}async updateManifest(){var l,d;let t=await super.updateManifest();if((0,Y.isNullable)(t))return null;if((0,Y.isNullable)(t.live))return this.error$.next({id:"ManifestParsing",category:Y.ErrorCategory.PARSER,message:"MPD doesnt contain live section for live stream"}),null;this.isLive$.next(!0);let{availabilityStartTime:i,latestSegmentPublishTime:r,streamIsUnpublished:a,streamIsAlive:n}=t.live,o=((l=t.duration)!=null?l:0)/1e3;this.liveSeekableDuration$.next(-1*o),this.liveDuration$.next((r-i)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let u="active";if(n||(u=a?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(u),this.bufferManagers.forEach(p=>p.updateManifest(t)),(d=this.liveTextManager)==null||d.updateLive(t),n&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let p=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seek(p).catch(h=>{this.error$.next({id:"updateManifest",category:Y.ErrorCategory.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:h})})}return t}prepareManifestUrlString(t,i){return Ae(t,i,2)}updateManifestUrlWithTimeOffset(t){let i=this.liveStreamStatus$.getValue()!=="active"?(0,Y.now)()-this.liveStreamEndTimestamp:0,r=this.normalizeLiveOffset(t+i);this.isActiveLive$.next(r===0),this.manifestUrlString=Ae(this.manifestUrlString,r,2)}createBuffers(t,i,r,a){(0,Y.assertNonNullable)(this.manifest),super.createBuffers(t,i,r,a),ks.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new ks(this.manifest.streams.text,t))}initRepresentationSubscriptions(){(0,Y.assertNonNullable)(this.element),(0,Y.assertNonNullable)(this.videoBufferManager),this.isActiveLive$.next(this.isLive$.getValue()),super.initRepresentationSubscriptions();let t=this.videoBufferManager,i=this.bufferManagers;this.initStreamDurationOnPauseSubscription(),this.initLiveChangePlaybackRateSubscriptions(),this.initLiveDurationSubscriptions(t),this.initLiveBufferInfoSubscriptions(t,i),this.initLiveMaintainSubscription(i),(0,Y.isNonNullable)(this.liveTextManager)&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$))}initStreamDurationOnPauseSubscription(){(0,Y.assertNonNullable)(this.element);let{liveUpdateInterval:t}=this.tuning.dash,i=()=>(0,Y.interval)(t).subscribe(async r=>{let a=pi(this.manifestUrlString,2);this.manifestUrlString=Ae(this.manifestUrlString,a+t,2),this.liveStreamStatus$.getValue()==="active"&&(this.manifest=await this.updateManifest())});this.representationSubscription.add((0,Y.fromEvent)(this.element,"pause").subscribe(r=>{this.livePauseWatchdogSubscription=i(),this.representationSubscription.add(this.livePauseWatchdogSubscription)})),this.representationSubscription.add((0,Y.fromEvent)(this.element,"play").subscribe(r=>{var a;return(a=this.livePauseWatchdogSubscription)==null?void 0:a.unsubscribe()}))}initLiveDurationSubscriptions(t){this.representationSubscription.add(this.liveDuration$.pipe((0,Y.filterChanged)()).subscribe(i=>this.liveStreamEndTimestamp=(0,Y.now)())),this.representationSubscription.add(t.currentLowLatencySegmentLength$.subscribe(i=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!i)return;let r=this.liveSeekableDuration$.getValue()-i/1e3;this.liveSeekableDuration$.next(Math.max(r,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+i/1e3)}))}initLiveChangePlaybackRateSubscriptions(){this.representationSubscription.add((0,Y.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,Y.map)(({isActiveLive:t,isLowLatency:i})=>t&&i),(0,Y.filterChanged)(),(0,Y.filter)(t=>!this.isManualDecreasePlaybackInLive())).subscribe(t=>Gr(this.element,1))),this.representationSubscription.add((0,Y.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,Y.filter)(t=>!this.isManualDecreasePlaybackInLive())).subscribe(({liveBuffer:t,isActiveLive:i,isLowLatency:r})=>{if(!r||!i)return;let a=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,n=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,o=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,u=t-a,c=1;Math.abs(u)>n&&(c=1+Math.sign(u)*o),Gr(this.element,c)}))}initLiveBufferInfoSubscriptions(t,i){this.representationSubscription.add((0,Y.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,Y.filter)(({bufferLength:r,isActiveLive:a,isLowLatency:n})=>a&&n&&!!r),(0,Y.map)(({bufferLength:r})=>r)).subscribe(this.liveBuffer)),this.representationSubscription.add(this.bufferLength$.subscribe(r=>{var n,o;let a=0;if(r){let u=((o=(n=this.element)==null?void 0:n.currentTime)!=null?o:0)*1e3;a=Math.min(...i.map(l=>{var d,p;return(p=(d=l.getLiveSegmentsToLoadState(this.manifest))==null?void 0:d.to)!=null?p:u}))-u}this.liveLoadBufferLength$.getValue()!==a&&this.liveLoadBufferLength$.next(a)})),this.representationSubscription.add((0,Y.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:t.currentLiveSegmentServerLatency$}).pipe((0,Y.filter)(({isLive:r})=>r),(0,Y.filterChanged)((r,a)=>a.bufferLength<r.bufferLength),(0,Y.map)(({rtt:r,bufferLength:a,segmentServerLatency:n})=>{let o=pi(this.manifestUrlString,2);return(r/2+a+n+o)/1e3})).subscribe(this.liveLatency$))}initLiveMaintainSubscription(t){let i=0;this.representationSubscription.add((0,Y.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,Y.throttle)(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:r,bufferLength:a})=>{(0,Y.assertNonNullable)(this.element);let n=this.element.playbackRate,o=pi(this.manifestUrlString,2),u=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,c=Math.min(u,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*n),l=this.tuning.dashCmafLive.normalizedActualBufferOffset*n,d=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*n,p=isFinite(r)?r:a,h=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),m=u<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(m);let b="none";if(h?b="active_low_latency":this.isLowLatency$.getValue()&&m?(t.forEach(S=>S.proceedLowLatencyLive()),b="active_low_latency"):o!==0&&p<c?b="live_forward_buffering":p<c+d&&(b="live_with_target_offset"),isFinite(r)&&(i=r>i?r:i),b==="live_forward_buffering"||b==="live_with_target_offset"){let S=i-(c+l),v=this.normalizeLiveOffset(Math.trunc(o+S/n)),y=Math.abs(v-o),x=0;!r||y<=this.tuning.dashCmafLive.offsetCalculationError?x=o:v>0&&y>this.tuning.dashCmafLive.offsetCalculationError&&(x=v),this.manifestUrlString=Ae(this.manifestUrlString,x,2)}(b==="live_with_target_offset"||b==="live_forward_buffering")&&(i=0,this.manifest=await this.updateManifest())},r=>{this.error$.next({id:"updateLive",category:Y.ErrorCategory.VIDEO_PIPELINE,thrown:r,message:"Failed to update live with subscription"})}))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let t=1-this.element.playbackRate;return Number(t.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normalizeLiveOffset(t){return Math.trunc(t/1e3)*1e3}};var Yr=class extends Zi{constructor(e){super(e),this.textTracksManager.destroy()}getPlayer(){return new Do({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec})}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);let o=new be.ValueSubject(1);n(r.playbackRateState$,o),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe((0,be.filterChanged)()).subscribe(u=>{let c=i.position$.getValue(),l=i.volume$.getValue(),d=!l.volume||l.muted;!u&&!c&&d?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((0,be.map)(u=>u.to)).subscribe(this.player.isLowLatency$)).add((0,be.combine)({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,be.map)(({liveBufferTime:u,liveAvailabilityStartTime:c})=>u&&c?u+c:void 0)).subscribe(i.liveTime$)).add((0,be.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,be.merge)(r.playbackRateState$,new be.ValueSubject(1))}).pipe((0,be.filter)(({liveStreamStatus:u,liveDuration:c})=>u==="active"&&!!c)).subscribe(({liveDuration:u,playbackRate:c})=>{let l=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;d||c<1-p||this.video.paused||(0,be.isNullable)(l)||(t=u-l)})).add((0,be.combine)({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,be.merge)(r.playbackRateState$,new be.ValueSubject(1))}).pipe((0,be.filterChanged)((u,c)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===c.liveDuration:u.time===c.time)).subscribe(({time:u,liveDuration:c,playbackRate:l})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&l>=1-p||(0,be.isNullable)(u)||(0,be.isNullable)(c))return;let h=-1*(c-u-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let c=Rv(u);this.params.output.availableTextTracks$.next([c])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe((0,be.filter)(u=>(0,be.isNonNullable)(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.seek(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var W=require("@vkontakte/videoplayer-shared/es2018");var qy=G(Xe(),1),Nl=G(Wa(),1);var Ri=(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};var T=require("@vkontakte/videoplayer-shared/es2018");var Bo=G(Xe(),1),or=G(bt(),1),Vo=G(Wa(),1);var Uy=G(Wc(),1);var Mi=require("@vkontakte/videoplayer-shared/es2018");var X$=18,Ny=!1;try{Ny=H.browser.isSafari&&!!H.browser.safariVersion&&H.browser.safariVersion<=X$}catch(s){console.error(s)}var _l=class{constructor(e,t=!1){this.bufferFull$=new Mi.Subject;this.error$=new Mi.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Mi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};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)};Ny&&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(){var r;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((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Mi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:(0,Mi.assertNever)(t)}}},Fy=_l;var Ol=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};var P=require("@vkontakte/videoplayer-shared/es2018");var As=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:c}){this.currentLiveSegmentServerLatency$=new P.ValueSubject(0);this.currentLowLatencySegmentLength$=new P.ValueSubject(0);this.currentSegmentLength$=new P.ValueSubject(0);this.onLastSegment$=new P.ValueSubject(!1);this.fullyBuffered$=new P.ValueSubject(!1);this.playingRepresentation$=new P.ValueSubject(void 0);this.playingRepresentationInit$=new P.ValueSubject(void 0);this.error$=new P.Subject;this.gaps=[];this.subscription=new P.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ye;this.switchAbortController=new ye;this.destroyAbortController=new ye;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=(0,P.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,P.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Fy(this.sourceBuffer,this.tuning.dash.useAbortMSEFix),this.subscription.add((0,P.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add((0,P.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:P.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!Se(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Ol(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let c=this.getForwardBufferDuration(o),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,c<l).catch(d=>{this.handleAsyncError(d,"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);(0,P.assertNonNullable)(i,"No init buffer for starting representation"),(0,P.assertNonNullable)(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=(0,P.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!Se(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,P.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,P.isNullable)(a)||(0,P.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,P.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!Se(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();(0,P.isNonNullable)(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=(0,P.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!Se(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,P.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,P.isNullable)(a)||(0,P.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,P.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!Se(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();(0,P.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=(0,P.abortable)(this.destroyAbortController.signal,async function*(e){var u;let t=(0,Vo.default)(e,c=>c.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let c of this.representations.keys()){let l=t.find(h=>h.id===c);l&&this.representations.set(c,l);let d=this.representations.get(c);if(!d||!dt(d.segmentReference)){this.isSeekingLive=!1;return}let p=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,p)}let i=(u=this.switchingToRepresentationId)!=null?u:this.downloadingRepresentationId,r=this.representations.get(i);(0,P.assertNonNullable)(r,`Representation not found by id ${i}`);let a=this.segments.get(i);(0,P.assertNonNullable)(a,"No segments for starting representation");let n=this.initData.get(i);if((0,P.assertNonNullable)(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));var l;this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(c!=null&&c.live),this.baseUrls=(l=c==null?void 0:c.baseUrls)!=null?l:[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!Se(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ye,(0,P.abortable)(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);(0,P.assertNonNullable)(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if((0,P.isNullable)(o)||(0,P.isNullable)(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),(0,P.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!Se(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();(0,P.isNonNullable)(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!(0,P.isNullable)(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 ye,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var p;if((0,P.isNullable)(e)||(0,P.isNullable)(this.downloadingRepresentationId)||(0,P.isNullable)(this.playingRepresentationId)||(0,P.isNullable)(this.sourceBuffer)||!Se(this.mediaSource,this.sourceBuffer)||(0,P.isNonNullable)(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((0,P.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),(0,P.assertNonNullable)(i,`No such representation ${this.playingRepresentationId}`),(0,P.isNullable)(r)||(0,P.isNullable)(a))return;let n=r.find(h=>e>=h.time.from&&e<h.time.to);(0,P.isNonNullable)(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next((n==null?void 0:n.time.to)-n.time.from);let o=e,u=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let h=this.getForwardBufferDuration(e),m=xi(i),b=xi(t),S=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&(0,P.isNonNullable)(m)&&(0,P.isNonNullable)(b)&&(0,P.isHigher)(m.quality,b.quality),v=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(S||v?o+=Math.min(h,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=n.time.to-e+u&&(o=n?n.time.to+u:-1/0),this.tuning.dash.useNewRepresentationSwitch){let x=(p=[...this.segments.entries()].map(([w,M])=>{let _=M.find(q=>e>=q.time.from&&e<q.time.to);return{representationId:w,status:_==null?void 0:_.status}}).find(w=>w.status==="fed"))==null?void 0:p.representationId;x&&(this.playingRepresentationId=x,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&Ol(this.sourceBuffer.buffered)>=this.bufferLimit){let h=this.getForwardBufferDuration(e),m=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,h<m).catch(b=>{this.handleAsyncError(b,"pruneBuffer")});return}let l=[];if(!this.activeSegments.size&&(l=this.selectForwardBufferSegments(r,t.segmentReference.type,o),l.length)){let h="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,Bo.default)(l,n))h="high";else{let m=(0,or.default)(l,0);m&&m.time.from-n.time.to>=this.forwardBufferTarget/2&&(h="low")}this.loadSegments(l,t,h).catch(m=>{this.handleAsyncError(m,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!l.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let d=(0,or.default)(r,-1);!this.isLive&&d&&(this.fullyBuffered$.next(d.time.to-e-this.getForwardBufferDuration(e)<u),this.onLastSegment$.next(e-d.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;(0,P.isNonNullable)(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==null?void 0:e.streams[this.kind];if(!t)return;let i=(0,Vo.default)(t,a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var i,r,a;if(!e||[...this.segments.values()].every(n=>!n.length))return;let t=(0,Vo.default)(e.streams[this.kind],n=>n.representations);for(let n of t){if(!n||!dt(n.segmentReference))return;let o=n.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),u=100,c=(i=this.segments.get(n.id))!=null?i:[],l=(a=(r=(0,or.default)(c,-1))==null?void 0:r.time.to)!=null?a:0,d=o==null?void 0:o.findIndex(p=>l>=p.time.from+u&&l<=p.time.to+u);if(d===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(n.segmentReference);this.segments.set(n.id,p)}else{let p=o.slice(d+1);this.segments.set(n.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,P.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){var t;if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(t=(0,or.default)(e,-1))==null?void 0:t.time.to:0)||0}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let a=r.segmentReference;if(!dt(a))return;let n=(i=this.segments.get(r.id))!=null?i:[],o=n.find(c=>Math.floor(c.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(c=>Math.floor(c.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let c=Math.round(e.time.to*a.timescale/1e3).toString(10),l=At(a.segmentTemplateUrl,{segmentTime:c});n.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&rr&&rr(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&rr&&rr(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}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:p,time:{from:h,to:m}},b)=>{let S=h<=i&&m>=i,v=h>i||S||b===0&&i===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),x=this.preloadOnly&&h<=i+y||r<y&&m-h>=y||m<=i+y;return(p==="none"||p==="partially_ejected"&&v&&x&&this.sourceBuffer&&Se(this.mediaSource,this.sourceBuffer)&&!(Ri(this.sourceBuffer.buffered,h)&&Ri(this.sourceBuffer.buffered,m)))&&v&&x});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,c=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let p=a;p<n.length&&(o<=l||u<=d);p++){let h=n[p];if(o+=h.byte.to+1-h.byte.from,u+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")c.push(h);else break}return c}async loadSegments(e,t,i="auto"){dt(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:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await(0,P.abortable)(o,async function*(){let l=(0,P.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,l))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let l=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=(0,P.now)(),!l)return;let d=new DataView(l),p=nr(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=p.getChunkEndTime(d,b)}u&&r.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=p.getServerLatencyTimestamps(d);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(l){this.abortActiveSegments([e]),(0,P.isAbortError)(l)||(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())dt(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(0,P.abortable)(n,async function*(){let u=(0,P.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,u),(0,P.fromEvent)(window,"online").pipe((0,P.once)()).subscribe(()=>{c(),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=(0,P.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),(0,P.isAbortError)(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(dt(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,or.default)(e,0).byte.from,to:(0,or.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=(0,P.now)(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!dt(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?(c,l)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=(0,P.now)();let d=this.onSomeTemplateDataLoaded({dataView:c,loaded:l,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Bo.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!Se(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 c=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),l=nr(n.mime).parseFeedableSegmentChunk(c,this.isLive);l!=null&&l.byteLength&&(u.status="partially_fed",o.feedingBytes+=l.byteLength,await this.sourceBufferTaskQueue.append(l),o.fedBytes+=l.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!Se(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:c}=u;if(u.representationId!==t)continue;if(a.aborted){await n();continue}let l=c.byte.from-i,d=c.byte.to-i,p=d-l+1,h=l<r,m=d<=r;if(!h)continue;let b=nr(o.mime);if(c.status==="downloading"&&m){c.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+l,p);await this.sourceBufferTaskQueue.append(S,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(u.loadedBytes=Math.min(p,r-l),u.loadedBytes>u.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+l+u.feedingBytes,u.loadedBytes-u.feedingBytes),v=u.loadedBytes===p?S:b.parseFeedableSegmentChunk(S);v!=null&&v.byteLength&&(c.status="partially_fed",u.feedingBytes+=v.byteLength,await this.sourceBufferTaskQueue.append(v,a)&&!a.aborted?(u.fedBytes+=v.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var i;if(!((0,P.isNullable)(this.sourceBuffer)||!Se(this.mediaSource,this.sourceBuffer))){!this.isLive&&H.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ri(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ri(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:P.ErrorCategory.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",Cl(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let a of(i=this.segments.get(r.id))!=null?i:[])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.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||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=ir(()=>(0,Uy.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?(0,P.abortable)(this.destroyAbortController.signal,async function*(){let u=(0,P.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,nr(e.mime),{priority:r,ignoreNetworkErrors:a})).then(async u=>{if(!u)return;let{init:c,dataView:l,segments:d}=u,p=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,p);let h=d;this.isLive&&dt(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),c&&this.parsedInitData.set(e.id,c)}).then(()=>this.failedDownloads=0,u=>{a||this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:P.ErrorCategory.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||!Se(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,P.isNullable)(e))return!1;let r=[],a=0,n=u=>{u.sort((l,d)=>l.from-d.from);let c=[u[0]];for(let l=1;l<u.length;l++){let{from:d,to:p}=u[l],h=c[c.length-1];h.to>=d?h.to=Math.max(h.to,p):c.push(u[l])}return c},o=u=>{var l;if(a>=t)return r;r.push({...u.time}),r=n(r);let c=Cl(u)?(l=u.size)!=null?l:0:u.byte.to-u.byte.from;a+=c};for(let u of this.segments.values())for(let c of u){let l=c.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=c.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||d)&&c.status==="fed"&&o(c)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let c=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)(0,Bo.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(l)&&d++;if(d===this.segments.size){let p={time:{from:c,to:l},url:"",status:"none"};o(p)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let l of c)l.time.from>=e+u&&l.status==="fed"&&o(l)}return r.length?(await Promise.all(r.map(c=>this.sourceBufferTaskQueue.remove(c.from,c.to)))).reduce((c,l)=>c||l,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!Se(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||!Se(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||!Se(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,P.isNullable)(e)?0:ki(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!Se(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||!Se(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=ir(()=>{try{this.detectGaps(e,t)}catch(a){this.error$.next({id:"GapDetection",category:P.ErrorCategory.WTF,message:"detectGaps threw",thrown:a})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if((0,P.isNullable)(this.sourceBuffer)||!Se(this.mediaSource,this.sourceBuffer)||(0,P.isNullable)(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(l=>l.from-t<=n&&l.to+t>=o),c=e.filter(l=>n>=l.from&&n<l.to-t||o>l.from+t&&o<=l.to);u||(c.length===1?r.status="partially_ejected":this.gaps.some(l=>l.from===r.time.from||l.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:P.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var F=require("@vkontakte/videoplayer-shared/es2018");var _o=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.manifestRequested$=new F.Subject;this.firstBytesManifest$=new F.Subject;this.firstBytesRequested$=new F.Subject;this.firstBytesReceived$=new F.Subject;this.lastConnectionType$=new F.ValueSubject(void 0);this.lastConnectionReused$=new F.ValueSubject(void 0);this.lastRequestFirstBytes$=new F.ValueSubject(void 0);this.lastConnectionMetrics$=new F.ValueSubject(void 0);this.lastDownloadMetrics$=new F.ValueSubject(void 0);this.recoverableError$=new F.Subject;this.error$=new F.Subject;this.abortAllController=new ye;this.subscription=new F.SubscriptionRemovable;this.performanceObserver=null;this.pendingConnectionMetrics=new Map;this.fetchManifest=(0,F.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Ii(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=mo(i)),this.trackRequestStart(i,performance.now());let r=(0,F.now)();this.manifestRequested$.next();let a=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(F.suppressAbort);if(a){let n=(0,F.now)();t.log("success",(0,F.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(a.headers),this.firstBytesManifest$.next();let o=a.headers.get("content-length"),u=0;o&&(u=parseInt(o,10));let c=await a.text();if((!o||isNaN(u)||u<=0)&&(u=new TextEncoder().encode(c).length),u>0){let l=n-r,p=u/(l/1e3)*8/1024,h={bytes:u,speed:p,url:e};this.lastDownloadMetrics$.next(h)}return c}else return t.error("error",(0,F.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null}.bind(this));this.fetch=(0,F.abortable)(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:c=!1,ignoreNetworkErrors:l=!1}={}){var le,oe,A;let d=e,p=new Headers,h=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{p.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let $=new URL(d,(0,F.getWindow)().location.href);$.searchParams.append("bytes",`${i.from}-${i.to}`),d=$.toString();break}default:(0,F.assertNever)(t)}this.requestQuic&&(d=Ii(d));let m=this.abortAllController.signal,b;if(n){let $=new ye;if(b=(0,F.merge)((0,F.fromEvent)(this.abortAllController.signal,"abort"),(0,F.fromEvent)(n,"abort")).subscribe(()=>{try{$.abort()}catch(k){(0,F.suppressAbort)(k)}}),this.subscription.add(b),this.abortAllController.signal.aborted||n.aborted)try{$.abort()}catch(k){(0,F.suppressAbort)(k)}m=$.signal}let S=0,v=(0,F.now)();h.log("startRequest",(0,F.flattenObject)({url:d,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:v})),this.trackRequestStart(d,performance.now()),this.firstBytesRequested$.next();let y=yield this.doFetch(d,{priority:a,headers:p,signal:m},{ignoreNetworkErrors:l}),x=(0,F.now)();if(!y)return h.error("error",{message:"No response in request"}),h.end(),this.unsubscribeAbortSubscription(b),null;if((le=this.throughputEstimator)==null||le.addRawRtt(x-v),!y.ok||!y.body){this.unsubscribeAbortSubscription(b);let $=`Fetch error ${y.status}: ${y.statusText}`;return h.error("error",{message:$}),h.end(),Promise.reject(new Error(`Fetch error ${y.status}: ${y.statusText}`))}if(this.onHeadersReceived(y.headers),!r&&!o){this.unsubscribeAbortSubscription(b);let $=(0,F.now)(),k={requestStartedAt:v,requestEndedAt:$,duration:$-v};return h.log("endRequest",(0,F.flattenObject)(k)),h.end(),y.arrayBuffer()}let w=y.body;if(o){let $;[w,$]=y.body.tee(),(oe=this.throughputEstimator)==null||oe.trackStream($,u)}let M=w.getReader(),_,q=parseInt((A=y.headers.get("content-length"))!=null?A:"",10);Number.isFinite(q)&&(_=q),!_&&i&&(_=i.to-i.from+1);let O=_?new Uint8Array(_):new Uint8Array(0),j=!1,V=$=>{this.unsubscribeAbortSubscription(b),j=!0,(0,F.suppressAbort)($)},Q=(0,F.abortable)(m,async function*({done:$,value:k}){if(S===0&&(this.lastRequestFirstBytes$.next((0,F.now)()-v),this.firstBytesReceived$.next()),m.aborted){this.unsubscribeAbortSubscription(b);return}if(!$&&k){if(c&&_)O.set(k,S),S+=k.byteLength;else{let R=new Uint8Array(O.length+k.length);R.set(O),R.set(k,O.length),O=R,S+=k.byteLength}r==null||r(new DataView(O.buffer),S),yield M==null?void 0:M.read().then(Q,V)}}.bind(this));yield M==null?void 0:M.read().then(Q,V),this.unsubscribeAbortSubscription(b);let U=(0,F.now)(),ie={failed:j,requestStartedAt:v,requestEndedAt:U,duration:U-v};if(j)return h.error("endRequest",(0,F.flattenObject)(ie)),h.end(),null;if(S>0){let $=U-v,R=S/($/1e3)*8/1024,Z={bytes:S,speed:R,url:e};this.lastDownloadMetrics$.next(Z)}return h.log("endRequest",(0,F.flattenObject)(ie)),h.end(),O.buffer}.bind(this));this.fetchByteRangeRepresentation=(0,F.abortable)(this.abortAllController.signal,async function*(e,t,i){var v;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,c,l;e.indexRange&&(c=e.indexRange.from,l=e.indexRange.to,u=a+1===c,u&&(n=Math.min(c,r),o=Math.max(l,a))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},measureThroughput:!1,...i});if(!d)return null;let p=new DataView(d,r-n,a-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=(v=e.indexRange)!=null?v:t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,m.from-n,m.to-m.from+1);else{let y=yield this.fetch(e.url,{range:m,measureThroughput:!1});if(!y)return null;b=new DataView(y)}let S=t.parseSegments(b,h,m);return{init:h,dataView:new DataView(d),segments:S}}.bind(this));this.fetchTemplateRepresentation=(0,F.abortable)(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,(0,F.getWindow)().PerformanceObserver&&this.setupPerformanceObserver()}onHeadersReceived(e){let{type:t,reused:i}=fo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}setupPerformanceObserver(){this.performanceObserver=new((0,F.getWindow)()).PerformanceObserver(e=>{e.getEntriesByType("resource").forEach(t=>{this.processPerformanceResourceTiming(t)})}),this.performanceObserver.observe({entryTypes:["resource"]})}processPerformanceResourceTiming(e){let t=this.findMatchingRequest(e);if(!t||!this.pendingConnectionMetrics.get(t))return;this.pendingConnectionMetrics.delete(t);let r=this.extractConnectionMetrics(e);r&&this.lastConnectionMetrics$.next(r)}estimateNetworkType(){if(!("connection"in(0,F.getWindow)().navigator))return"unknown";let e=(0,F.getWindow)().navigator.connection;return e.effectiveType?{"slow-2g":"2g","2g":"2g","3g":"3g","4g":"lte"}[e.effectiveType]||e.effectiveType:e.downlink?e.downlink<1?"2g":e.downlink<5?"3g":e.downlink<50?"lte":"wifi":e.rtt?e.rtt>500?"2g":e.rtt>250?"3g":e.rtt>50?"lte":"wifi":"unknown"}extractConnectionMetrics(e){let t=0,i=0,r=0,a=0;return e.domainLookupStart>0&&e.domainLookupEnd>0&&(t=e.domainLookupEnd-e.domainLookupStart),e.connectStart>0&&e.connectEnd>0&&(a=e.connectEnd-e.connectStart,e.secureConnectionStart>0?(r=e.connectEnd-e.secureConnectionStart,i=e.secureConnectionStart-e.connectStart):i=a),{dnsResolveTime:Math.max(0,t),tcpHandshakeTime:Math.max(0,i),tlsHandshakeTime:Math.max(0,r),totalConnectTime:Math.max(0,a),networkType:this.estimateNetworkType(),url:e.name}}findMatchingRequest(e){try{for(let[t,i]of this.pendingConnectionMetrics.entries()){let r=new URL(e.name),a=r.origin+r.pathname,n=new URL(i.url),o=n.origin+n.pathname;if(a===o&&e.startTime>=i.startTime-10&&e.startTime<=i.startTime+1e3)return t}}catch(t){this.recoverableError$.next({id:"VideoDataFetchError",message:"Video data fetch error with getting download metrics",category:F.ErrorCategory.WTF})}return null}trackRequestStart(e,t){let i=`${e}_${t}_${Math.random().toString(36).substr(2,9)}`;this.pendingConnectionMetrics.set(i,{url:e,startTime:t})}async fetchRepresentation(e,t,i){var a,n;let{type:r}=e;switch(r){case"byteRange":return(a=await this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:(0,F.assertNever)(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.performanceObserver&&(this.performanceObserver.disconnect(),this.performanceObserver=null),this.pendingConnectionMetrics.clear(),this.tracer.end()}async doFetch(e,t,i){let r=await vt(e,t);if(r.ok)return r;if(i!=null&&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:F.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:a});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:F.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:a});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:F.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:a});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:F.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:a});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${n})`,category:F.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:a})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}};var Oo=require("@vkontakte/videoplayer-shared/es2018");var Rs=class s{constructor(e,t){this.currentRepresentation$=new Oo.ValueSubject(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!(0,Oo.isNullable)(e))for(let i of this.representations)for(let r of i){let a=r.segmentReference,n=a.segments.length,o=a.segments[0].time.from,u=a.segments[n-1].time.to;if(e<o||e>u)continue;let c=a.segments.find(l=>l.time.from<=e&&l.time.to>=e);!c||((t=this.currentSegment)==null?void 0:t.time.from)===c.time.from&&this.currentSegment.time.to===c.time.to||(this.currentSegment=c,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(c.url,a.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?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!=null&&e.some(t=>s.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&dt(t.segmentReference))}};var Z$=["timeupdate","progress","play","seeked","stalled","waiting"],eL=["timeupdate","progress","loadeddata","playing","seeked"];var No=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new T.Subscription;this.subscriptionRemovable=new T.SubscriptionRemovable;this.representationSubscription=new T.Subscription;this.state$=new ae("none");this.currentVideoRepresentation$=new T.ValueSubject(void 0);this.currentVideoRepresentationInit$=new T.ValueSubject(void 0);this.currentAudioRepresentation$=new T.ValueSubject(void 0);this.currentVideoSegmentLength$=new T.ValueSubject(0);this.currentAudioSegmentLength$=new T.ValueSubject(0);this.error$=new T.Subject;this.manifestRequested$=new T.Subject;this.firstBytesManifest$=new T.Subject;this.manifestReceived$=new T.Subject;this.firstBytesRequested$=new T.Subject;this.firstBytesReceived$=new T.Subject;this.lastConnectionType$=new T.ValueSubject(void 0);this.lastConnectionReused$=new T.ValueSubject(void 0);this.lastRequestFirstBytes$=new T.ValueSubject(void 0);this.lastConnectionMetrics$=new T.ValueSubject(void 0);this.lastDownloadMetrics$=new T.ValueSubject(void 0);this.currentLiveTextRepresentation$=new T.ValueSubject(null);this.isLive$=new T.ValueSubject(!1);this.isActiveLive$=new T.ValueSubject(!1);this.isLowLatency$=new T.ValueSubject(!1);this.liveDuration$=new T.ValueSubject(0);this.liveSeekableDuration$=new T.ValueSubject(0);this.liveAvailabilityStartTime$=new T.ValueSubject(0);this.liveStreamStatus$=new T.ValueSubject(void 0);this.bufferLength$=new T.ValueSubject(0);this.liveLatency$=new T.ValueSubject(void 0);this.liveLoadBufferLength$=new T.ValueSubject(0);this.livePositionFromPlayer$=new T.ValueSubject(0);this.currentStallDuration$=new T.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new T.ValueSubject(0);this.fetcherRecoverableError$=new T.Subject;this.fetcherError$=new T.Subject;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new T.Subject;this.gapWatchdogActive=!1;this.liveWasInterrupted=!1;this.destroyController=new ye;this.initManifest=(0,T.abortable)(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Ae(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:T.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,T.abortable)(this.destroyController.signal,async function*(){var u,c;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(l=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:T.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:l})});if(!e)return null;let t=null;try{t=So(e!=null?e:"",this.manifestUrlString),this.manifestReceived$.next()}catch(l){let d=(u=ho(e))!=null?u:{id:"ManifestParsing",category:T.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:l};this.error$.next(d)}if(!t)return null;let i=(l,d,p)=>{var h,m,b,S;return!!((m=(h=this.element)==null?void 0:h.canPlayType)!=null&&m.call(h,d)&&((S=(b=ut())==null?void 0:b.isTypeSupported)!=null&&S.call(b,`${d}; codecs="${p}"`))||l==="text")};if(t.live){this.isLive$.next(!0);let{availabilityStartTime:l,latestSegmentPublishTime:d,streamIsUnpublished:p,streamIsAlive:h}=t.live,m=((c=t.duration)!=null?c:0)/1e3;this.liveSeekableDuration$.next(-1*m),this.liveDuration$.next((d-l)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let b="active";if(h||(b=p?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(b),h&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let S=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(S).catch(v=>{this.error$.next({id:"updateManifest",category:T.ErrorCategory.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:v})})}}let r={text:t.streams.text,video:[],audio:[]},a,n;for(let l of["video","audio"]){let p=t.streams[l].filter(({mime:m,codecs:b})=>i(l,m,b));r[l]=p;let h;if(this.tuning.dash.codecsPrioritizeEnabled){let m=p.map(({codecs:b})=>b);l==="audio"&&(n=wo(m),h=n[0]),l==="video"&&(a=Eo(m),this.forceVideoCodec&&(0,qy.default)(a,this.forceVideoCodec)?h=this.forceVideoCodec:h=a[0]),h&&(r[l]=p.filter(({codecs:b})=>Ei(b)===h))}else{let m=new Set(p.map(({codecs:b})=>b));h=Io(m),h&&(r[l]=p.filter(({codecs:b})=>b.startsWith(h)))}if(l==="video"){let m=this.tuning.preferHDR,b=r.video.some(y=>y.hdr),S=r.video.some(y=>!y.hdr);H.display.isHDR&&m&&b?r.video=r.video.filter(y=>y.hdr):S&&(r.video=r.video.filter(y=>!y.hdr));let{videoStreamRepresentaionsFilter:v}=this.tuning.dash;v.length&&Ao(r,v)}}let o={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:a,audio:n}),this.tracer.log("updateManifestEnd",(0,T.flattenObject)(o)),o}.bind(this));this.initRepresentations=(0,T.abortable)(this.destroyController.signal,async function*(e,t,i){var d;this.tracer.log("initRepresentationsStart",(0,T.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,T.assertNonNullable)(this.manifest),(0,T.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add((0,T.fromEvent)(p,"error").pipe((0,T.filter)(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=vn();let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),xr())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}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((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new As("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,T.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new As("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}if(Rs.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Rs(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,T.merge)(...eL.map(p=>(0,T.fromEvent)(this.element,p))).pipe((0,T.map)(p=>this.element?ki(this.element.buffered,this.element.currentTime*1e3):0),(0,T.filterChanged)(),(0,T.tap)(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&this.stopStallWatchdogSubscription()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,T.merge)((0,T.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{this.stopStallWatchdogSubscription()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,T.filterChanged)()).subscribe(h=>this.liveStreamEndTimestamp=(0,T.now)())),this.subscription.add((0,T.fromEvent)(this.element,"pause").subscribe(()=>{let{liveUpdateInterval:h}=this.tuning.dash;this.livePauseWatchdogSubscription=(0,T.interval)(h).subscribe(m=>{let b=pi(this.manifestUrlString,2);this.manifestUrlString=Ae(this.manifestUrlString,b+h,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add((0,T.fromEvent)(this.element,"play").subscribe(h=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add((0,T.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,T.map)(({isActiveLive:h,isLowLatency:m})=>h&&m),(0,T.filterChanged)()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Gr(this.element,1)})),this.representationSubscription.add((0,T.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,T.filter)(({bufferLength:h,isActiveLive:m,isLowLatency:b})=>m&&b&&!!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 m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add((0,T.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,T.filter)(({isLive:h})=>h),(0,T.filterChanged)((h,m)=>m.bufferLength<h.bufferLength),(0,T.map)(({rtt:h,bufferLength:m,segmentServerLatency:b})=>{let S=pi(this.manifestUrlString,2);return(h/2+m+b+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,T.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:b})=>{if(!b||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,x=h-S;if(this.isManualDecreasePlaybackInLive())return;let w=1;Math.abs(x)>v&&(w=1+Math.sign(x)*y),Gr(this.element,w)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,S;let m=0;if(h){let v=((S=(b=this.element)==null?void 0:b.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(x=>{var w,M;return(M=(w=x.getLiveSegmentsToLoadState(this.manifest))==null?void 0:w.to)!=null?M:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add((0,T.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,T.throttle)(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let b=this.element.playbackRate,S=pi(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),x=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,w=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,M=isFinite(h)?h:m,_=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),q=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(q);let O="none";if(_?O="active_low_latency":this.isLowLatency$.getValue()&&q?(this.bufferManagers.forEach(j=>j.proceedLowLatencyLive()),O="active_low_latency"):S!==0&&M<y?O="live_forward_buffering":M<y+w&&(O="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),O==="live_forward_buffering"||O==="live_with_target_offset"){let j=p-(y+x),V=this.normalizeLiveOffset(Math.trunc(S+j/b)),Q=Math.abs(V-S),U=0;!h||Q<=this.tuning.dashCmafLive.offsetCalculationError?U=S:V>0&&Q>this.tuning.dashCmafLive.offsetCalculationError&&(U=V),this.manifestUrlString=Ae(this.manifestUrlString,U,2)}(O==="live_with_target_offset"||O==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:T.ErrorCategory.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let u=(0,T.merge)(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe((0,T.map)(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=(0,T.merge)(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe((0,T.map)(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),l=(0,T.combine)({allBuffersFull:u,someBufferEnded:c}).pipe((0,T.filterChanged)(),(0,T.map)(({allBuffersFull:p,someBufferEnded:h})=>p&&h),(0,T.filter)(p=>p));if(this.representationSubscription.add((0,T.merge)(this.forceEnded$,l).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add((0,T.merge)(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var b;if(((b=this.source)==null?void 0:b.readyState)==="open"){h();return}this.error$.next({id:"OpenOfStream",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(m=this.source)==null||m.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(d=this.manifest.duration)!=null?d:0,...(0,Nl.default)((0,Nl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),dt(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&(0,T.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r,a;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(a=this.audioBufferManager)!=null&&a.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,T.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:T.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),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 _o({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.subscription.add(this.fetcher.lastConnectionMetrics$.subscribe(this.lastConnectionMetrics$)),this.subscription.add(this.fetcher.lastDownloadMetrics$.subscribe(this.lastDownloadMetrics$)),this.liveBuffer=ti.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){(0,T.assertNonNullable)(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"?(0,T.now)()-this.liveStreamEndTimestamp:0,i=this.normalizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Ae(this.manifestUrlString,i,2)}async updateLiveBuffersFromManifest(e){var t,i,r;await((t=this.videoBufferManager)==null?void 0:t.seekLive(e.streams.video)),await((i=this.audioBufferManager)==null?void 0:i.seekLive(e.streams.audio)),(r=this.liveTextManager)==null||r.seekLive(e.streams.text)}stopStallWatchdogSubscription(){var e;(e=this.stallWatchdogSubscription)==null||e.unsubscribe(),this.currentStallDuration$.next(0)}initBuffer(){(0,T.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,T.merge)(...Z$.map(e=>(0,T.fromEvent)(this.element,e)),(0,T.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:T.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,T.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,T.fromEvent)(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===2&&!this.element.seeking&&Ri(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var w,M,_,q,O,j,V,Q,U,ie,le;let{keepSilentStallWatchdogWhenNotActive:t}=this.tuning.dashCmafLive,{crashOnStallTimeout:i,crashOnStallTWithoutDataTimeout:r,liveStallReinitInterval:a,stallWatchdogInterval:n}=this.tuning.dash,o=this.isLive$.getValue(),c=this.liveStreamStatus$.getValue()==="active";if(!this.element||((w=this.source)==null?void 0:w.readyState)!=="open")return;let l=this.currentStallDuration$.getValue();l+=n,this.currentStallDuration$.next(l);let d={timeInWaiting:l},p=(0,T.now)(),h=100,m=(_=(M=this.videoBufferManager)==null?void 0:M.lastDataObtainedTimestamp)!=null?_:0;this.videoLastDataObtainedTimestamp$.next(m);let b=(O=(q=this.audioBufferManager)==null?void 0:q.lastDataObtainedTimestamp)!=null?O:0,S=(V=(j=this.videoBufferManager)==null?void 0:j.getForwardBufferDuration())!=null?V:0,v=(U=(Q=this.audioBufferManager)==null?void 0:Q.getForwardBufferDuration())!=null?U:0,y=S<h&&p-m>r,x=this.audioBufferManager&&v<h&&p-b>r;if((!t||c)&&((y||x)&&l>r||l>=i))throw new Error(`Stall timeout exceeded: ${l} ms`);if(o&&l%a===0){let oe=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);!c&&t?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(oe),this.updateManifest()):this.seekLive(oe).catch(A=>{this.error$.next({id:"stallIntervalCallback",category:T.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:A})}),d.liveLastOffset=oe}else{let oe=this.element.currentTime*1e3;(ie=this.videoBufferManager)==null||ie.maintain(oe),(le=this.audioBufferManager)==null||le.maintain(oe),d.position=oe}this.tracer.log("stallIntervalCallback",(0,T.flattenObject)(d))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=(0,T.interval)(this.tuning.dash.stallWatchdogInterval).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:T.ErrorCategory.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==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,a,n,o,u;(0,T.assertNonNullable)(this.element),(0,T.assertNonNullable)(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Ri(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!((0,T.isNullable)(this.element)||(0,T.isNullable)(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,T.flattenObject)({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;(0,T.isNonNullable)(this.element)&&(0,T.isNonNullable)(this.source)&&(0,T.isNonNullable)(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}getCodecs(){var e;return(e=this.manifest)==null?void 0:e.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,T.getTraceSubscriptionMethod)(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(){var e;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(t=>t.updateLive(this.manifest)),(e=this.liveTextManager)==null||e.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 c of u.gaps)(r&&c.persistent||u.playingRepresentation$.getValue()===c.representation)&&c.from-o<=a&&c.to+o>a&&(this.element.duration*1e3-c.to<this.tuning.endGapTolerance?n.push(1/0):n.push(c.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",(0,T.flattenObject)(i)))}}calculateDurationFromSegments(){var e,t;return Math.max(((e=this.videoBufferManager)==null?void 0:e.calculateDurationFromSegments())||0,((t=this.audioBufferManager)==null?void 0:t.calculateDurationFromSegments())||0)}};var at=require("@vkontakte/videoplayer-shared/es2018"),Fo=class{constructor(){this.subscription=new at.Subscription;this.pipSize$=new at.ValueSubject(void 0);this.videoSize$=new at.ValueSubject(void 0);this.elementSize$=new at.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=at.noop}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add((0,at.observeElementSize)(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((0,at.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,at.map)(({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 W.Subscription;this.videoState=new ae("stopped");this.observableVideo=null;this.droppedFramesManager=new Or;this.stallsManager=new uo;this.elementSizeManager=new Fo;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Si;this.audioTrackSwitchHistory=new Si;this.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==null?void 0: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"),B(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"),B(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&B(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==null?void 0:i.to)==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return(0,W.assertNever)(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new Nr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((a=e.projectionData)==null?void 0:a.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 mt(e.source.url),this.params=e,this.video=Je(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(We(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 No({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;(0,W.isNullable)(this.observableVideo)&&(this.observableVideo=tt(this.video),this.subscription.add(()=>{var n;return(n=this.observableVideo)==null?void 0:n.destroy()}));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:W.ErrorCategory.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((0,W.filter)(d=>!!d.length),(0,W.once)()).subscribe(d=>{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:d})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,W.map)(d=>d.to.state!=="none"),(0,W.filterChanged)());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.lastConnectionMetrics$,e.httpConnectionMetrics$),a(this.player.lastDownloadMetrics$,e.httpDownloadMetrics$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe((0,W.filter)(W.isNonNullable),(0,W.once)()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe((0,W.map)(d=>d.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(Ft(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),Ti({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(et(this.video,t.volume,i.volumeState$,r)),this.subscription.add(ft(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(gt(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&!this.video.ended&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")})),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let p=this.player.getStreams(),h=this.player.getCodecs();if((0,W.assertNonNullable)(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let b=[];for(let S of p.audio){b.push($l(S));let v=[];for(let y of S.representations){let x=Is(y);v.push(x),this.audioTracksMap.set(x,{stream:S,representation:y})}this.audioStreamsMap.set(S,v)}this.params.output.availableAudioStreams$.next(b)}let m=[];for(let b of p.video){m.push(Ll(b));let S=[];for(let v of b.representations){let y=xi({...v,streamId:b.id});y&&(S.push(y),this.videoTracksMap.set(y,{stream:b,representation:v}))}this.videoStreamsMap.set(b,S)}this.params.output.availableVideoStreams$.next(m);for(let b of p.text)for(let S of b.representations){let v=Ry(b,S);this.textTracksMap.set(v,{stream:b,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!=null&&h.video&&this.params.output.availableVideoCodecs$.next(h.video),h!=null&&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 d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let o=(0,W.merge)(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$,(0,W.fromEvent)(this.video,"progress")).pipe((0,W.filter)(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe((0,W.throttle)(u))),this.subscription.add(o.subscribe(async()=>{let d=this.player.state$.getState(),p=this.player.state$.getTransition();if(d!=="manifest_ready"&&d!=="running"||p)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[m,b]=h,S=[...this.videoTracksMap.keys()].find(y=>{var x;return((x=this.videoTracksMap.get(y))==null?void 0:x.representation.id)===m.id});(0,W.isNonNullable)(S)&&(this.stallsManager.lastVideoTrackSelected=S);let v=this.params.desiredState.autoVideoTrackLimits.getTransition();if(v&&this.params.output.autoVideoTrackLimits$.next(v.to),d==="manifest_ready")await this.player.initRepresentations(m.id,b==null?void 0:b.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",m.id),b){let y=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",b.id,y)}},r)),this.subscription.add((0,W.combine)({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:(0,W.merge)((0,W.observableFrom)([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,W.map)(d=>d.to)))}).pipe((0,W.map)(({videoState:d,autoVideoTrackState:p})=>d.to!=="stopped"&&p),(0,W.filterChanged)()).subscribe(d=>this.player.setSmartRepresentationSwitch(d))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSizeManager.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,W.filterChanged)()).subscribe(d=>{let p=[...this.videoTracksMap.entries()].find(([,{representation:v}])=>v.id===d);if(!p){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:m}]=p,b=this.params.desiredState.videoStream.getTransition();b&&b.to&&b.to.id===m.id&&this.params.desiredState.videoStream.setState(b.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Ll(m));let S=this.player.calculateDurationFromSegments();S&&this.params.output.duration$.next(S/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,W.filterChanged)()).subscribe(d=>{let p=[...this.audioTracksMap.entries()].find(([,{representation:S}])=>S.id===d);if(!p){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=p,b=this.params.desiredState.audioStream.getTransition();b&&b.to&&b.to.id===m.id&&this.params.desiredState.audioStream.setState(b.to),e.currentAudioStream$.next($l(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var p,h;if(d!=null&&d.is3dVideo&&((p=this.params.tuning.spherical)!=null&&p.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(m){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${m}`})}else this.destroy3DScene(),(h=this.params.tuning.spherical)!=null&&h.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 c=t.playbackState.stateChangeStarted$.pipe((0,W.map)(({to:d})=>d==="ready"),(0,W.filterChanged)());this.subscription.add((0,W.merge)(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,W.observableFrom)(["init"])).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add((0,W.merge)(c,this.player.state$.stateChangeEnded$,(0,W.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=(0,W.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,W.observableFrom)(["init"])).pipe((0,W.debounce)(0));this.subscription.add(l.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var O,j,V,Q,U,ie,le,oe,A,$,k,R,Z;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Oa:_a,t=this.params.tuning.useNewAutoSelectVideoTrack?io:to,i=this.params.tuning.useNewAutoSelectVideoTrack?Ut:eo,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(O=r.videoTrack.getState())==null?void 0:O.id,u=[...this.videoTracksMap.keys()].find(({id:K})=>K===o),c=a.currentVideoTrack$.getValue(),l=((Q=(V=r.videoStream.getState())!=null?V:u&&((j=this.videoTracksMap.get(u))==null?void 0:j.stream))!=null?Q:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!l)return;let d=[...this.videoStreamsMap.keys()].find(({id:K})=>K===l.id),p=d&&this.videoStreamsMap.get(d);if(!p)return;let h=ki(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let b=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(m,b||1/0),1),v=(U=r.audioStream.getState())!=null?U:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,y=(ie=[...this.audioStreamsMap.keys()].find(({id:K})=>K===(v==null?void 0:v.id)))!=null?ie:this.audioStreamsMap.keys().next().value,x=0;if(y){if(u&&!n){let K=e(u,p,(le=this.audioStreamsMap.get(y))!=null?le:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,(oe=K==null?void 0:K.bitrate)!=null?oe:-1/0)}if(c){let K=e(c,p,(A=this.audioStreamsMap.get(y))!=null?A:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,($=K==null?void 0:K.bitrate)!=null?$:-1/0)}}let w=u;(n||!w)&&(w=i(p,{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:x,forwardBufferHealth:S,current:c,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 M=y&&t(w,p,(k=this.audioStreamsMap.get(y))!=null?k:[],{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}),_=(R=this.videoTracksMap.get(w))==null?void 0:R.representation,q=M&&((Z=this.audioTracksMap.get(M))==null?void 0:Z.representation);if(_&&q)return[_,q];if(_&&!q&&this.audioTracksMap.size===0)return[_,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){it(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:W.ErrorCategory.DOM,thrown:e}))}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),Ze(this.video,this.params.tuning.keepVideoElement,this.params.tuning.clearVideoElementInnerHTML),this.tracer.end()}};var Ms=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)}};var ge=require("@vkontakte/videoplayer-shared/es2018");var $s=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 ge.ValueSubject(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe((0,ge.filterChanged)()).subscribe(u=>{let c=i.position$.getValue(),l=i.volume$.getValue(),d=!l.volume||l.muted;!u&&!c&&d?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((0,ge.map)(u=>u.to)).subscribe(this.player.isLowLatency$)).add((0,ge.combine)({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,ge.map)(({liveBufferTime:u,liveAvailabilityStartTime:c})=>u&&c?u*1e3+c+t:void 0)).subscribe(i.liveTime$)).add((0,ge.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,ge.merge)(r.playbackRateState$,new ge.ValueSubject(1))}).pipe((0,ge.filter)(({liveStreamStatus:u,liveDuration:c})=>u==="active"&&!!c)).subscribe(({liveDuration:u,playbackRate:c})=>{let l=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;d||c<1-p||this.video.paused||(0,ge.isNullable)(l)||(t=u-l)})).add((0,ge.combine)({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,ge.merge)(r.playbackRateState$,new ge.ValueSubject(1))}).pipe((0,ge.filterChanged)((u,c)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===c.liveDuration:u.time===c.time)).subscribe(({time:u,liveDuration:c,playbackRate:l})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&l>=1-p||(0,ge.isNullable)(u)||(0,ge.isNullable)(c))return;let h=-1*(c-u-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let c=My(u);this.params.output.availableTextTracks$.next([c])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe((0,ge.filter)(u=>(0,ge.isNonNullable)(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)})}};var Hy="X-Playback-Duration",Fl=async s=>{var r;let e=await vt(s),t=await e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(Hy)?parseInt(e.headers.get(Hy),10):void 0};var ne=require("@vkontakte/videoplayer-shared/es2018");var ql=G(sc(),1);var Uo=require("@vkontakte/videoplayer-shared/es2018");var iL=s=>{let e=null;if(s.QUALITY&&(e=vi(s.QUALITY)),!e&&s.RESOLUTION){let[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=(0,Uo.videoSizeToQuality)({width:t,height:i})}return e!=null?e:null},rL=(s,e)=>{var a,n;let t=s.split(`
178
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(l,"i")}var dy=s=>{if(!(s!=null&&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==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},At=(s,e)=>{let t=s;t=(0,Pl.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,py.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Pl.default)(t,n,(o,u)=>(0,Ga.isNullable)(a)?o:(0,Ga.isNullable)(u)?a:(0,hy.default)(a,parseInt(u,10),"0"))}return t},So=(s,e)=>{var j,V,Q,U,ie,le,oe,A,$,k,R,Z,K,$t,Lt,pe,Ne,Fe,Ue,st,jt,Wt,$i,lr,Li,Xl,Jl,Zl,ed,td,id,rd,ad,sd,nd,od,ud,cd,ld,dd,pd,hd,fd,md,bd,gd,vd,Sd,yd,Td,Id,Ed,wd,xd,Pd,kd,Ad,Rd,Md,$d,Ld;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(Tt=>{var ve,Ci;return(Ci=(ve=Tt.textContent)==null?void 0:ve.trim())!=null?Ci:""}),o=(j=(0,fy.default)(n,0))!=null?j:"",u=a.getAttribute("type")==="dynamic",c=a.getAttribute("availabilityStartTime"),l=a.getAttribute("publishTime"),d=a.getElementsByTagName("vk:Attrs")[0],p=d==null?void 0:d.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=d==null?void 0:d.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=d==null?void 0:d.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=d==null?void 0:d.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,S;u&&(S={availabilityStartTime:c?new Date(c).getTime():0,publishTime:l?new Date(l).getTime():0,latestSegmentPublishTime:p?new Date(p).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:m==="yes"});let v,y=a.getAttribute("mediaPresentationDuration"),x=[...a.getElementsByTagName("Period")],w=x.reduce((Tt,ve)=>({...Tt,[ve.id]:ve.children}),{}),M=x.reduce((Tt,ve)=>({...Tt,[ve.id]:ve.getAttribute("duration")}),{});y?v=dy(y):(0,kl.default)(M).filter(Tt=>Tt).length&&!u?v=(0,kl.default)(M).reduce((Tt,ve)=>{var Ci;return Tt+((Ci=dy(ve))!=null?Ci:0)},0):b&&(v=parseInt(b,10));let _=0,q=(Q=(V=a.getAttribute("profiles"))==null?void 0:V.split(","))!=null?Q:[];for(let Tt of x.map(ve=>ve.id))for(let ve of w[Tt]){let Ci=(U=ve.getAttribute("id"))!=null?U:"id"+(_++).toString(10),Zr=(ie=ve.getAttribute("mimeType"))!=null?ie:"",Qo=(le=ve.getAttribute("codecs"))!=null?le:"",zo=(oe=ve.getAttribute("contentType"))!=null?oe:Zr==null?void 0:Zr.split("/")[0],dT=($=(A=ve.getAttribute("profiles"))==null?void 0:A.split(","))!=null?$:[],Cd=(R=ly((k=ve.getAttribute("lang"))!=null?k:""))!=null?R:{},Ns=($t=(K=(Z=ve.querySelector("Label"))==null?void 0:Z.textContent)==null?void 0:K.trim())!=null?$t:void 0,pT=ve.querySelectorAll("Representation"),hT=ve.querySelector("SegmentTemplate"),fT=(pe=(Lt=ve.querySelector("Role"))==null?void 0:Lt.getAttribute("value"))!=null?pe:void 0,dr=zo,Re={id:Ci,language:Cd.language,isDefault:fT==="main",label:Ns,codecs:Qo,hdr:dr==="video"&&xl(Qo),mime:Zr,representations:[]};for(let me of pT){let ai=(Ne=me.getAttribute("lang"))!=null?Ne:void 0,Fs=(Ue=(Fe=Ns!=null?Ns:ve.getAttribute("label"))!=null?Fe:me.getAttribute("label"))!=null?Ue:void 0,Us=(Wt=(jt=(st=me.querySelector("BaseURL"))==null?void 0:st.textContent)==null?void 0:jt.trim())!=null?Wt:"",Di=new URL(Us||o,e).toString(),si=($i=me.getAttribute("mimeType"))!=null?$i:Zr,qs=(Li=(lr=me.getAttribute("codecs"))!=null?lr:Qo)!=null?Li:"",Hs;if(zo==="text"){let ni=me.getAttribute("id")||"",js=((Xl=Cd.privateuse)==null?void 0:Xl.includes("x-auto"))||ni.includes("_auto"),Bi=me.querySelector("SegmentTemplate");if(Bi){let ea={representationId:(Jl=me.getAttribute("id"))!=null?Jl:void 0,bandwidth:(Zl=me.getAttribute("bandwidth"))!=null?Zl:void 0},Ws=parseInt((ed=me.getAttribute("bandwidth"))!=null?ed:"",10)/1e3,Qs=(id=parseInt((td=Bi.getAttribute("startNumber"))!=null?td:"",10))!=null?id:1,pr=parseInt((rd=Bi.getAttribute("timescale"))!=null?rd:"",10),Go=(ad=Bi.querySelectorAll("SegmentTimeline S"))!=null?ad:[],hr=Bi.getAttribute("media");if(!hr)continue;let zs=[],Gs=0,Ys="",fr=0,ta=Qs,Qe=0;for(let It of Go){let Vi=parseInt((sd=It.getAttribute("d"))!=null?sd:"",10),ht=parseInt((nd=It.getAttribute("r"))!=null?nd:"",10)||0,oi=parseInt((od=It.getAttribute("t"))!=null?od:"",10);Qe=Number.isFinite(oi)?oi:Qe;let _i=Vi/pr*1e3,ui=Qe/pr*1e3;for(let Ct=0;Ct<ht+1;Ct++){let ci=At(hr,{...ea,segmentNumber:ta.toString(10),segmentTime:(Qe+Ct*Vi).toString(10)}),mr=(ui!=null?ui:0)+Ct*_i,ra=mr+_i;ta++,zs.push({time:{from:mr,to:ra},url:ci})}Qe+=(ht+1)*Vi,Gs+=(ht+1)*_i}fr=Qe/pr*1e3,Ys=At(hr,{...ea,segmentNumber:ta.toString(10),segmentTime:Qe.toString(10)});let ia={time:{from:fr,to:1/0},url:Ys},Qt={type:"template",baseUrl:Di,segmentTemplateUrl:hr,initUrl:"",totalSegmentsDurationMs:Gs,segments:zs,nextSegmentBeyondManifest:ia,timescale:pr};Hs={id:ni,kind:"text",segmentReference:Qt,profiles:[],duration:v,bitrate:Ws,mime:"",codecs:"",width:0,height:0,isAuto:js}}else Hs={id:ni,isAuto:js,kind:"text",url:Di}}else{let ni=(cd=(ud=me.getAttribute("contentType"))!=null?ud:si==null?void 0:si.split("/")[0])!=null?cd:zo,js=(dd=(ld=ve.getAttribute("profiles"))==null?void 0:ld.split(","))!=null?dd:[],Bi=parseInt((pd=me.getAttribute("width"))!=null?pd:"",10),ea=parseInt((hd=me.getAttribute("height"))!=null?hd:"",10),Ws=parseInt((fd=me.getAttribute("bandwidth"))!=null?fd:"",10)/1e3,Qs=(md=me.getAttribute("frameRate"))!=null?md:"",pr=(bd=me.getAttribute("quality"))!=null?bd:void 0,Go=Qs?cy(Qs):void 0,hr=(gd=me.getAttribute("id"))!=null?gd:"id"+(_++).toString(10),zs=ni==="video"?`${ea}p`:ni==="audio"?`${Ws}Kbps`:qs,Gs=`${hr}@${zs}`,Ys=[...q,...dT,...js],fr,ta=me.querySelector("SegmentBase"),Qe=(vd=me.querySelector("SegmentTemplate"))!=null?vd:hT;if(ta){let Qt=(yd=(Sd=me.querySelector("SegmentBase Initialization"))==null?void 0:Sd.getAttribute("range"))!=null?yd:"",[It,Vi]=Qt.split("-").map(ci=>parseInt(ci,10)),ht={from:It,to:Vi},oi=(Td=me.querySelector("SegmentBase"))==null?void 0:Td.getAttribute("indexRange"),[_i,ui]=oi?oi.split("-").map(ci=>parseInt(ci,10)):[],Ct=oi?{from:_i,to:ui}:void 0;fr={type:"byteRange",url:Di,initRange:ht,indexRange:Ct}}else if(Qe){let Qt={representationId:(Id=me.getAttribute("id"))!=null?Id:void 0,bandwidth:(Ed=me.getAttribute("bandwidth"))!=null?Ed:void 0},It=parseInt((wd=Qe.getAttribute("timescale"))!=null?wd:"",10),Vi=(xd=Qe.getAttribute("initialization"))!=null?xd:"",ht=Qe.getAttribute("media"),oi=(kd=parseInt((Pd=Qe.getAttribute("startNumber"))!=null?Pd:"",10))!=null?kd:1,_i=At(Vi,Qt);if(!ht)throw new ReferenceError("No media attribute in SegmentTemplate");let ui=(Ad=Qe.querySelectorAll("SegmentTimeline S"))!=null?Ad:[],Ct=[],ci=0,mr="",ra=0;if(ui.length){let Ks=oi,Et=0;for(let br of ui){let Dt=parseInt((Rd=br.getAttribute("d"))!=null?Rd:"",10),Oi=parseInt((Md=br.getAttribute("r"))!=null?Md:"",10)||0,Xs=parseInt(($d=br.getAttribute("t"))!=null?$d:"",10);Et=Number.isFinite(Xs)?Xs:Et;let Yo=Dt/It*1e3,Ko=Et/It*1e3;for(let Js=0;Js<Oi+1;Js++){let bT=At(ht,{...Qt,segmentNumber:Ks.toString(10),segmentTime:(Et+Js*Dt).toString(10)}),Dd=(Ko!=null?Ko:0)+Js*Yo,gT=Dd+Yo;Ks++,Ct.push({time:{from:Dd,to:gT},url:bT})}Et+=(Oi+1)*Dt,ci+=(Oi+1)*Yo}ra=Et/It*1e3,mr=At(ht,{...Qt,segmentNumber:Ks.toString(10),segmentTime:Et.toString(10)})}else if((0,Ga.isNonNullable)(v)){let Et=parseInt((Ld=Qe.getAttribute("duration"))!=null?Ld:"",10)/It*1e3,br=Math.ceil(v/Et),Dt=0;for(let Oi=1;Oi<br;Oi++){let Xs=At(ht,{...Qt,segmentNumber:Oi.toString(10),segmentTime:Dt.toString(10)});Ct.push({time:{from:Dt,to:Dt+Et},url:Xs}),Dt+=Et}ra=Dt,mr=At(ht,{...Qt,segmentNumber:br.toString(10),segmentTime:Dt.toString(10)})}let mT={time:{from:ra,to:1/0},url:mr};fr={type:"template",baseUrl:Di,segmentTemplateUrl:ht,initUrl:_i,totalSegmentsDurationMs:ci,segments:Ct,nextSegmentBeyondManifest:mT,timescale:It}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ni||!si)continue;let ia={video:"video",audio:"audio",text:"text"}[ni];if(!ia)continue;dr||(dr=ia),Hs={id:Gs,kind:ia,segmentReference:fr,profiles:Ys,duration:v,bitrate:Ws,mime:si,codecs:qs,width:Bi,height:ea,fps:Go,quality:pr}}Re.language||(Re.language=ai),Re.label||(Re.label=Fs),Re.mime||(Re.mime=si),Re.codecs||(Re.codecs=qs),Re.hdr||(Re.hdr=dr==="video"&&xl(qs)),Re.representations.push(Hs)}if(dr){let me=r[dr].find(ai=>ai.id===Re.id);if(me&&Re.representations.every(ai=>ai.segmentReference.type==="template"))for(let ai of me.representations){let Fs=Re.representations.find(si=>si.id===ai.id);if(!Fs)continue;let Us=Fs.segmentReference,Di=ai.segmentReference;Di.segments.push(...Us.segments),Di.nextSegmentBeyondManifest=Us.nextSegmentBeyondManifest}else r[dr].push(Re)}}return{duration:v,streams:r,baseUrls:n,live:S}};var To=G(bt(),1),Al=G(Xe(),1),Ka=require("@vkontakte/videoplayer-shared/es2018");var Ya=(a=>(a.VP9="vp9",a.AV1="av1",a.NONE="none",a.SMOOTH="smooth",a.POWER_EFFICIENT="power_efficient",a))(Ya||{});var yo=s=>{let{webmDecodingInfo:e}=H.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:(0,Ka.assertNever)(s)}},my=({webmCodec:s,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...yo(s),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],a=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(H.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",...yo(s),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...yo(s),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...yo(s),...a,"HLS","HLS_ONDEMAND"];default:(0,Ka.assertNever)(e)}if(H.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:(0,Ka.assertNever)(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},by=({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=H.device.isMac&&H.browser.isSafari;if(H.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:(0,Ka.assertNever)(s)}else H.video.nativeHlsSupported&&!u&&!H.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"]},Rl=s=>s?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Io=s=>{if(s.size===0)return;if(s.size===1){let t=s.values().next();return(0,To.default)(t.value.split("."),0)}for(let t of s){let i=(0,To.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=s.values().next();return(0,To.default)(e.value.split("."),0)},Eo=s=>{let e=s.map(i=>Ei(i)),{codecs:t}=H.video;return A$().filter(i=>{if((0,Al.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})},wo=s=>{let e=s.map(i=>Ei(i)),{codecs:t}=H.video;return R$().filter(i=>{if((0,Al.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},Ei=s=>s.split(".")[0].replace("0",""),A$=()=>["av1","vp9","hev1","avc1"],R$=()=>["opus","mp4a"];var $y=G(bt(),1);var M$=(s,e={})=>{let i=e.timeout||1,r=performance.now();return Le.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},$$=s=>Le.clearTimeout(s),gy=s=>typeof s=="function"&&(s==null?void 0:s.toString().endsWith("{ [native code] }")),vy=!gy(Le.requestIdleCallback)||!gy(Le.cancelIdleCallback),ir=vy?M$:Le.requestIdleCallback,rr=vy?$$:Le.cancelIdleCallback;var C=require("@vkontakte/videoplayer-shared/es2018");var yy=G(bt(),1);var xo=s=>s.valid,ce=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 Hr=class extends ce{};var Sy=require("@vkontakte/videoplayer-shared/es2018");var Xa=class extends ce{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:(0,Sy.assertNever)(e)}}};var Ja=class extends ce{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 Za=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ie=class extends ce{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 es=class extends Ie{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 ts=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var is=class extends ce{constructor(e,t){super(e,t),this.data=this.content}};var ar=class extends Ie{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,c=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:c})}}}};var rs=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var as=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ss=class extends Ie{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 ns=class extends Ie{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var os=class extends Ie{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 us=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var cs=class extends Ie{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var ls=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ds=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ps=class extends Ie{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var hs=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var fs=class extends Ie{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var ms=class extends Ie{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 bs=class extends Ie{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 gs=class extends ce{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var vs=class extends Ie{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 Ss=class extends ce{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 C$={ftyp:Ja,moov:Za,mvhd:es,moof:ts,mdat:is,sidx:ar,trak:rs,mdia:us,mfhd:ps,tkhd:cs,traf:hs,tfhd:fs,tfdt:ms,trun:bs,minf:ls,sv3d:as,st3d:ss,prhd:ns,proj:ds,equi:os,uuid:Xa,stbl:gs,stsd:vs,avc1:Ss,unknown:Hr},Zt=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||!xo(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=C$[e];return i?new i(t,new s):new Hr(t,new s)}};var wi=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,a;xo(t)&&((a=(i=this.index)[r=t.type])!=null||(i[r]=[]),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 B$=new TextDecoder("ascii"),V$=s=>B$.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",_$=s=>{let e=new ar(s,new Zt),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})},O$=(s,e)=>{let i=new Zt().parse(s),r=new wi(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],c=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(s.buffer,c,d)},N$=s=>{let t=new Zt().parse(s),i=new wi(t),r={},a=i.findAll("uuid"),n=(0,yy.default)(a,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},F$=s=>{var r;let t=new Zt().parse(s);return(r=new wi(t).find("sidx"))==null?void 0:r.timescale},U$=(s,e)=>{let i=new Zt().parse(s),a=new wi(i).findAll("traf"),n=a[a.length-1].children.find(d=>d.type==="tfhd"),o=a[a.length-1].children.find(d=>d.type==="tfdt"),u=a[a.length-1].children.find(d=>d.type==="trun"),c=0;return u.sampleDuration.length?c=u.sampleDuration.reduce((d,p)=>d+p,0):c=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+c)/e*1e3},q$=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 Zt().parse(s),r=new wi(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},Ty={validateData:V$,parseInit:q$,getIndexRange:()=>{},parseSegments:_$,parseFeedableSegmentChunk:O$,getChunkEndTime:U$,getServerLatencyTimestamps:N$,getTimescaleFromIndex:F$};var Ts=G(Xe(),1),ei=require("@vkontakte/videoplayer-shared/es2018");var Ey=require("@vkontakte/videoplayer-shared/es2018");var Iy={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"}},wy=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=ys(s,t),r=i in Iy,a=r?Iy[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),c=n&255>>o,l=ys(u),d=c*2**((o-1)*8)+l,p=t+o,h;return p+d>s.byteLength?h=new DataView(s.buffer,s.byteOffset+p):h=new DataView(s.buffer,s.byteOffset+p,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},ys=(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},Rt=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return ys(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:(0,Ey.assertNever)(e)}},sr=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=wy(i);if(!e(r))return;r.type==="master"&&sr(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},xy=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=wy(s);return sr(r.value,({tag:a,type:n,value:o})=>(a===17143?e=Rt(o,n):a===17026?t=Rt(o,n):a===17029&&(i=Rt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Py=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],H$=[231,22612,22743,167,171,163,160,175],j$=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,c,l=!1,d=0;return sr(s,({tag:p,type:h,value:m,valueSize:b})=>{if(p===21419){let S=Rt(m,h);c=ys(S)}else p!==21420&&(c=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+b):p===357149030?a=!0:p===290298740?n=!0:p===2807729?i=Rt(m,h):p===17545?r=Rt(m,h):p===21420&&c===475249515?u=Rt(m,h):p===374648427?sr(m,({tag:S,type:v,value:y})=>S===30321?(l=Rt(y,v)===1,!1):!0):a&&n&&(0,Ts.default)(Py,p)&&(o=!0),!o}),(0,ei.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,ei.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,ei.assertNonNullable)(r,"Failed to parse webm Segment duration"),i=i!=null?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:l,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},W$=s=>{if((0,ei.isNullable)(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Q$=(s,e)=>{let t=!1,i=!1,r=o=>(0,ei.isNonNullable)(o.time)&&(0,ei.isNonNullable)(o.position),a=[],n;return sr(s,({tag:o,type:u,value:c})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=Rt(c,u));break;case 183:break;case 241:n&&(n.position=Rt(c,u));break;default:t&&(0,Ts.default)(Py,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:c,position:l}=o,d=a[u+1];return{status:"none",time:{from:c,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},z$=s=>{let e=0,t=!1;try{sr(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,Ts.default)(H$,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,Ts.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},ky={validateData:xy,parseInit:j$,getIndexRange:W$,parseSegments:Q$,parseFeedableSegmentChunk:z$};var nr=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return ky;case"mp4":return Ty}}throw new ReferenceError(`Unsupported mime type ${s}`)};var Ml=G(bt(),1);var Ay=require("@vkontakte/videoplayer-shared/es2018"),xi=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n,tvDisabled:o})=>{var c;let u=(c=a?vi(a):void 0)!=null?c:(0,Ay.videoSizeToQuality)({width:e,height:t});return u&&{id:s,quality:u,bitrate:i,size:{width:e,height:t},fps:r,streamId:n,tvDisabled:o}},Is=({id:s,bitrate:e})=>({id:s,bitrate:e}),Ry=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),My=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),$l=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,Ml.default)(i.split("."),0),isDefault:r}),Ll=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,Ml.default)(r.split("."),0)}),Cl=s=>"url"in s,dt=s=>s.type==="template";var jr=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,getCurrentStallDuration:o,manifest:u}){this.error$=new C.Subject;this.playingRepresentation$=new C.ValueSubject(void 0);this.playingRepresentationInit$=new C.ValueSubject(void 0);this.currentSegmentLength$=new C.ValueSubject(0);this.onLastSegment$=new C.ValueSubject(!1);this.fullyBuffered$=new C.ValueSubject(!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 ye;this.downloadAbortController=new ye;this.subscription=new C.Subscription;this.startWith=(0,C.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,C.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.containerParser=nr(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);(0,C.assertNonNullable)(i,"No init buffer for starting representation"),(0,C.assertNonNullable)(r,"No segments for starting representation"),await this.nativeBufferManager.addInitSegment(i),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a)}.bind(this));this.switchTo=(0,C.abortable)(this.destroyAbortController.signal,async function*(e,t=!0){var d;if((0,C.isNullable)(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);(0,C.assertNonNullable)(r,`No such representation ${e}`),(0,C.assertNonNullable)(i,`No such representation ${this.downloadingRepresentationId}`),yield this.loadInitIfNeeded(r,"high");let a=this.initData.get(r.id),n=this.segments.get(r.id);(0,C.assertNonNullable)(a,"No init buffer for switching representation"),(0,C.assertNonNullable)(n,"No segments for switching representation");let o=(d=this.getCurrentPosition())!=null?d:0,u=p=>p.segment.bufferStatus!=="fed",c=p=>{let h=this.representations.get(p.representationId);return(0,C.assertNonNullable)(h,"No itemRepresentation for previous track before switch"),p.segment.networkStatus!=="downloaded"||this.forceSwitchCondition(h,r)},l=p=>t?u(p)&&c(p):u(p);this.bufferPlaybackQueue.filter(l).forEach(p=>p.segment.bufferStatus="none"),this.bufferPlaybackQueue=this.bufferPlaybackQueue.filter(p=>!l(p)),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=(0,C.abortable)(this.downloadAbortController.signal,async function*(){let e=(0,C.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(t=>{let i=(0,C.getWindow)();this.loadByteRangeSegmentsTimeoutId=i.setTimeout(t,e),this.subscription.add((0,C.fromEvent)(i,"online").pipe((0,C.once)()).subscribe(()=>{t(),i.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}))})}.bind(this));var c;this.kind=e,this.nativeBufferManager=t,this.fetcher=r,this.tuning=a,this.getCurrentPosition=n,this.getCurrentStallDuration=o,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.baseUrls=(c=u==null?void 0:u.baseUrls)!=null?c:[],this.representations=new Map(i.map(l=>[l.id,l]))}async seek(e){await this.abort(),await this.clearBuffer(),await this.maintain(e)}async maintain(e=this.getCurrentPosition()){(0,C.isNullable)(e)||(await this.maintainPlaybackBuffer(e),await this.maintainNativeBuffer(),this.actualizeLastSegmentInfo(e))}getForwardPlaybackBufferDuration(e=this.getCurrentPosition()){let t=this.bufferPlaybackQueue.filter(a=>a.segment.networkStatus==="downloaded"),i=t[t.length-1],r=(0,C.isNonNullable)(e)&&(0,C.isNonNullable)(i)?i.segment.time.to-e:0;return Math.max(r,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){var a,n;let t=(n=(a=this.downloadingRepresentationId)!=null?a:this.playingRepresentationId)!=null?n:"",i=this.segments.get(t),r=i==null?void 0:i.find(o=>o.time.from<=e&&o.time.to>=e);return r==null?void 0:r.time.from}getRepresentationInitialTime(){var t;if((0,C.isNullable)(this.playingRepresentationId))return 0;let e=this.segments.get(this.playingRepresentationId);return((t=e==null?void 0:e[0].time.from)!=null?t:0)/1e3}calculateDurationFromSegments(e){var i;let t=this.segments.get(e);return(t?(i=(0,$y.default)(t,-1))==null?void 0:i.time.to:0)||0}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){let e=(0,C.getWindow)();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(),e.__polyfill_cancelIdleCallback_e6f3enkn2id4)for(let t of this.idleCallbacks.values())e.__polyfill_cancelIdleCallback_e6f3enkn2id4(t);this.idleCallbacks.clear(),e.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}forceSwitchCondition(e,t){let i=!0;if(this.kind==="video"){let r=xi(e),a=xi(t);i=(0,C.isNonNullable)(r)&&(0,C.isNonNullable)(a)&&(0,C.isHigher)(a.quality,r.quality)}else if(this.kind==="audio"){let r=Is(e),a=Is(t);i=(0,C.isNonNullable)(r==null?void 0:r.bitrate)&&(0,C.isNonNullable)(a==null?void 0: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 ye,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,ir(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():(0,C.isNonNullable)(r)?a=r:a=this.loadInit(e,t,i),await a}async loadInit(e,t="auto",i=!1){var r;try{let a=this.tuning.dash.useFetchPriorityHints?t:"auto",n=this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,a);this.initDataPromises.set(e.id,n);let{initMetadata:o,initDataView:u,segments:c}=(r=await n)!=null?r:{};if(this.initDataPromises.delete(e.id),(0,C.isNullable)(u)||(0,C.isNullable)(c))return;o&&this.parsedInitData.set(e.id,o);let l=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,l),this.segments.set(e.id,c),this.failedDownloads=0}catch(a){i&&this.error$.next({id:"LoadInits",category:C.ErrorCategory.WTF,message:"loadInit threw",thrown:a})}}async maintainNativeBuffer(){var h,m,b;let e=this.getCurrentPosition(),t=this.segments.get((h=this.downloadingRepresentationId)!=null?h:""),i=t==null?void 0:t[(t==null?void 0:t.length)-1];if((0,C.isNullable)(e)||(0,C.isNullable)(i)||this.maintainNativeBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex||this.preloadOnly)return;this.maintainNativeBufferMutex=!0;let r=this.bufferPlaybackQueue.find(S=>this.withinInterval(e,S.segment.time)),a=this.bufferPlaybackQueue.find(S=>S.segment.bufferStatus!=="fed"),n=this.initData.get((m=a==null?void 0:a.representationId)!=null?m:""),o=this.bufferPlaybackQueue[0],u=this.downloadAbortController.signal,l=((b=this.getCurrentStallDuration())!=null?b:0)>0;this.tuning.dash.useBufferHoldingOnlyOnStall&&l&&(l=e>0);let d=Math.min(this.tuning.dash.minSafeBufferToPlay,i.time.to-e),p=l?this.getForwardPlaybackBufferDuration()>=d:!0;(0,C.isNonNullable)(n)&&(0,C.isNonNullable)(a)&&(0,C.isNonNullable)(r)&&this.playingRepresentationId!==a.representationId&&this.withinAppendInterval(e,a.segment.time)&&(a===r||r.segment.bufferStatus==="fed")&&(await this.abortNativeBuffer(),await this.nativeBufferManager.addInitSegment(n,this.downloadAbortController.signal),this.playingRepresentationId=a.representationId,this.playingRepresentation$.next(this.playingRepresentationId)),(0,C.isNonNullable)(a)&&this.withinAppendInterval(e,a.segment.time)&&p&&(a.segment.loadedBytes===a.segment.size&&a.segment.bufferStatus==="none"?await this.appendSegmentFully(a,u):await this.appendSegmentPartially(a,u)),(0,C.isNonNullable)(o)&&this.withinRemoveInterval(e,o.segment.time)&&await this.removeSegment(o,u),this.pruneVirtualBuffer(e),this.maintainNativeBufferMutex=!1}async maintainPlaybackBuffer(e){(0,C.assertNonNullable)(this.downloadingRepresentationId);let t=this.segments.get(this.downloadingRepresentationId),i=this.representations.get(this.downloadingRepresentationId);if((0,C.isNullable)(t)||(0,C.isNullable)(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);(0,C.isNonNullable)(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0: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){var r;let t=this.segments.get((r=this.downloadingRepresentationId)!=null?r:"");if((0,C.isNullable)(t)||t.length===0)return;let i=t[(t==null?void 0:t.length)-1];(0,C.isNullable)(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){(0,C.assertNonNullable)(this.downloadingRepresentationId);let i=this.getPlaybackBufferState(),r,a;(0,C.isNonNullable)(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(0,C.isNonNullable)(e)?e+r>=t&&e<i:!1}withinAppendInterval(e,{from:t,to:i}){let{actionTimeShiftFromSegment:r}=this.tuning.dash;return(0,C.isNonNullable)(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(0,C.isNonNullable)(e)?e-i>t:!1}async appendSegmentFully(e,t){if((0,C.isNullable)(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((0,C.isNullable)(e.segment.data)||(0,C.isNullable)(e.segment.loadedBytes)||(0,C.isNullable)(e.segment.feedingBytes)||(0,C.isNullable)(e.segment.fedBytes)||(0,C.isNullable)(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!=null&&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||(0,C.isNonNullable)(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)(0,C.isNonNullable)(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())(0,C.isNonNullable)(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)}};var St=require("@vkontakte/videoplayer-shared/es2018"),Po=class extends jr{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=(0,St.now)(),this.failedDownloads=0}catch(o){this.abortDownloadingItems(),(0,St.isAbortError)(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(_e(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=(0,St.now)(),await this.onSomeDataLoaded({downloadingItems:e,dataView:o,loaded:u,signal:i,globalFrom:a?a.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:St.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}},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||(0,St.isNullable)(o)||(0,St.isNullable)(r)||n.aborted))for(let u of e){let{segment:c}=u,l=c.byte.from-r,d=c.byte.to-r,p=d-l+1,h=l<a,m=d<=a;c.size=p,h&&(c.networkStatus==="downloading"&&c.bufferStatus==="none"&&m?(c.data=new DataView(t.buffer,t.byteOffset+l,p),this.currentVirtualBufferSize+=c.size,this.onItemFullyDownloaded(u),c.loadedBytes=Math.min(p,a-l),await this.onDownloadItem(u)):(0,St.isNonNullable)(c.feedingBytes)&&this.tuning.dash.enableSubSegmentBufferFeeding&&c.networkStatus==="downloading"&&(c.loadedBytes=Math.min(p,a-l),m&&(this.currentVirtualBufferSize+=c.size,this.onItemFullyDownloaded(u)),c.loadedBytes>c.feedingBytes&&(c.data=new DataView(t.buffer,t.byteOffset+l,c.loadedBytes),await this.onDownloadItem(u))))}}updateRepresentationBaseUrl(e,t){if(_e(e.segmentReference))throw new Error("Representation is not byte range type");e.segmentReference.url=t}};var Mt=require("@vkontakte/videoplayer-shared/es2018"),Wr=class extends jr{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=(0,Mt.now)(),(0,Mt.isNullable)(o))return;let u=e[0],c=new DataView(o);u.segment.size=c.byteLength,u.segment.loadedBytes=c.byteLength,u.segment.data=c,this.onItemFullyDownloaded(u),await this.onDownloadItem(u),this.failedDownloads=0}catch(o){this.abortDownloadingItems(),(0,Mt.isAbortError)(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=(0,Mt.now)(),await this.onSomeDataLoaded({downloadingItems:e,dataView:n,loaded:o,signal:r,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:Mt.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}},signal:r,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}getFetchUrl(e,t){if(!_e(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||(0,Mt.isNullable)(u)||(0,Mt.isNullable)(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(!_e(e.segmentReference))throw new Error("Representation is not template type");e.segmentReference.baseUrl=t}};var Dl=G(Wa(),1),Ly=G(bt(),1);var Oe=require("@vkontakte/videoplayer-shared/es2018");var ko=class extends Wr{constructor(t,i,r,a){super(t,i,r,a);this.currentLiveSegmentServerLatency$=new Oe.ValueSubject(0);this.currentLowLatencySegmentLength$=new Oe.ValueSubject(0);this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.isActiveLowLatency=a.isActiveLowLatency}updateManifest(t){var r,a,n;if(!t||[...this.segments.values()].every(o=>!o.length))return;let i=(0,Dl.default)(t.streams[this.kind],o=>o.representations);for(let o of i){if((0,Oe.isNullable)(o)||!_e(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>({...h,networkStatus:"none",bufferStatus:"none",size:void 0})),c=100,l=(r=this.segments.get(o.id))!=null?r:[],d=(n=(a=(0,Ly.default)(l,-1))==null?void 0:a.time.to)!=null?n:0,p=u==null?void 0:u.findIndex(h=>d>=h.time.from+c&&d<=h.time.to+c);if(p===-1){let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(p+1);this.segments.set(o.id,[...l,...h])}this.representations.set(o.id,o)}}proceedLowLatencyLive(){let t=this.downloadingRepresentationId;(0,Oe.assertNonNullable)(t);let i=this.segments.get(t);if(i!=null&&i.length){let r={representationId:t,segmentIndex:i.length-1,segment:i[i.length-1]};this.updateLowLatencyLive(r)}}getLiveSegmentsToLoadState(t){let i=t==null?void 0:t.streams[this.kind],r=(0,Dl.default)(i,n=>n.representations).find(n=>n.id===this.downloadingRepresentationId);if((0,Oe.isNullable)(r))return;let a=this.segments.get(r.id);if(a!=null&&a.length)return{from:a[0].time.from,to:a[a.length-1].time.to}}getRepresentationInitialTime(){var r;if((0,Oe.isNullable)(this.playingRepresentationId))return 0;let t=(r=this.representations.get(this.playingRepresentationId))==null?void 0:r.segmentReference;return(0,Oe.isNullable)(t)||!_e(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),(0,Oe.isNullable)(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){var n;let i=t.segment.data,r=(n=this.representations.get(t.representationId))==null?void 0:n.segmentReference;if((0,Oe.isNullable)(t.segment.data)||(0,Oe.isNullable)(r)||!_e(r))return;let a=this.containerParser;if(t.segment.isCurrentLowLatency){let{timescale:o}=r;t.segment.time.to=a.getChunkEndTime(i,o)}}updateLowLatencyLive(t){var r;let i=0;for(let a of this.representations.values()){let n=a.segmentReference;if(!_e(n))return;let o=(r=this.segments.get(a.id))!=null?r:[],u=o.find(l=>Math.floor(l.time.from)===Math.floor(t.segment.time.from));if(u!=null&&u.isCurrentLowLatency&&(u.time.to=t.segment.time.to,i=u.time.to-u.time.from,u.isCurrentLowLatency=!1),!!!o.find(l=>Math.floor(l.time.from)===Math.floor(t.segment.time.to))&&this.isActiveLowLatency()){let l=Math.round(t.segment.time.to*n.timescale/1e3).toString(10),d=At(n.segmentTemplateUrl,{segmentTime:l});o.push({networkStatus:"none",bufferStatus:"none",time:{from:t.segment.time.to,to:t.segment.time.to+this.tuning.dash.bufferTolerance},url:d,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){var a;try{let n=this.tuning.dash.useFetchPriorityHints?i:"auto",o=this.fetcher.fetchRepresentation(t.segmentReference,this.containerParser,n);this.initDataPromises.set(t.id,o);let{initMetadata:u,initDataView:c,segments:l}=(a=await o)!=null?a:{};if(this.initDataPromises.delete(t.id),(0,Oe.isNullable)(c)||(0,Oe.isNullable)(l))return;u&&this.parsedInitData.set(t.id,u);let d=this.getActualLiveStartingSegments(t.segmentReference);this.segments.has(t.id)||this.segments.set(t.id,d);let p=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);this.initData.set(t.id,p),this.failedDownloads=0}catch(n){r&&this.error$.next({id:"LoadInits",category:Oe.ErrorCategory.WTF,message:"loadInit threw",thrown:n})}}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 Es=class{static getBufferManager(e,t,i,r){var a;return(a=r.manifest)!=null&&a.live?new ko(e,t,i,r):_e(i[0].segmentReference)?new Wr(e,t,i,r):new Po(e,t,i,r)}};var Ye=require("@vkontakte/videoplayer-shared/es2018");var Pi=require("@vkontakte/videoplayer-shared/es2018");var G$=18,Cy=!1;try{Cy=H.browser.isSafari&&!!H.browser.safariVersion&&H.browser.safariVersion<=G$}catch(s){console.error(s)}var Bl=class{constructor(e,t=!1){this.bufferFull$=new Pi.Subject;this.error$=new Pi.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Pi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};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)};Cy&&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(){var r;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((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Pi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:(0,Pi.assertNever)(t)}}},Dy=Bl;var ki=(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 ws=class{constructor(e){this.error$=new Ye.Subject;this.subscription=new Ye.Subscription;this.mediaSource=e}init(e,t,i=!1){this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e}; codecs="${t}"`),this.sourceBufferTaskQueue=new Dy(this.sourceBuffer,i),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(r=>this.error$.next(r))),this.subscription.add((0,Ye.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Ye.ErrorCategory.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((0,Ye.isNullable)(t))return Promise.resolve(!1);let i=!0;await this.sourceBufferTaskQueue.abort();for(let r of t)i&&(i=await this.sourceBufferTaskQueue.remove(r.from,r.to,e));return i}warmUpMediaSource(){!(0,Ye.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}getBufferState(){if((0,Ye.isNullable)(this.sourceBuffer)||!Se(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(0,Ye.isNullable)(this.sourceBuffer)||!Se(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,Ye.isNullable)(e)?0:ki(this.sourceBuffer.buffered,e)}async abortBuffer(e){return(0,Ye.isNullable)(this.sourceBuffer)?!1:this.sourceBufferTaskQueue.abort(e)}destroy(){var e;if(this.subscription.unsubscribe(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null}};var Ao=(s,e)=>{s.video.forEach(t=>{t.representations.forEach(i=>{var c;let{height:r,codecs:a,fps:n}=i,o=(c=e.find(([l,d,p])=>l===`${r}p`&&Ei(a)===p))==null?void 0:c[1],u=By(o)&&By(n)&&n>o;i.tvDisabled=u})})};function By(s){return typeof s=="number"&&Number.isInteger(s)}var Y$=["timeupdate","progress","play","seeked","stalled","waiting"],Vy=["timeupdate","progress","loadeddata","playing","seeked"],Qr=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.nativeBufferManagers=[];this.subscription=new I.Subscription;this.subscriptionRemovable=new I.SubscriptionRemovable;this.representationSubscription=new I.Subscription;this.forceEnded$=new I.Subject;this.destroyController=new ye;this.state$=new ae("none");this.currentVideoRepresentation$=new I.ValueSubject(void 0);this.currentVideoRepresentationInit$=new I.ValueSubject(void 0);this.currentAudioRepresentation$=new I.ValueSubject(void 0);this.currentVideoSegmentLength$=new I.ValueSubject(0);this.currentAudioSegmentLength$=new I.ValueSubject(0);this.error$=new I.Subject;this.manifestRequested=new I.Subject;this.manifestReceived=new I.Subject;this.firstBytesRequested=new I.Subject;this.firstBytesReceived=new I.Subject;this.lastConnectionType$=new I.ValueSubject(void 0);this.lastConnectionReused$=new I.ValueSubject(void 0);this.lastRequestFirstBytes$=new I.ValueSubject(void 0);this.lastConnectionMetrics$=new I.ValueSubject(void 0);this.lastDownloadMetrics$=new I.ValueSubject(void 0);this.currentLiveTextRepresentation$=new I.ValueSubject(null);this.isLive$=new I.ValueSubject(!1);this.isActiveLive$=new I.ValueSubject(!1);this.isLowLatency$=new I.ValueSubject(!1);this.liveDuration$=new I.ValueSubject(0);this.liveSeekableDuration$=new I.ValueSubject(0);this.liveAvailabilityStartTime$=new I.ValueSubject(0);this.liveStreamStatus$=new I.ValueSubject(void 0);this.currentBuffer$=new I.ValueSubject({from:0,to:0});this.bufferLength$=new I.ValueSubject(0);this.nativeBufferLength$=new I.ValueSubject(0);this.liveLatency$=new I.ValueSubject(void 0);this.liveLoadBufferLength$=new I.ValueSubject(0);this.livePositionFromPlayer$=new I.ValueSubject(0);this.currentStallDuration$=new I.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new I.ValueSubject(0);this.fetcherRecoverableError$=new I.Subject;this.fetcherError$=new I.Subject;this.initRepresentations=(0,I.abortable)(this.destroyController.signal,async function*(e,t,i){var a;this.tracer.log("initRepresentationsStart",(0,I.flattenObject)({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,getCurrentStallDuration:()=>this.currentStallDuration$.getValue(),isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest};this.createBuffers(r,e,t,i),this.initRepresentationSubscriptions(),yield this.waitStreamToOpen(),this.setSourceDuration(),(0,I.assertNonNullable)(this.videoBufferManager),yield Promise.all([this.videoBufferManager.startWith(e),t?(a=this.audioBufferManager)==null?void 0:a.startWith(t):Promise.resolve()]),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.fetchManifest=(0,I.abortable)(this.destroyController.signal,async function*(){try{return yield this.fetcher.fetchManifest(this.manifestUrlString)}catch(e){(0,I.isNullable)(this.manifest)&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:I.ErrorCategory.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 bo({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){var r;this.tracer.log("initManifest"),this.state$.startTransitionTo("manifest_ready"),this.element=e,this.manifestUrlString=this.prepareManifestUrlString(t,i),this.manifest=await this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:I.ErrorCategory.PARSER,message:"No playable video representations"})}initBuffer(){var t,i;(0,I.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,I.merge)(...Y$.map(r=>(0,I.fromEvent)(this.element,r)),(0,I.fromEvent)((0,I.getWindow)(),"online"),(0,I.interval)(this.tuning.dash.tickMaintainInterval)).subscribe(()=>this.tick(),r=>this.error$.next({id:"DashVKPlayer",category:I.ErrorCategory.WTF,message:"Internal logic error",thrown:r})));let e=[...(i=(t=this.source)==null?void 0:t.activeSourceBuffers)!=null?i:[]];this.subscription.add((0,I.merge)(...e.map(r=>(0,I.fromEvent)(r,"updateend"))).subscribe(r=>this.reinitDecoderIfNeeded())),this.subscription.add((0,I.fromEvent)(this.element,"waiting").subscribe(r=>{this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=(0,I.interval)(this.tuning.dash.stallWatchdogInterval).subscribe(()=>this.stallWatchdogIntervalCallback(),a=>this.error$.next({id:"StallWatchdogCallback",category:I.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:a})),this.subscriptionRemovable.add(this.stallWatchdogSubscription)}))}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return r==null?void 0:r.switchTo(t,i)}async seek(e,t=!1){var r,a,n,o,u;(0,I.assertNonNullable)(this.element),(0,I.assertNonNullable)(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),this.element.currentTime=i/1e3,H.browser.isSafari?(await((o=this.audioBufferManager)==null?void 0:o.seek(i)),await this.videoBufferManager.seek(i)):(await this.videoBufferManager.seek(i),await((u=this.audioBufferManager)==null?void 0:u.seek(i))),this.tracer.log("seek",(0,I.flattenObject)({requestedPosition:e,forcePrecise:t,position:i}))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){(0,I.isNonNullable)(this.element)&&(0,I.isNonNullable)(this.source)&&(0,I.isNonNullable)(e)&&this.isStreamEnded&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.nativeBufferManagers.forEach(i=>i.warmUpMediaSource())}calculateDurationFromSegments(e){var t,i;return Math.max(((t=this.videoBufferManager)==null?void 0:t.calculateDurationFromSegments(e))||0,((i=this.audioBufferManager)==null?void 0:i.calculateDurationFromSegments(e))||0)}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}getCodecs(){var e;return(e=this.manifest)==null?void 0:e.codecs}setBufferTarget(e){this.bufferManagers.forEach(t=>t.setTarget(e))}setPreloadOnly(e){this.bufferManagers.forEach(t=>t.setPreloadOnly(e))}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.nativeBufferManagers.forEach(r=>r.destroy()),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&(0,I.getWindow)().clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),(0,I.isNonNullable)(this.source)&&this.isStreamNotOpen&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}get isStreamNotOpen(){var e;return((e=this.source)==null?void 0:e.readyState)!=="open"}async reinitDecoderIfNeeded(e=!1){var r,a;let t=(a=(r=this.videoNativeBufferManager)==null?void 0:r.getBufferState())!=null?a:[];if((0,I.isNullable)(this.element)||!t.length)return;let i=this.element.currentTime*1e3;this.element.readyState<3&&t.some(n=>i>=n.from&&i<=n.to)&&(e?await this.seek(i):this.element.currentTime=this.element.currentTime)}async stallWatchdogIntervalCallback(){(0,I.assertNonNullable)(this.element),(0,I.assertNonNullable)(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)){if(this.tuning.dash.useNewStallExitPolicy)return this.seek(this.element.currentTime*1e3);throw new Error(`Stall timeout exceeded: ${t} ms`)}await this.restoreAfterDeepStall(i),this.tracer.log("stallIntervalCallback",(0,I.flattenObject)(i))}isStallExceeded(e){var p,h,m,b,S,v,y,x;let{crashOnStallTimeout:t,crashOnStallTWithoutDataTimeout:i}=this.tuning.dash,r=(0,I.now)(),a=100,n=(h=(p=this.videoBufferManager)==null?void 0:p.lastDataObtainedTimestamp)!=null?h:0;this.videoLastDataObtainedTimestamp$.next(n);let o=(b=(m=this.audioBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?b:0,u=(v=(S=this.videoBufferManager)==null?void 0:S.getForwardPlaybackBufferDuration())!=null?v:0,c=(x=(y=this.audioBufferManager)==null?void 0:y.getForwardPlaybackBufferDuration())!=null?x:0,l=(0,I.isNonNullable)(this.videoBufferManager)&&u<a&&r-n>i,d=(0,I.isNonNullable)(this.audioBufferManager)&&c<a&&r-o>i;return(l||d)&&e>i||e>=t}async updateManifest(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=await this.fetchManifest();if((0,I.isNullable)(e))return null;let t=this.parseManifest(e);if(!t)return null;let i=this.getResultManifest(t);return this.tracer.log("updateManifestEnd",(0,I.flattenObject)(i)),i}parseManifest(e){var t;try{return So(e!=null?e:"",this.manifestUrlString)}catch(i){let r=(t=ho(e))!=null?t:{id:"ManifestParsing",category:I.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:i};this.error$.next(r)}}getResultManifest(e){let t={text:e.streams.text,video:[],audio:[]},i=(o,u,c)=>{var l,d,p,h;return!!((d=(l=this.element)==null?void 0:l.canPlayType)!=null&&d.call(l,u)&&((h=(p=ut())==null?void 0:p.isTypeSupported)!=null&&h.call(p,`${u}; codecs="${c}"`))||o==="text")},r,a;for(let o of["video","audio"]){let c=e.streams[o].filter(({mime:d,codecs:p})=>i(o,d,p));t[o]=c;let l;if(this.tuning.dash.codecsPrioritizeEnabled){let d=c.map(({codecs:p})=>p);o==="audio"&&(a=wo(d),l=a[0]),o==="video"&&(r=Eo(d),this.forceVideoCodec&&(0,_y.default)(r,this.forceVideoCodec)?l=this.forceVideoCodec:l=r[0]),l&&(t[o]=c.filter(({codecs:p})=>Ei(p)===l))}else{let d=new Set(c.map(({codecs:p})=>p));l=Io(d),l&&(t[o]=c.filter(({codecs:p})=>p.startsWith(l)))}if(o==="video"){let d=this.tuning.preferHDR,p=t.video.some(b=>b.hdr),h=t.video.some(b=>!b.hdr);H.display.isHDR&&d&&p?t.video=t.video.filter(b=>b.hdr):h&&(t.video=t.video.filter(b=>!b.hdr));let{videoStreamRepresentaionsFilter:m}=this.tuning.dash;m.length&&Ao(t,m)}}let n={...e,streams:t};return this.tuning.dash.codecsPrioritizeEnabled&&(n.codecs={video:r,audio:a}),n}stopStallWatchdogSubscription(){var e;(e=this.stallWatchdogSubscription)==null||e.unsubscribe(),this.currentStallDuration$.next(0)}createBuffers(e,t,i,r){(0,I.assertNonNullable)(this.manifest),(0,I.assertNonNullable)(this.element);let a=c=>{this.representationSubscription.add((0,I.fromEvent)(c,"error").pipe((0,I.filter)(l=>{var d;return!!((d=this.element)!=null&&d.played.length)})).subscribe(l=>{this.error$.next({id:"VideoSource",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:l})}))};this.source=vn();let n=(0,I.getWindow)().document,o=n.createElement("source");if(a(o),o.src=URL.createObjectURL(this.source),this.element.appendChild(o),xr())if(r){let c=n.createElement("source");a(c),c.type="application/x-mpegurl",c.src=r.url,this.element.appendChild(c)}else this.element.disableRemotePlayback=!0;let u=this.manifest.streams.video.reduce((c,l)=>[...c,...l.representations],[]);if(this.videoNativeBufferManager=new ws(this.source),this.videoBufferManager=Es.getBufferManager("video",this.videoNativeBufferManager,u,e),this.bufferManagers=[this.videoBufferManager],this.nativeBufferManagers=[this.videoNativeBufferManager],(0,I.isNonNullable)(i)){this.audioNativeBufferManager=new ws(this.source);let c=this.manifest.streams.audio.reduce((l,d)=>[...l,...d.representations],[]);this.audioBufferManager=Es.getBufferManager("audio",this.audioNativeBufferManager,c,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=>{var i;e&&(this.timeoutSourceOpenId=(0,I.getWindow)().setTimeout(()=>{if(this.isStreamNotOpen){t();return}this.error$.next({id:"OpenOfStream",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(i=this.source)==null||i.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&(0,I.getWindow)().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(this.fetcher.lastConnectionMetrics$.subscribe(this.lastConnectionMetrics$)),this.representationSubscription.add(this.fetcher.lastDownloadMetrics$.subscribe(this.lastDownloadMetrics$)),this.representationSubscription.add((0,I.merge)(...this.bufferManagers.map(e=>e.error$)).subscribe(this.error$)),(0,I.assertNonNullable)(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((0,I.merge)(...Vy.map(e=>(0,I.fromEvent)(this.element,e))).pipe((0,I.map)(e=>{var t;return(t=this.videoBufferManager)==null?void 0:t.getPlaybackBufferState()}),(0,I.filter)(I.isNonNullable),(0,I.map)(({from:e,to:t})=>({from:e/1e3,to:t/1e3}))).subscribe(this.currentBuffer$)),this.representationSubscription.add((0,I.merge)(...Vy.map(e=>(0,I.fromEvent)(this.element,e))).pipe((0,I.map)(e=>{var t,i,r,a,n,o;return Math.min((i=(t=this.videoBufferManager)==null?void 0:t.getForwardPlaybackBufferDuration())!=null?i:0,(a=(r=this.audioBufferManager)==null?void 0:r.getForwardPlaybackBufferDuration())!=null?a:0,(o=(n=this.audioBufferManager)==null?void 0:n.getForwardPlaybackBufferDuration())!=null?o:0)}),(0,I.filterChanged)()).subscribe(this.bufferLength$)),this.representationSubscription.add(this.nativeBufferLength$.pipe((0,I.filter)(e=>e>this.tuning.dash.bufferEmptinessTolerance)).subscribe(e=>this.stopStallWatchdogSubscription()))}initTracerSubscription(){let e=(0,I.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}async tick(){var r,a,n;if((0,I.isNullable)(this.element)||(0,I.isNullable)(this.videoBufferManager)||this.isStreamNotOpen)return;let e=this.element.currentTime*1e3,i=((a=(r=this.videoNativeBufferManager)==null?void 0:r.getBufferState())!=null?a:[]).find(o=>e>=o.from&&e<=o.to);this.nativeBufferLength$.next(i?i.to-e:0),await this.videoBufferManager.maintain(e),await((n=this.audioBufferManager)==null?void 0:n.maintain(e))}};var fe=require("@vkontakte/videoplayer-shared/es2018");var Ro=class extends Qr{constructor(e){super(e)}prepareManifestUrlString(e,t){return e}initRepresentationSubscriptions(){super.initRepresentationSubscriptions(),this.initDisableStallWatchdogSubscription(),this.initEndOfVideoSubscription()}setSourceDuration(){var t;(0,fe.assertNonNullable)(this.manifest),(0,fe.assertNonNullable)(this.source);let e=[(t=this.manifest.duration)!=null?t:0,...(0,Vl.default)((0,Vl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],i=>i.representations),i=>{let r=[];return i.duration&&r.push(i.duration),_e(i.segmentReference)&&i.segmentReference.totalSegmentsDurationMs&&r.push(i.segmentReference.totalSegmentsDurationMs),r})];this.source.duration=Math.max(...e)/1e3}async restoreAfterDeepStall(e){var i,r;(0,fe.assertNonNullable)(this.element);let t=this.element.currentTime*1e3;await Promise.all([(i=this.videoBufferManager)==null?void 0:i.maintain(t),(r=this.audioBufferManager)==null?void 0:r.maintain(t)]),e.position=t}initDisableStallWatchdogSubscription(){(0,fe.assertNonNullable)(this.element);let e=(0,fe.merge)((0,fe.fromEvent)(this.element,"ended"),this.forceEnded$),t=this.nativeBufferLength$.pipe((0,fe.filter)(i=>i>this.tuning.dash.bufferEmptinessTolerance));this.representationSubscription.add((0,fe.merge)(e,t).subscribe(i=>this.stopStallWatchdogSubscription()))}initEndOfVideoSubscription(){let e=(0,fe.merge)(...this.bufferManagers.map(a=>a.fullyBuffered$)).pipe((0,fe.map)(()=>this.bufferManagers.every(a=>a.fullyBuffered$.getValue()))),t=(0,fe.merge)(...this.bufferManagers.map(a=>a.onLastSegment$)).pipe((0,fe.map)(()=>this.bufferManagers.some(a=>a.onLastSegment$.getValue()))),i=(0,fe.combine)({allBuffersFull:e,someBufferEnded:t}).pipe((0,fe.filterChanged)(),(0,fe.map)(({allBuffersFull:a,someBufferEnded:n})=>a&&n),(0,fe.filter)(a=>a)),r=()=>{var a;try{(a=this.source)==null||a.endOfStream()}catch(n){this.error$.next({id:"EndOfStream",category:fe.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:n})}};this.representationSubscription.add((0,fe.merge)(this.forceEnded$,i).pipe((0,fe.filter)(a=>(0,fe.isNonNullable)(this.source)&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(n=>!n.updating))).subscribe(r))}};var xs=class extends Zi{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,zr.filterChanged)(),(0,zr.filter)(a=>(0,zr.isNonNullable)(a))).subscribe(a=>{let n=this.player.calculateDurationFromSegments(a);n&&this.params.output.duration$.next(n/1e3)},r))}getPlayer(){return new Ro({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)}};var be=require("@vkontakte/videoplayer-shared/es2018");var Ps=require("@vkontakte/videoplayer-shared/es2018"),Ai=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Ps.ValueSubject(e.initial),this.debounced$=new Ps.ValueSubject(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ze(`raw_${t}`),this.smoothedSeries$=new ze(`smoothed_${t}`),this.reportedSeries$=new ze(`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)&&((0,Ps.isNullable)(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var Mo=class extends Ai{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Jt(this.slow,e,this.params.emaAlphaSlow),this.fast=Jt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var $o=class extends Ai{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=ll(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Jt(this.emaSmoothed,e,this.params.emaAlpha);let i=Lv(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Lo=class extends Ai{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?Jt(this.smoothed,t,this.params.emaAlpha):t}};var ti=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Mo({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new $o({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 Lo({initial:e,label:"liveEdgeDelay",...t})}};var Y=require("@vkontakte/videoplayer-shared/es2018");var Gr=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)};var Co=require("@vkontakte/videoplayer-shared/es2018");var ks=class s{constructor(e,t){this.currentRepresentation$=new Co.ValueSubject(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!(0,Co.isNullable)(e))for(let i of this.representations)for(let r of i){let a=r.segmentReference,n=a.segments.length,o=a.segments[0].time.from,u=a.segments[n-1].time.to;if(e<o||e>u)continue;let c=a.segments.find(l=>l.time.from<=e&&l.time.to>=e);!c||((t=this.currentSegment)==null?void 0:t.time.from)===c.time.from&&this.currentSegment.time.to===c.time.to||(this.currentSegment=c,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(c.url,a.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?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!=null&&e.some(t=>s.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&_e(t.segmentReference))}};var Do=class extends Qr{constructor(t){super(t);this.liveStreamEndTimestamp=0;this.liveWasInterrupted=!1;this.liveBuffer=ti.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...t.tuning.dashCmafLive.lowLatency.bufferEstimator})}async seek(t){(0,Y.assertNonNullable)(this.element),this.updateManifestUrlWithTimeOffset(t),this.manifest=await this.updateManifest(),await this.forcePositionToRepresentationInitialTime()}initBuffer(){super.initBuffer(),this.forcePositionToRepresentationInitialTime()}async forcePositionToRepresentationInitialTime(){var r;let t=this.videoBufferManager,i=(r=t==null?void 0:t.getRepresentationInitialTime())!=null?r:0;await super.seek(i,!1)}async tick(){var i,r,a;await super.tick();let t=((r=(i=this.element)==null?void 0:i.currentTime)!=null?r:0)*1e3;(a=this.liveTextManager)==null||a.maintain(t)}setSourceDuration(){(0,Y.assertNonNullable)(this.source),this.source.duration=Number.MAX_SAFE_INTEGER}isStallExceeded(t){let{keepSilentStallWatchdogWhenNotActive:i}=this.tuning.dashCmafLive,a=this.liveStreamStatus$.getValue()==="active";return(!i||a)&&super.isStallExceeded(t)}async restoreAfterDeepStall(t){let{liveStallReinitInterval:i}=this.tuning.dash,{keepSilentStallWatchdogWhenNotActive:r}=this.tuning.dashCmafLive,a=this.currentStallDuration$.getValue(),o=this.liveStreamStatus$.getValue()==="active";if(a%i===0){let u=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);t.liveLastOffset=u,!o&&r?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(u),this.manifest=await this.updateManifest(),await this.forcePositionToRepresentationInitialTime()):this.seek(u).catch(c=>{this.error$.next({id:"stallIntervalCallback",category:Y.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:c})})}}async updateManifest(){var l,d;let t=await super.updateManifest();if((0,Y.isNullable)(t))return null;if((0,Y.isNullable)(t.live))return this.error$.next({id:"ManifestParsing",category:Y.ErrorCategory.PARSER,message:"MPD doesnt contain live section for live stream"}),null;this.isLive$.next(!0);let{availabilityStartTime:i,latestSegmentPublishTime:r,streamIsUnpublished:a,streamIsAlive:n}=t.live,o=((l=t.duration)!=null?l:0)/1e3;this.liveSeekableDuration$.next(-1*o),this.liveDuration$.next((r-i)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let u="active";if(n||(u=a?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(u),this.bufferManagers.forEach(p=>p.updateManifest(t)),(d=this.liveTextManager)==null||d.updateLive(t),n&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let p=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seek(p).catch(h=>{this.error$.next({id:"updateManifest",category:Y.ErrorCategory.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:h})})}return t}prepareManifestUrlString(t,i){return Ae(t,i,2)}updateManifestUrlWithTimeOffset(t){let i=this.liveStreamStatus$.getValue()!=="active"?(0,Y.now)()-this.liveStreamEndTimestamp:0,r=this.normalizeLiveOffset(t+i);this.isActiveLive$.next(r===0),this.manifestUrlString=Ae(this.manifestUrlString,r,2)}createBuffers(t,i,r,a){(0,Y.assertNonNullable)(this.manifest),super.createBuffers(t,i,r,a),ks.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new ks(this.manifest.streams.text,t))}initRepresentationSubscriptions(){(0,Y.assertNonNullable)(this.element),(0,Y.assertNonNullable)(this.videoBufferManager),this.isActiveLive$.next(this.isLive$.getValue()),super.initRepresentationSubscriptions();let t=this.videoBufferManager,i=this.bufferManagers;this.initStreamDurationOnPauseSubscription(),this.initLiveChangePlaybackRateSubscriptions(),this.initLiveDurationSubscriptions(t),this.initLiveBufferInfoSubscriptions(t,i),this.initLiveMaintainSubscription(i),(0,Y.isNonNullable)(this.liveTextManager)&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$))}initStreamDurationOnPauseSubscription(){(0,Y.assertNonNullable)(this.element);let{liveUpdateInterval:t}=this.tuning.dash,i=()=>(0,Y.interval)(t).subscribe(async r=>{let a=pi(this.manifestUrlString,2);this.manifestUrlString=Ae(this.manifestUrlString,a+t,2),this.liveStreamStatus$.getValue()==="active"&&(this.manifest=await this.updateManifest())});this.representationSubscription.add((0,Y.fromEvent)(this.element,"pause").subscribe(r=>{this.livePauseWatchdogSubscription=i(),this.representationSubscription.add(this.livePauseWatchdogSubscription)})),this.representationSubscription.add((0,Y.fromEvent)(this.element,"play").subscribe(r=>{var a;return(a=this.livePauseWatchdogSubscription)==null?void 0:a.unsubscribe()}))}initLiveDurationSubscriptions(t){this.representationSubscription.add(this.liveDuration$.pipe((0,Y.filterChanged)()).subscribe(i=>this.liveStreamEndTimestamp=(0,Y.now)())),this.representationSubscription.add(t.currentLowLatencySegmentLength$.subscribe(i=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!i)return;let r=this.liveSeekableDuration$.getValue()-i/1e3;this.liveSeekableDuration$.next(Math.max(r,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+i/1e3)}))}initLiveChangePlaybackRateSubscriptions(){this.representationSubscription.add((0,Y.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,Y.map)(({isActiveLive:t,isLowLatency:i})=>t&&i),(0,Y.filterChanged)(),(0,Y.filter)(t=>!this.isManualDecreasePlaybackInLive())).subscribe(t=>Gr(this.element,1))),this.representationSubscription.add((0,Y.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,Y.filter)(t=>!this.isManualDecreasePlaybackInLive())).subscribe(({liveBuffer:t,isActiveLive:i,isLowLatency:r})=>{if(!r||!i)return;let a=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,n=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,o=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,u=t-a,c=1;Math.abs(u)>n&&(c=1+Math.sign(u)*o),Gr(this.element,c)}))}initLiveBufferInfoSubscriptions(t,i){this.representationSubscription.add((0,Y.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,Y.filter)(({bufferLength:r,isActiveLive:a,isLowLatency:n})=>a&&n&&!!r),(0,Y.map)(({bufferLength:r})=>r)).subscribe(this.liveBuffer)),this.representationSubscription.add(this.bufferLength$.subscribe(r=>{var n,o;let a=0;if(r){let u=((o=(n=this.element)==null?void 0:n.currentTime)!=null?o:0)*1e3;a=Math.min(...i.map(l=>{var d,p;return(p=(d=l.getLiveSegmentsToLoadState(this.manifest))==null?void 0:d.to)!=null?p:u}))-u}this.liveLoadBufferLength$.getValue()!==a&&this.liveLoadBufferLength$.next(a)})),this.representationSubscription.add((0,Y.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:t.currentLiveSegmentServerLatency$}).pipe((0,Y.filter)(({isLive:r})=>r),(0,Y.filterChanged)((r,a)=>a.bufferLength<r.bufferLength),(0,Y.map)(({rtt:r,bufferLength:a,segmentServerLatency:n})=>{let o=pi(this.manifestUrlString,2);return(r/2+a+n+o)/1e3})).subscribe(this.liveLatency$))}initLiveMaintainSubscription(t){let i=0;this.representationSubscription.add((0,Y.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,Y.throttle)(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:r,bufferLength:a})=>{(0,Y.assertNonNullable)(this.element);let n=this.element.playbackRate,o=pi(this.manifestUrlString,2),u=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,c=Math.min(u,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*n),l=this.tuning.dashCmafLive.normalizedActualBufferOffset*n,d=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*n,p=isFinite(r)?r:a,h=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),m=u<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(m);let b="none";if(h?b="active_low_latency":this.isLowLatency$.getValue()&&m?(t.forEach(S=>S.proceedLowLatencyLive()),b="active_low_latency"):o!==0&&p<c?b="live_forward_buffering":p<c+d&&(b="live_with_target_offset"),isFinite(r)&&(i=r>i?r:i),b==="live_forward_buffering"||b==="live_with_target_offset"){let S=i-(c+l),v=this.normalizeLiveOffset(Math.trunc(o+S/n)),y=Math.abs(v-o),x=0;!r||y<=this.tuning.dashCmafLive.offsetCalculationError?x=o:v>0&&y>this.tuning.dashCmafLive.offsetCalculationError&&(x=v),this.manifestUrlString=Ae(this.manifestUrlString,x,2)}(b==="live_with_target_offset"||b==="live_forward_buffering")&&(i=0,this.manifest=await this.updateManifest())},r=>{this.error$.next({id:"updateLive",category:Y.ErrorCategory.VIDEO_PIPELINE,thrown:r,message:"Failed to update live with subscription"})}))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let t=1-this.element.playbackRate;return Number(t.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normalizeLiveOffset(t){return Math.trunc(t/1e3)*1e3}};var Yr=class extends Zi{constructor(e){super(e),this.textTracksManager.destroy()}getPlayer(){return new Do({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec})}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);let o=new be.ValueSubject(1);n(r.playbackRateState$,o),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe((0,be.filterChanged)()).subscribe(u=>{let c=i.position$.getValue(),l=i.volume$.getValue(),d=!l.volume||l.muted;!u&&!c&&d?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((0,be.map)(u=>u.to)).subscribe(this.player.isLowLatency$)).add((0,be.combine)({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,be.map)(({liveBufferTime:u,liveAvailabilityStartTime:c})=>u&&c?u+c:void 0)).subscribe(i.liveTime$)).add((0,be.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,be.merge)(r.playbackRateState$,new be.ValueSubject(1))}).pipe((0,be.filter)(({liveStreamStatus:u,liveDuration:c})=>u==="active"&&!!c)).subscribe(({liveDuration:u,playbackRate:c})=>{let l=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;d||c<1-p||this.video.paused||(0,be.isNullable)(l)||(t=u-l)})).add((0,be.combine)({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,be.merge)(r.playbackRateState$,new be.ValueSubject(1))}).pipe((0,be.filterChanged)((u,c)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===c.liveDuration:u.time===c.time)).subscribe(({time:u,liveDuration:c,playbackRate:l})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&l>=1-p||(0,be.isNullable)(u)||(0,be.isNullable)(c))return;let h=-1*(c-u-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let c=Rv(u);this.params.output.availableTextTracks$.next([c])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe((0,be.filter)(u=>(0,be.isNonNullable)(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.seek(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var W=require("@vkontakte/videoplayer-shared/es2018");var qy=G(Xe(),1),Nl=G(Wa(),1);var Ri=(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};var T=require("@vkontakte/videoplayer-shared/es2018");var Bo=G(Xe(),1),or=G(bt(),1),Vo=G(Wa(),1);var Uy=G(Wc(),1);var Mi=require("@vkontakte/videoplayer-shared/es2018");var X$=18,Ny=!1;try{Ny=H.browser.isSafari&&!!H.browser.safariVersion&&H.browser.safariVersion<=X$}catch(s){console.error(s)}var _l=class{constructor(e,t=!1){this.bufferFull$=new Mi.Subject;this.error$=new Mi.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Mi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};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)};Ny&&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(){var r;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((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Mi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:(0,Mi.assertNever)(t)}}},Fy=_l;var Ol=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};var P=require("@vkontakte/videoplayer-shared/es2018");var As=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:c}){this.currentLiveSegmentServerLatency$=new P.ValueSubject(0);this.currentLowLatencySegmentLength$=new P.ValueSubject(0);this.currentSegmentLength$=new P.ValueSubject(0);this.onLastSegment$=new P.ValueSubject(!1);this.fullyBuffered$=new P.ValueSubject(!1);this.playingRepresentation$=new P.ValueSubject(void 0);this.playingRepresentationInit$=new P.ValueSubject(void 0);this.error$=new P.Subject;this.gaps=[];this.subscription=new P.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ye;this.switchAbortController=new ye;this.destroyAbortController=new ye;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=(0,P.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,P.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Fy(this.sourceBuffer,this.tuning.dash.useAbortMSEFix),this.subscription.add((0,P.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add((0,P.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:P.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!Se(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Ol(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let c=this.getForwardBufferDuration(o),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,c<l).catch(d=>{this.handleAsyncError(d,"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);(0,P.assertNonNullable)(i,"No init buffer for starting representation"),(0,P.assertNonNullable)(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=(0,P.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!Se(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,P.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,P.isNullable)(a)||(0,P.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,P.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!Se(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();(0,P.isNonNullable)(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=(0,P.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!Se(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,P.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,P.isNullable)(a)||(0,P.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,P.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!Se(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();(0,P.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=(0,P.abortable)(this.destroyAbortController.signal,async function*(e){var u;let t=(0,Vo.default)(e,c=>c.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let c of this.representations.keys()){let l=t.find(h=>h.id===c);l&&this.representations.set(c,l);let d=this.representations.get(c);if(!d||!dt(d.segmentReference)){this.isSeekingLive=!1;return}let p=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,p)}let i=(u=this.switchingToRepresentationId)!=null?u:this.downloadingRepresentationId,r=this.representations.get(i);(0,P.assertNonNullable)(r,`Representation not found by id ${i}`);let a=this.segments.get(i);(0,P.assertNonNullable)(a,"No segments for starting representation");let n=this.initData.get(i);if((0,P.assertNonNullable)(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));var l;this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(c!=null&&c.live),this.baseUrls=(l=c==null?void 0:c.baseUrls)!=null?l:[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!Se(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ye,(0,P.abortable)(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);(0,P.assertNonNullable)(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if((0,P.isNullable)(o)||(0,P.isNullable)(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),(0,P.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!Se(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();(0,P.isNonNullable)(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!(0,P.isNullable)(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 ye,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var p;if((0,P.isNullable)(e)||(0,P.isNullable)(this.downloadingRepresentationId)||(0,P.isNullable)(this.playingRepresentationId)||(0,P.isNullable)(this.sourceBuffer)||!Se(this.mediaSource,this.sourceBuffer)||(0,P.isNonNullable)(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((0,P.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),(0,P.assertNonNullable)(i,`No such representation ${this.playingRepresentationId}`),(0,P.isNullable)(r)||(0,P.isNullable)(a))return;let n=r.find(h=>e>=h.time.from&&e<h.time.to);(0,P.isNonNullable)(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next((n==null?void 0:n.time.to)-n.time.from);let o=e,u=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let h=this.getForwardBufferDuration(e),m=xi(i),b=xi(t),S=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&(0,P.isNonNullable)(m)&&(0,P.isNonNullable)(b)&&(0,P.isHigher)(m.quality,b.quality),v=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(S||v?o+=Math.min(h,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=n.time.to-e+u&&(o=n?n.time.to+u:-1/0),this.tuning.dash.useNewRepresentationSwitch){let x=(p=[...this.segments.entries()].map(([w,M])=>{let _=M.find(q=>e>=q.time.from&&e<q.time.to);return{representationId:w,status:_==null?void 0:_.status}}).find(w=>w.status==="fed"))==null?void 0:p.representationId;x&&(this.playingRepresentationId=x,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&Ol(this.sourceBuffer.buffered)>=this.bufferLimit){let h=this.getForwardBufferDuration(e),m=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,h<m).catch(b=>{this.handleAsyncError(b,"pruneBuffer")});return}let l=[];if(!this.activeSegments.size&&(l=this.selectForwardBufferSegments(r,t.segmentReference.type,o),l.length)){let h="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,Bo.default)(l,n))h="high";else{let m=(0,or.default)(l,0);m&&m.time.from-n.time.to>=this.forwardBufferTarget/2&&(h="low")}this.loadSegments(l,t,h).catch(m=>{this.handleAsyncError(m,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!l.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let d=(0,or.default)(r,-1);!this.isLive&&d&&(this.fullyBuffered$.next(d.time.to-e-this.getForwardBufferDuration(e)<u),this.onLastSegment$.next(e-d.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;(0,P.isNonNullable)(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==null?void 0:e.streams[this.kind];if(!t)return;let i=(0,Vo.default)(t,a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var i,r,a;if(!e||[...this.segments.values()].every(n=>!n.length))return;let t=(0,Vo.default)(e.streams[this.kind],n=>n.representations);for(let n of t){if(!n||!dt(n.segmentReference))return;let o=n.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),u=100,c=(i=this.segments.get(n.id))!=null?i:[],l=(a=(r=(0,or.default)(c,-1))==null?void 0:r.time.to)!=null?a:0,d=o==null?void 0:o.findIndex(p=>l>=p.time.from+u&&l<=p.time.to+u);if(d===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(n.segmentReference);this.segments.set(n.id,p)}else{let p=o.slice(d+1);this.segments.set(n.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,P.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){var t;if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(t=(0,or.default)(e,-1))==null?void 0:t.time.to:0)||0}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let a=r.segmentReference;if(!dt(a))return;let n=(i=this.segments.get(r.id))!=null?i:[],o=n.find(c=>Math.floor(c.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(c=>Math.floor(c.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let c=Math.round(e.time.to*a.timescale/1e3).toString(10),l=At(a.segmentTemplateUrl,{segmentTime:c});n.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&rr&&rr(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&rr&&rr(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}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:p,time:{from:h,to:m}},b)=>{let S=h<=i&&m>=i,v=h>i||S||b===0&&i===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),x=this.preloadOnly&&h<=i+y||r<y&&m-h>=y||m<=i+y;return(p==="none"||p==="partially_ejected"&&v&&x&&this.sourceBuffer&&Se(this.mediaSource,this.sourceBuffer)&&!(Ri(this.sourceBuffer.buffered,h)&&Ri(this.sourceBuffer.buffered,m)))&&v&&x});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,c=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let p=a;p<n.length&&(o<=l||u<=d);p++){let h=n[p];if(o+=h.byte.to+1-h.byte.from,u+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")c.push(h);else break}return c}async loadSegments(e,t,i="auto"){dt(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:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await(0,P.abortable)(o,async function*(){let l=(0,P.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,l))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let l=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=(0,P.now)(),!l)return;let d=new DataView(l),p=nr(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=p.getChunkEndTime(d,b)}u&&r.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=p.getServerLatencyTimestamps(d);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(l){this.abortActiveSegments([e]),(0,P.isAbortError)(l)||(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())dt(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(0,P.abortable)(n,async function*(){let u=(0,P.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,u),(0,P.fromEvent)(window,"online").pipe((0,P.once)()).subscribe(()=>{c(),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=(0,P.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),(0,P.isAbortError)(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(dt(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,or.default)(e,0).byte.from,to:(0,or.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=(0,P.now)(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!dt(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?(c,l)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=(0,P.now)();let d=this.onSomeTemplateDataLoaded({dataView:c,loaded:l,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Bo.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!Se(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 c=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),l=nr(n.mime).parseFeedableSegmentChunk(c,this.isLive);l!=null&&l.byteLength&&(u.status="partially_fed",o.feedingBytes+=l.byteLength,await this.sourceBufferTaskQueue.append(l),o.fedBytes+=l.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!Se(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:c}=u;if(u.representationId!==t)continue;if(a.aborted){await n();continue}let l=c.byte.from-i,d=c.byte.to-i,p=d-l+1,h=l<r,m=d<=r;if(!h)continue;let b=nr(o.mime);if(c.status==="downloading"&&m){c.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+l,p);await this.sourceBufferTaskQueue.append(S,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(u.loadedBytes=Math.min(p,r-l),u.loadedBytes>u.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+l+u.feedingBytes,u.loadedBytes-u.feedingBytes),v=u.loadedBytes===p?S:b.parseFeedableSegmentChunk(S);v!=null&&v.byteLength&&(c.status="partially_fed",u.feedingBytes+=v.byteLength,await this.sourceBufferTaskQueue.append(v,a)&&!a.aborted?(u.fedBytes+=v.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var i;if(!((0,P.isNullable)(this.sourceBuffer)||!Se(this.mediaSource,this.sourceBuffer))){!this.isLive&&H.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ri(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ri(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:P.ErrorCategory.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",Cl(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let a of(i=this.segments.get(r.id))!=null?i:[])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.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||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=ir(()=>(0,Uy.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?(0,P.abortable)(this.destroyAbortController.signal,async function*(){let u=(0,P.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,nr(e.mime),{priority:r,ignoreNetworkErrors:a})).then(async u=>{if(!u)return;let{init:c,dataView:l,segments:d}=u,p=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,p);let h=d;this.isLive&&dt(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),c&&this.parsedInitData.set(e.id,c)}).then(()=>this.failedDownloads=0,u=>{a||this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:P.ErrorCategory.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||!Se(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,P.isNullable)(e))return!1;let r=[],a=0,n=u=>{u.sort((l,d)=>l.from-d.from);let c=[u[0]];for(let l=1;l<u.length;l++){let{from:d,to:p}=u[l],h=c[c.length-1];h.to>=d?h.to=Math.max(h.to,p):c.push(u[l])}return c},o=u=>{var l;if(a>=t)return r;r.push({...u.time}),r=n(r);let c=Cl(u)?(l=u.size)!=null?l:0:u.byte.to-u.byte.from;a+=c};for(let u of this.segments.values())for(let c of u){let l=c.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=c.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||d)&&c.status==="fed"&&o(c)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let c=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)(0,Bo.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(l)&&d++;if(d===this.segments.size){let p={time:{from:c,to:l},url:"",status:"none"};o(p)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let l of c)l.time.from>=e+u&&l.status==="fed"&&o(l)}return r.length?(await Promise.all(r.map(c=>this.sourceBufferTaskQueue.remove(c.from,c.to)))).reduce((c,l)=>c||l,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!Se(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||!Se(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||!Se(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,P.isNullable)(e)?0:ki(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!Se(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||!Se(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=ir(()=>{try{this.detectGaps(e,t)}catch(a){this.error$.next({id:"GapDetection",category:P.ErrorCategory.WTF,message:"detectGaps threw",thrown:a})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if((0,P.isNullable)(this.sourceBuffer)||!Se(this.mediaSource,this.sourceBuffer)||(0,P.isNullable)(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(l=>l.from-t<=n&&l.to+t>=o),c=e.filter(l=>n>=l.from&&n<l.to-t||o>l.from+t&&o<=l.to);u||(c.length===1?r.status="partially_ejected":this.gaps.some(l=>l.from===r.time.from||l.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:P.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var F=require("@vkontakte/videoplayer-shared/es2018");var _o=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.manifestRequested$=new F.Subject;this.firstBytesManifest$=new F.Subject;this.firstBytesRequested$=new F.Subject;this.firstBytesReceived$=new F.Subject;this.lastConnectionType$=new F.ValueSubject(void 0);this.lastConnectionReused$=new F.ValueSubject(void 0);this.lastRequestFirstBytes$=new F.ValueSubject(void 0);this.lastConnectionMetrics$=new F.ValueSubject(void 0);this.lastDownloadMetrics$=new F.ValueSubject(void 0);this.recoverableError$=new F.Subject;this.error$=new F.Subject;this.abortAllController=new ye;this.subscription=new F.SubscriptionRemovable;this.performanceObserver=null;this.pendingConnectionMetrics=new Map;this.fetchManifest=(0,F.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Ii(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=mo(i)),this.trackRequestStart(i,performance.now());let r=(0,F.now)();this.manifestRequested$.next();let a=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(F.suppressAbort);if(a){let n=(0,F.now)();t.log("success",(0,F.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(a.headers),this.firstBytesManifest$.next();let o=a.headers.get("content-length"),u=0;o&&(u=parseInt(o,10));let c=await a.text();if((!o||isNaN(u)||u<=0)&&(u=new TextEncoder().encode(c).length),u>0){let l=n-r,p=u/(l/1e3)*8/1024,h={bytes:u,speed:p,url:e};this.lastDownloadMetrics$.next(h)}return c}else return t.error("error",(0,F.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null}.bind(this));this.fetch=(0,F.abortable)(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:c=!1,ignoreNetworkErrors:l=!1}={}){var le,oe,A;let d=e,p=new Headers,h=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{p.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let $=new URL(d,(0,F.getWindow)().location.href);$.searchParams.append("bytes",`${i.from}-${i.to}`),d=$.toString();break}default:(0,F.assertNever)(t)}this.requestQuic&&(d=Ii(d));let m=this.abortAllController.signal,b;if(n){let $=new ye;if(b=(0,F.merge)((0,F.fromEvent)(this.abortAllController.signal,"abort"),(0,F.fromEvent)(n,"abort")).subscribe(()=>{try{$.abort()}catch(k){(0,F.suppressAbort)(k)}}),this.subscription.add(b),this.abortAllController.signal.aborted||n.aborted)try{$.abort()}catch(k){(0,F.suppressAbort)(k)}m=$.signal}let S=0,v=(0,F.now)();h.log("startRequest",(0,F.flattenObject)({url:d,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:v})),this.trackRequestStart(d,performance.now()),this.firstBytesRequested$.next();let y=yield this.doFetch(d,{priority:a,headers:p,signal:m},{ignoreNetworkErrors:l}),x=(0,F.now)();if(!y)return h.error("error",{message:"No response in request"}),h.end(),this.unsubscribeAbortSubscription(b),null;if((le=this.throughputEstimator)==null||le.addRawRtt(x-v),!y.ok||!y.body){this.unsubscribeAbortSubscription(b);let $=`Fetch error ${y.status}: ${y.statusText}`;return h.error("error",{message:$}),h.end(),Promise.reject(new Error(`Fetch error ${y.status}: ${y.statusText}`))}if(this.onHeadersReceived(y.headers),!r&&!o){this.unsubscribeAbortSubscription(b);let $=(0,F.now)(),k={requestStartedAt:v,requestEndedAt:$,duration:$-v};return h.log("endRequest",(0,F.flattenObject)(k)),h.end(),y.arrayBuffer()}let w=y.body;if(o){let $;[w,$]=y.body.tee(),(oe=this.throughputEstimator)==null||oe.trackStream($,u)}let M=w.getReader(),_,q=parseInt((A=y.headers.get("content-length"))!=null?A:"",10);Number.isFinite(q)&&(_=q),!_&&i&&(_=i.to-i.from+1);let O=_?new Uint8Array(_):new Uint8Array(0),j=!1,V=$=>{this.unsubscribeAbortSubscription(b),j=!0,(0,F.suppressAbort)($)},Q=(0,F.abortable)(m,async function*({done:$,value:k}){if(S===0&&(this.lastRequestFirstBytes$.next((0,F.now)()-v),this.firstBytesReceived$.next()),m.aborted){this.unsubscribeAbortSubscription(b);return}if(!$&&k){if(c&&_)O.set(k,S),S+=k.byteLength;else{let R=new Uint8Array(O.length+k.length);R.set(O),R.set(k,O.length),O=R,S+=k.byteLength}r==null||r(new DataView(O.buffer),S),yield M==null?void 0:M.read().then(Q,V)}}.bind(this));yield M==null?void 0:M.read().then(Q,V),this.unsubscribeAbortSubscription(b);let U=(0,F.now)(),ie={failed:j,requestStartedAt:v,requestEndedAt:U,duration:U-v};if(j)return h.error("endRequest",(0,F.flattenObject)(ie)),h.end(),null;if(S>0){let $=U-v,R=S/($/1e3)*8/1024,Z={bytes:S,speed:R,url:e};this.lastDownloadMetrics$.next(Z)}return h.log("endRequest",(0,F.flattenObject)(ie)),h.end(),O.buffer}.bind(this));this.fetchByteRangeRepresentation=(0,F.abortable)(this.abortAllController.signal,async function*(e,t,i){var v;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,c,l;e.indexRange&&(c=e.indexRange.from,l=e.indexRange.to,u=a+1===c,u&&(n=Math.min(c,r),o=Math.max(l,a))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},measureThroughput:!1,...i});if(!d)return null;let p=new DataView(d,r-n,a-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=(v=e.indexRange)!=null?v:t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,m.from-n,m.to-m.from+1);else{let y=yield this.fetch(e.url,{range:m,measureThroughput:!1});if(!y)return null;b=new DataView(y)}let S=t.parseSegments(b,h,m);return{init:h,dataView:new DataView(d),segments:S}}.bind(this));this.fetchTemplateRepresentation=(0,F.abortable)(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,(0,F.getWindow)().PerformanceObserver&&this.setupPerformanceObserver()}onHeadersReceived(e){let{type:t,reused:i}=fo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}setupPerformanceObserver(){this.performanceObserver=new((0,F.getWindow)()).PerformanceObserver(e=>{e.getEntriesByType("resource").forEach(t=>{this.processPerformanceResourceTiming(t)})}),this.performanceObserver.observe({entryTypes:["resource"]})}processPerformanceResourceTiming(e){let t=this.findMatchingRequest(e);if(!t||!this.pendingConnectionMetrics.get(t))return;this.pendingConnectionMetrics.delete(t);let r=this.extractConnectionMetrics(e);r&&this.lastConnectionMetrics$.next(r)}estimateNetworkType(){if(!("connection"in(0,F.getWindow)().navigator))return"unknown";let e=(0,F.getWindow)().navigator.connection;return e.effectiveType?{"slow-2g":"2g","2g":"2g","3g":"3g","4g":"lte"}[e.effectiveType]||e.effectiveType:e.downlink?e.downlink<1?"2g":e.downlink<5?"3g":e.downlink<50?"lte":"wifi":e.rtt?e.rtt>500?"2g":e.rtt>250?"3g":e.rtt>50?"lte":"wifi":"unknown"}extractConnectionMetrics(e){let t=0,i=0,r=0,a=0;return e.domainLookupStart>0&&e.domainLookupEnd>0&&(t=e.domainLookupEnd-e.domainLookupStart),e.connectStart>0&&e.connectEnd>0&&(a=e.connectEnd-e.connectStart,e.secureConnectionStart>0?(r=e.connectEnd-e.secureConnectionStart,i=e.secureConnectionStart-e.connectStart):i=a),{dnsResolveTime:Math.max(0,t),tcpHandshakeTime:Math.max(0,i),tlsHandshakeTime:Math.max(0,r),totalConnectTime:Math.max(0,a),networkType:this.estimateNetworkType(),url:e.name}}findMatchingRequest(e){try{for(let[t,i]of this.pendingConnectionMetrics.entries()){let r=new URL(e.name),a=r.origin+r.pathname,n=new URL(i.url),o=n.origin+n.pathname;if(a===o&&e.startTime>=i.startTime-10&&e.startTime<=i.startTime+1e3)return t}}catch(t){this.recoverableError$.next({id:"VideoDataFetchError",message:"Video data fetch error with getting download metrics",category:F.ErrorCategory.WTF})}return null}trackRequestStart(e,t){let i=`${e}_${t}_${Math.random().toString(36).substr(2,9)}`;this.pendingConnectionMetrics.set(i,{url:e,startTime:t})}async fetchRepresentation(e,t,i){var a,n;let{type:r}=e;switch(r){case"byteRange":return(a=await this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:(0,F.assertNever)(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.performanceObserver&&(this.performanceObserver.disconnect(),this.performanceObserver=null),this.pendingConnectionMetrics.clear(),this.tracer.end()}async doFetch(e,t,i){let r=await vt(e,t);if(r.ok)return r;if(i!=null&&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:F.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:a});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:F.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:a});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:F.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:a});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:F.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:a});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${n})`,category:F.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:a})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}};var Oo=require("@vkontakte/videoplayer-shared/es2018");var Rs=class s{constructor(e,t){this.currentRepresentation$=new Oo.ValueSubject(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!(0,Oo.isNullable)(e))for(let i of this.representations)for(let r of i){let a=r.segmentReference,n=a.segments.length,o=a.segments[0].time.from,u=a.segments[n-1].time.to;if(e<o||e>u)continue;let c=a.segments.find(l=>l.time.from<=e&&l.time.to>=e);!c||((t=this.currentSegment)==null?void 0:t.time.from)===c.time.from&&this.currentSegment.time.to===c.time.to||(this.currentSegment=c,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(c.url,a.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?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!=null&&e.some(t=>s.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&dt(t.segmentReference))}};var Z$=["timeupdate","progress","play","seeked","stalled","waiting"],eL=["timeupdate","progress","loadeddata","playing","seeked"];var No=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new T.Subscription;this.subscriptionRemovable=new T.SubscriptionRemovable;this.representationSubscription=new T.Subscription;this.state$=new ae("none");this.currentVideoRepresentation$=new T.ValueSubject(void 0);this.currentVideoRepresentationInit$=new T.ValueSubject(void 0);this.currentAudioRepresentation$=new T.ValueSubject(void 0);this.currentVideoSegmentLength$=new T.ValueSubject(0);this.currentAudioSegmentLength$=new T.ValueSubject(0);this.error$=new T.Subject;this.manifestRequested$=new T.Subject;this.firstBytesManifest$=new T.Subject;this.manifestReceived$=new T.Subject;this.firstBytesRequested$=new T.Subject;this.firstBytesReceived$=new T.Subject;this.lastConnectionType$=new T.ValueSubject(void 0);this.lastConnectionReused$=new T.ValueSubject(void 0);this.lastRequestFirstBytes$=new T.ValueSubject(void 0);this.lastConnectionMetrics$=new T.ValueSubject(void 0);this.lastDownloadMetrics$=new T.ValueSubject(void 0);this.currentLiveTextRepresentation$=new T.ValueSubject(null);this.isLive$=new T.ValueSubject(!1);this.isActiveLive$=new T.ValueSubject(!1);this.isLowLatency$=new T.ValueSubject(!1);this.liveDuration$=new T.ValueSubject(0);this.liveSeekableDuration$=new T.ValueSubject(0);this.liveAvailabilityStartTime$=new T.ValueSubject(0);this.liveStreamStatus$=new T.ValueSubject(void 0);this.bufferLength$=new T.ValueSubject(0);this.liveLatency$=new T.ValueSubject(void 0);this.liveLoadBufferLength$=new T.ValueSubject(0);this.livePositionFromPlayer$=new T.ValueSubject(0);this.currentStallDuration$=new T.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new T.ValueSubject(0);this.fetcherRecoverableError$=new T.Subject;this.fetcherError$=new T.Subject;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new T.Subject;this.gapWatchdogActive=!1;this.liveWasInterrupted=!1;this.destroyController=new ye;this.initManifest=(0,T.abortable)(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Ae(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:T.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,T.abortable)(this.destroyController.signal,async function*(){var u,c;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(l=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:T.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:l})});if(!e)return null;let t=null;try{t=So(e!=null?e:"",this.manifestUrlString),this.manifestReceived$.next()}catch(l){let d=(u=ho(e))!=null?u:{id:"ManifestParsing",category:T.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:l};this.error$.next(d)}if(!t)return null;let i=(l,d,p)=>{var h,m,b,S;return!!((m=(h=this.element)==null?void 0:h.canPlayType)!=null&&m.call(h,d)&&((S=(b=ut())==null?void 0:b.isTypeSupported)!=null&&S.call(b,`${d}; codecs="${p}"`))||l==="text")};if(t.live){this.isLive$.next(!0);let{availabilityStartTime:l,latestSegmentPublishTime:d,streamIsUnpublished:p,streamIsAlive:h}=t.live,m=((c=t.duration)!=null?c:0)/1e3;this.liveSeekableDuration$.next(-1*m),this.liveDuration$.next((d-l)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let b="active";if(h||(b=p?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(b),h&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let S=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(S).catch(v=>{this.error$.next({id:"updateManifest",category:T.ErrorCategory.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:v})})}}let r={text:t.streams.text,video:[],audio:[]},a,n;for(let l of["video","audio"]){let p=t.streams[l].filter(({mime:m,codecs:b})=>i(l,m,b));r[l]=p;let h;if(this.tuning.dash.codecsPrioritizeEnabled){let m=p.map(({codecs:b})=>b);l==="audio"&&(n=wo(m),h=n[0]),l==="video"&&(a=Eo(m),this.forceVideoCodec&&(0,qy.default)(a,this.forceVideoCodec)?h=this.forceVideoCodec:h=a[0]),h&&(r[l]=p.filter(({codecs:b})=>Ei(b)===h))}else{let m=new Set(p.map(({codecs:b})=>b));h=Io(m),h&&(r[l]=p.filter(({codecs:b})=>b.startsWith(h)))}if(l==="video"){let m=this.tuning.preferHDR,b=r.video.some(y=>y.hdr),S=r.video.some(y=>!y.hdr);H.display.isHDR&&m&&b?r.video=r.video.filter(y=>y.hdr):S&&(r.video=r.video.filter(y=>!y.hdr));let{videoStreamRepresentaionsFilter:v}=this.tuning.dash;v.length&&Ao(r,v)}}let o={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:a,audio:n}),this.tracer.log("updateManifestEnd",(0,T.flattenObject)(o)),o}.bind(this));this.initRepresentations=(0,T.abortable)(this.destroyController.signal,async function*(e,t,i){var d;this.tracer.log("initRepresentationsStart",(0,T.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,T.assertNonNullable)(this.manifest),(0,T.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add((0,T.fromEvent)(p,"error").pipe((0,T.filter)(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=vn();let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),xr())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}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((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new As("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,T.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new As("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}if(Rs.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Rs(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,T.merge)(...eL.map(p=>(0,T.fromEvent)(this.element,p))).pipe((0,T.map)(p=>this.element?ki(this.element.buffered,this.element.currentTime*1e3):0),(0,T.filterChanged)(),(0,T.tap)(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&this.stopStallWatchdogSubscription()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,T.merge)((0,T.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{this.stopStallWatchdogSubscription()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,T.filterChanged)()).subscribe(h=>this.liveStreamEndTimestamp=(0,T.now)())),this.subscription.add((0,T.fromEvent)(this.element,"pause").subscribe(()=>{let{liveUpdateInterval:h}=this.tuning.dash;this.livePauseWatchdogSubscription=(0,T.interval)(h).subscribe(m=>{let b=pi(this.manifestUrlString,2);this.manifestUrlString=Ae(this.manifestUrlString,b+h,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add((0,T.fromEvent)(this.element,"play").subscribe(h=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add((0,T.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,T.map)(({isActiveLive:h,isLowLatency:m})=>h&&m),(0,T.filterChanged)()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Gr(this.element,1)})),this.representationSubscription.add((0,T.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,T.filter)(({bufferLength:h,isActiveLive:m,isLowLatency:b})=>m&&b&&!!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 m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add((0,T.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,T.filter)(({isLive:h})=>h),(0,T.filterChanged)((h,m)=>m.bufferLength<h.bufferLength),(0,T.map)(({rtt:h,bufferLength:m,segmentServerLatency:b})=>{let S=pi(this.manifestUrlString,2);return(h/2+m+b+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,T.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:b})=>{if(!b||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,x=h-S;if(this.isManualDecreasePlaybackInLive())return;let w=1;Math.abs(x)>v&&(w=1+Math.sign(x)*y),Gr(this.element,w)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,S;let m=0;if(h){let v=((S=(b=this.element)==null?void 0:b.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(x=>{var w,M;return(M=(w=x.getLiveSegmentsToLoadState(this.manifest))==null?void 0:w.to)!=null?M:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add((0,T.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,T.throttle)(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let b=this.element.playbackRate,S=pi(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),x=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,w=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,M=isFinite(h)?h:m,_=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),q=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(q);let O="none";if(_?O="active_low_latency":this.isLowLatency$.getValue()&&q?(this.bufferManagers.forEach(j=>j.proceedLowLatencyLive()),O="active_low_latency"):S!==0&&M<y?O="live_forward_buffering":M<y+w&&(O="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),O==="live_forward_buffering"||O==="live_with_target_offset"){let j=p-(y+x),V=this.normalizeLiveOffset(Math.trunc(S+j/b)),Q=Math.abs(V-S),U=0;!h||Q<=this.tuning.dashCmafLive.offsetCalculationError?U=S:V>0&&Q>this.tuning.dashCmafLive.offsetCalculationError&&(U=V),this.manifestUrlString=Ae(this.manifestUrlString,U,2)}(O==="live_with_target_offset"||O==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:T.ErrorCategory.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let u=(0,T.merge)(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe((0,T.map)(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=(0,T.merge)(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe((0,T.map)(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),l=(0,T.combine)({allBuffersFull:u,someBufferEnded:c}).pipe((0,T.filterChanged)(),(0,T.map)(({allBuffersFull:p,someBufferEnded:h})=>p&&h),(0,T.filter)(p=>p));if(this.representationSubscription.add((0,T.merge)(this.forceEnded$,l).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add((0,T.merge)(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var b;if(((b=this.source)==null?void 0:b.readyState)==="open"){h();return}this.error$.next({id:"OpenOfStream",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(m=this.source)==null||m.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(d=this.manifest.duration)!=null?d:0,...(0,Nl.default)((0,Nl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),dt(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&(0,T.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r,a;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(a=this.audioBufferManager)!=null&&a.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,T.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:T.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),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 _o({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.subscription.add(this.fetcher.lastConnectionMetrics$.subscribe(this.lastConnectionMetrics$)),this.subscription.add(this.fetcher.lastDownloadMetrics$.subscribe(this.lastDownloadMetrics$)),this.liveBuffer=ti.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){(0,T.assertNonNullable)(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"?(0,T.now)()-this.liveStreamEndTimestamp:0,i=this.normalizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Ae(this.manifestUrlString,i,2)}async updateLiveBuffersFromManifest(e){var t,i,r;await((t=this.videoBufferManager)==null?void 0:t.seekLive(e.streams.video)),await((i=this.audioBufferManager)==null?void 0:i.seekLive(e.streams.audio)),(r=this.liveTextManager)==null||r.seekLive(e.streams.text)}stopStallWatchdogSubscription(){var e;(e=this.stallWatchdogSubscription)==null||e.unsubscribe(),this.currentStallDuration$.next(0)}initBuffer(){(0,T.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,T.merge)(...Z$.map(e=>(0,T.fromEvent)(this.element,e)),(0,T.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:T.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,T.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,T.fromEvent)(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===2&&!this.element.seeking&&Ri(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var w,M,_,q,O,j,V,Q,U,ie,le;let{keepSilentStallWatchdogWhenNotActive:t}=this.tuning.dashCmafLive,{crashOnStallTimeout:i,crashOnStallTWithoutDataTimeout:r,liveStallReinitInterval:a,stallWatchdogInterval:n}=this.tuning.dash,o=this.isLive$.getValue(),c=this.liveStreamStatus$.getValue()==="active";if(!this.element||((w=this.source)==null?void 0:w.readyState)!=="open")return;let l=this.currentStallDuration$.getValue();l+=n,this.currentStallDuration$.next(l);let d={timeInWaiting:l},p=(0,T.now)(),h=100,m=(_=(M=this.videoBufferManager)==null?void 0:M.lastDataObtainedTimestamp)!=null?_:0;this.videoLastDataObtainedTimestamp$.next(m);let b=(O=(q=this.audioBufferManager)==null?void 0:q.lastDataObtainedTimestamp)!=null?O:0,S=(V=(j=this.videoBufferManager)==null?void 0:j.getForwardBufferDuration())!=null?V:0,v=(U=(Q=this.audioBufferManager)==null?void 0:Q.getForwardBufferDuration())!=null?U:0,y=S<h&&p-m>r,x=this.audioBufferManager&&v<h&&p-b>r;if((!t||c)&&((y||x)&&l>r||l>=i))throw new Error(`Stall timeout exceeded: ${l} ms`);if(o&&l%a===0){let oe=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);!c&&t?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(oe),this.updateManifest()):this.seekLive(oe).catch(A=>{this.error$.next({id:"stallIntervalCallback",category:T.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:A})}),d.liveLastOffset=oe}else{let oe=this.element.currentTime*1e3;(ie=this.videoBufferManager)==null||ie.maintain(oe),(le=this.audioBufferManager)==null||le.maintain(oe),d.position=oe}this.tracer.log("stallIntervalCallback",(0,T.flattenObject)(d))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=(0,T.interval)(this.tuning.dash.stallWatchdogInterval).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:T.ErrorCategory.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==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,a,n,o,u;(0,T.assertNonNullable)(this.element),(0,T.assertNonNullable)(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Ri(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!((0,T.isNullable)(this.element)||(0,T.isNullable)(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,T.flattenObject)({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;(0,T.isNonNullable)(this.element)&&(0,T.isNonNullable)(this.source)&&(0,T.isNonNullable)(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}getCodecs(){var e;return(e=this.manifest)==null?void 0:e.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,T.getTraceSubscriptionMethod)(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(){var e;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(t=>t.updateLive(this.manifest)),(e=this.liveTextManager)==null||e.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 c of u.gaps)(r&&c.persistent||u.playingRepresentation$.getValue()===c.representation)&&c.from-o<=a&&c.to+o>a&&(this.element.duration*1e3-c.to<this.tuning.endGapTolerance?n.push(1/0):n.push(c.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",(0,T.flattenObject)(i)))}}calculateDurationFromSegments(){var e,t;return Math.max(((e=this.videoBufferManager)==null?void 0:e.calculateDurationFromSegments())||0,((t=this.audioBufferManager)==null?void 0:t.calculateDurationFromSegments())||0)}};var at=require("@vkontakte/videoplayer-shared/es2018"),Fo=class{constructor(){this.subscription=new at.Subscription;this.pipSize$=new at.ValueSubject(void 0);this.videoSize$=new at.ValueSubject(void 0);this.elementSize$=new at.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=at.noop}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add((0,at.observeElementSize)(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((0,at.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,at.map)(({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 W.Subscription;this.videoState=new ae("stopped");this.observableVideo=null;this.droppedFramesManager=new Or;this.stallsManager=new uo;this.elementSizeManager=new Fo;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Si;this.audioTrackSwitchHistory=new Si;this.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==null?void 0: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"),B(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"),B(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&B(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==null?void 0:i.to)==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return(0,W.assertNever)(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new Nr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((a=e.projectionData)==null?void 0:a.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 mt(e.source.url),this.params=e,this.video=Je(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(We(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 No({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;(0,W.isNullable)(this.observableVideo)&&(this.observableVideo=tt(this.video),this.subscription.add(()=>{var n;return(n=this.observableVideo)==null?void 0:n.destroy()}));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:W.ErrorCategory.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((0,W.filter)(d=>!!d.length),(0,W.once)()).subscribe(d=>{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:d})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,W.map)(d=>d.to.state!=="none"),(0,W.filterChanged)());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.lastConnectionMetrics$,e.httpConnectionMetrics$),a(this.player.lastDownloadMetrics$,e.httpDownloadMetrics$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe((0,W.filter)(W.isNonNullable),(0,W.once)()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe((0,W.map)(d=>d.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(Ft(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),Ti({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(et(this.video,t.volume,i.volumeState$,r)),this.subscription.add(ft(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(gt(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&!this.video.ended&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")})),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let p=this.player.getStreams(),h=this.player.getCodecs();if((0,W.assertNonNullable)(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let b=[];for(let S of p.audio){b.push($l(S));let v=[];for(let y of S.representations){let x=Is(y);v.push(x),this.audioTracksMap.set(x,{stream:S,representation:y})}this.audioStreamsMap.set(S,v)}this.params.output.availableAudioStreams$.next(b)}let m=[];for(let b of p.video){m.push(Ll(b));let S=[];for(let v of b.representations){let y=xi({...v,streamId:b.id});y&&(S.push(y),this.videoTracksMap.set(y,{stream:b,representation:v}))}this.videoStreamsMap.set(b,S)}this.params.output.availableVideoStreams$.next(m);for(let b of p.text)for(let S of b.representations){let v=Ry(b,S);this.textTracksMap.set(v,{stream:b,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!=null&&h.video&&this.params.output.availableVideoCodecs$.next(h.video),h!=null&&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 d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let o=(0,W.merge)(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$,(0,W.fromEvent)(this.video,"progress")).pipe((0,W.filter)(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe((0,W.throttle)(u))),this.subscription.add(o.subscribe(async()=>{let d=this.player.state$.getState(),p=this.player.state$.getTransition();if(d!=="manifest_ready"&&d!=="running"||p)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[m,b]=h,S=[...this.videoTracksMap.keys()].find(y=>{var x;return((x=this.videoTracksMap.get(y))==null?void 0:x.representation.id)===m.id});(0,W.isNonNullable)(S)&&(this.stallsManager.lastVideoTrackSelected=S);let v=this.params.desiredState.autoVideoTrackLimits.getTransition();if(v&&this.params.output.autoVideoTrackLimits$.next(v.to),d==="manifest_ready")await this.player.initRepresentations(m.id,b==null?void 0:b.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",m.id),b){let y=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",b.id,y)}},r)),this.subscription.add((0,W.combine)({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:(0,W.merge)((0,W.observableFrom)([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,W.map)(d=>d.to)))}).pipe((0,W.map)(({videoState:d,autoVideoTrackState:p})=>d.to!=="stopped"&&p),(0,W.filterChanged)()).subscribe(d=>this.player.setSmartRepresentationSwitch(d))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSizeManager.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,W.filterChanged)()).subscribe(d=>{let p=[...this.videoTracksMap.entries()].find(([,{representation:v}])=>v.id===d);if(!p){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:m}]=p,b=this.params.desiredState.videoStream.getTransition();b&&b.to&&b.to.id===m.id&&this.params.desiredState.videoStream.setState(b.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Ll(m));let S=this.player.calculateDurationFromSegments();S&&this.params.output.duration$.next(S/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,W.filterChanged)()).subscribe(d=>{let p=[...this.audioTracksMap.entries()].find(([,{representation:S}])=>S.id===d);if(!p){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=p,b=this.params.desiredState.audioStream.getTransition();b&&b.to&&b.to.id===m.id&&this.params.desiredState.audioStream.setState(b.to),e.currentAudioStream$.next($l(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var p,h;if(d!=null&&d.is3dVideo&&((p=this.params.tuning.spherical)!=null&&p.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(m){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${m}`})}else this.destroy3DScene(),(h=this.params.tuning.spherical)!=null&&h.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 c=t.playbackState.stateChangeStarted$.pipe((0,W.map)(({to:d})=>d==="ready"),(0,W.filterChanged)());this.subscription.add((0,W.merge)(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,W.observableFrom)(["init"])).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add((0,W.merge)(c,this.player.state$.stateChangeEnded$,(0,W.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=(0,W.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,W.observableFrom)(["init"])).pipe((0,W.debounce)(0));this.subscription.add(l.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var O,j,V,Q,U,ie,le,oe,A,$,k,R,Z;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Oa:_a,t=this.params.tuning.useNewAutoSelectVideoTrack?io:to,i=this.params.tuning.useNewAutoSelectVideoTrack?Ut:eo,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(O=r.videoTrack.getState())==null?void 0:O.id,u=[...this.videoTracksMap.keys()].find(({id:K})=>K===o),c=a.currentVideoTrack$.getValue(),l=((Q=(V=r.videoStream.getState())!=null?V:u&&((j=this.videoTracksMap.get(u))==null?void 0:j.stream))!=null?Q:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!l)return;let d=[...this.videoStreamsMap.keys()].find(({id:K})=>K===l.id),p=d&&this.videoStreamsMap.get(d);if(!p)return;let h=ki(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let b=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(m,b||1/0),1),v=(U=r.audioStream.getState())!=null?U:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,y=(ie=[...this.audioStreamsMap.keys()].find(({id:K})=>K===(v==null?void 0:v.id)))!=null?ie:this.audioStreamsMap.keys().next().value,x=0;if(y){if(u&&!n){let K=e(u,p,(le=this.audioStreamsMap.get(y))!=null?le:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,(oe=K==null?void 0:K.bitrate)!=null?oe:-1/0)}if(c){let K=e(c,p,(A=this.audioStreamsMap.get(y))!=null?A:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,($=K==null?void 0:K.bitrate)!=null?$:-1/0)}}let w=u;(n||!w)&&(w=i(p,{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:x,forwardBufferHealth:S,current:c,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 M=y&&t(w,p,(k=this.audioStreamsMap.get(y))!=null?k:[],{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}),_=(R=this.videoTracksMap.get(w))==null?void 0:R.representation,q=M&&((Z=this.audioTracksMap.get(M))==null?void 0:Z.representation);if(_&&q)return[_,q];if(_&&!q&&this.audioTracksMap.size===0)return[_,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){it(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:W.ErrorCategory.DOM,thrown:e}))}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),Ze(this.video,this.params.tuning.keepVideoElement,this.params.tuning.clearVideoElementInnerHTML),this.tracer.end()}};var Ms=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)}};var ge=require("@vkontakte/videoplayer-shared/es2018");var $s=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 ge.ValueSubject(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe((0,ge.filterChanged)()).subscribe(u=>{let c=i.position$.getValue(),l=i.volume$.getValue(),d=!l.volume||l.muted;!u&&!c&&d?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((0,ge.map)(u=>u.to)).subscribe(this.player.isLowLatency$)).add((0,ge.combine)({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,ge.map)(({liveBufferTime:u,liveAvailabilityStartTime:c})=>u&&c?u*1e3+c+t:void 0)).subscribe(i.liveTime$)).add((0,ge.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,ge.merge)(r.playbackRateState$,new ge.ValueSubject(1))}).pipe((0,ge.filter)(({liveStreamStatus:u,liveDuration:c})=>u==="active"&&!!c)).subscribe(({liveDuration:u,playbackRate:c})=>{let l=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;d||c<1-p||this.video.paused||(0,ge.isNullable)(l)||(t=u-l)})).add((0,ge.combine)({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,ge.merge)(r.playbackRateState$,new ge.ValueSubject(1))}).pipe((0,ge.filterChanged)((u,c)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===c.liveDuration:u.time===c.time)).subscribe(({time:u,liveDuration:c,playbackRate:l})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&l>=1-p||(0,ge.isNullable)(u)||(0,ge.isNullable)(c))return;let h=-1*(c-u-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let c=My(u);this.params.output.availableTextTracks$.next([c])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe((0,ge.filter)(u=>(0,ge.isNonNullable)(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)})}};var Hy="X-Playback-Duration",Fl=async s=>{var r;let e=await vt(s),t=await e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(Hy)?parseInt(e.headers.get(Hy),10):void 0};var ne=require("@vkontakte/videoplayer-shared/es2018");var ql=G(sc(),1);var Uo=require("@vkontakte/videoplayer-shared/es2018");var iL=s=>{let e=null;if(s.QUALITY&&(e=vi(s.QUALITY)),!e&&s.RESOLUTION){let[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=(0,Uo.videoSizeToQuality)({width:t,height:i})}return e!=null?e:null},rL=(s,e)=>{var a,n;let t=s.split(`
179
179
  `),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],c=u.match(/^#EXT-X-STREAM-INF:(.+)/),l=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!c&&!l)){if(c){let d=(0,ql.default)(c[1].split(",").map(y=>y.split("="))),p=(a=d.QUALITY)!=null?a:`stream-${d.BANDWIDTH}`,h=iL(d),m;d.BANDWIDTH&&(m=parseInt(d.BANDWIDTH,10)/1e3||void 0),!m&&d["AVERAGE-BANDWIDTH"]&&(m=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,S;if(d.RESOLUTION){let[y,x]=d.RESOLUTION.split("x").map(w=>parseInt(w,10));y&&x&&(S={width:y,height:x})}let v=new URL(t[++o],e).toString();h&&i.push({id:p,quality:h,url:v,bandwidth:m,size:S,fps:b})}if(l){let d=(0,ql.default)(l[1].split(",").map(b=>{let S=b.indexOf("=");return[b.substring(0,S),b.substring(S+1)]}).map(([b,S])=>[b,S.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=d.LANGUAGE,m=d.NAME;p&&h&&r.push({type:"internal",id:h,label:m,language:h,url:p,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},aL=s=>new Promise(e=>{setTimeout(()=>{e()},s)}),Ul=0,jy=async(s,e=s,t,i)=>{let a=await(await vt(s,i)).text();Ul+=1;try{let{qualityManifests:n,textTracks:o}=rL(a,e);return{qualityManifests:n,textTracks:o}}catch(n){if(Ul<=t.manifestRetryMaxCount)return await aL((0,Uo.getExponentialDelay)(Ul-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),jy(s,e,t)}return{qualityManifests:[],textTracks:[]}},qo=jy;var pt=require("@vkontakte/videoplayer-shared/es2018");var Ho=class{constructor(e,t,i,r,a){this.subscription=new pt.Subscription;this.abortControllers={destroy:new ye,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new pt.ValueSubject(null);this.getCurrentTime$=new pt.ValueSubject(null);this.error$=new pt.Subject;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:a},this.subscription.add(e.pipe((0,pt.throttle)(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 vt(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],c=new URL(u,t).toString(),l=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:a,to:a+l},url:c}),a=a+l,!i.segmentStartTime){let d=new Date(i.vkStartTime).valueOf(),p=new Date(i.programDateTime).valueOf();i.segmentStartTime=p-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let c=new Date(u);c.setMilliseconds(0),a=c.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if((0,pt.isNonNullable)(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 ye;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(){var t;let e=(t=this.prepareUrl)!=null?t: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:pt.ErrorCategory.WTF,thrown:t,message:e})}};var Ls=class{constructor(e){this.subscription=new ne.Subscription;this.videoState=new ae("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new ne.ValueSubject([]);this.liveOffset=new Xi;this.manifestStartTime$=new ne.ValueSubject(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"),B(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let c=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let l=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(l),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&c.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(c.position&&c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?B(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),B(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==null?void 0:r.to)==="playing"&&B(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 l=this.liveOffset.getTotalOffset();l>=this.maxSeekBackTime$.getValue()&&(l=0,this.liveOffset.resetTo(l)),this.liveOffset.resume(),this.params.output.position$.next(-l/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&(B(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,ne.assertNever)(t)}};var i;this.params=e,this.video=Je(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ne.VideoQuality.INVARIANT,url:this.params.source.url};let t=(r,a)=>qo(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},a);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new Ho(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new mt(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:a})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:ne.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(a,this.params.source.url),this.manifests$.next([this.masterManifest,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:ne.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})}),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(We(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new ne.ValueSubject((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,c,l,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(d=(l=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?l:(c=t.getState())==null?void 0:c.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:ne.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=tt(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(et(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ft(this.video,t.playbackRate,r.playbackRateState$,i)),a(gt(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"),B(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe((0,ne.filterChanged)(),(0,ne.map)(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(),c=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&(0,ne.isNonNullable)(c.to)){let d=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(We(p.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.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(()=>{var u,c,l;let o=(l=(c=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:c.call(u))==null?void 0:l.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add((0,ne.combine)({startTime:this.manifestStartTime$.pipe((0,ne.filter)(ne.isNonNullable)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe((0,ne.map)(o=>o.map(({id:u,quality:c,size:l,bandwidth:d,fps:p})=>({id:u,quality:c,size:l,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let n=(0,ne.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,ne.observableFrom)(["init"])).pipe((0,ne.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),Ze(this.video,this.params.tuning.keepVideoElement,this.params.tuning.clearVideoElementInnerHTML)}prepare(){var o,u,c;let e=this.selectManifest();if((0,ne.isNullable)(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:l,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[p,h]of[[l,"mq"],[d,"lq"]]){let m=String(parseFloat(p||""));h&&p&&r.searchParams.set(h,m)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,n=Ae(r.toString(),this.liveOffset.getTotalOffset(),a);(c=this.liveTextManager)==null||c.prepare(n),this.video.setAttribute("src",n),this.video.load(),Fl(n).then(l=>{var d;if(!(0,ne.isNullable)(l))this.maxSeekBackTime$.next(l);else{let p=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();((0,ne.isNullable)(p)||!isFinite(p))&&vt(n).then(h=>h.text()).then(h=>{var b;let m=(b=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:b[1];if(m){let S=new URL(m,n).toString();Fl(S).then(v=>{(0,ne.isNullable)(v)||this.maxSeekBackTime$.next(v)})}}).catch(()=>{})}})}playIfAllowed(){it(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ne.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=Ae(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};var de=require("@vkontakte/videoplayer-shared/es2018");var Cs=class{constructor(e){this.subscription=new de.Subscription;this.videoState=new ae("stopped");this.manifests$=new de.ValueSubject([]);this.unmuteAfterBrowserResetsHappened=new de.ValueSubject(!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"),B(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let c=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let l=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(l);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&c.state==="requested"&&this.seek(c.position),t){case"ready":i==="ready"?B(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),B(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==null?void 0:r.to)==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&B(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,de.assertNever)(t)}};this.textTracksManager=new mt(e.source.url),this.params=e,this.video=Je(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:de.VideoQuality.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(We(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),qo(Ae(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:de.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,c,l,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(d=(l=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?l:(c=t.getState())==null?void 0:c.id)!=null?d:"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(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:de.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},r=tt(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((0,de.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ft(this.video,t.isLooped,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ft(this.video,t.playbackRate,r.playbackRateState$,i)),Ti({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(et(this.video,t.volume,r.volumeState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var h;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&(0,de.isNonNullable)(c.to)){let m=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let b=this.manifests$.getValue().find(S=>S.id===m);b&&(this.params.output.currentVideoTrack$.next(b),this.params.output.hostname$.next(We(b.url)))}let d=this.params.desiredState.playbackRate.getState(),p=(h=this.params.output.element$.getValue())==null?void 0:h.playbackRate;if(d!==p){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(d),m.playbackRate=d)}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.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"),B(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe((0,de.map)(o=>o.map(({id:u,quality:c,size:l,bandwidth:d,fps:p})=>({id:u,quality:c,size:l,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!H.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,de.merge)((0,de.fromEvent)(o,"addtrack"),(0,de.fromEvent)(o,"removetrack"),(0,de.fromEvent)(o,"change"),(0,de.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=(0,de.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,de.observableFrom)(["init"])).pipe((0,de.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ze(this.video,this.params.tuning.keepVideoElement,this.params.tuning.clearVideoElementInnerHTML)}prepare(){var a,n;let e=this.selectManifest();if((0,de.isNullable)(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}=(n=(a=t==null?void 0:t.to)!=null?a:i)!=null?n:{};for(let[c,l]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(c||""));l&&c&&r.searchParams.set(l,d)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){it(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:de.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var Wy=G(mi(),1),Hl=G(ji(),1),Qy=G(bt(),1);var Ee=require("@vkontakte/videoplayer-shared/es2018");var Ds=class{constructor(e){this.subscription=new Ee.Subscription;this.videoState=new ae("stopped");this.trackUrls={};this.textTracksManager=new mt;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"),B(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==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?B(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),B(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==null?void 0:i.to)==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return(0,Ee.assertNever)(e)}};this.params=e,this.video=Je(e.container,e.tuning),this.params.output.element$.next(this.video),(0,Wy.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,Hl.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:Ee.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},r=tt(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((0,Ee.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ft(this.video,t.isLooped,i)),Ti({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(et(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ft(this.video,t.playbackRate,r.playbackRateState$,i)),a(gt(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,c;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&(0,Ee.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let l=this.params.desiredState.playbackRate.getState(),d=(c=this.params.output.element$.getValue())==null?void 0:c.playbackRate;if(l!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(l),p.playbackRate=l)}}this.videoState.getState()==="playing"&&!this.video.ended&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let n=(0,Ee.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,Ee.observableFrom)(["init"])).pipe((0,Ee.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Ze(this.video,this.params.tuning.keepVideoElement,this.params.tuning.clearVideoElementInnerHTML)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;(0,Ee.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,Ee.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ii(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(We(t))}playIfAllowed(){it(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ee.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var c,l;this.params.output.autoVideoTrackLimits$.next(e);let t=d=>{this.params.output.currentVideoTrack$.next(d),this.params.desiredState.videoTrack.startTransitionTo(d)},i=d=>{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:d,abrLogger:this.params.dependencies.abrLogger});t(p)},r=(c=this.params.output.currentVideoTrack$.getValue())==null?void 0:c.quality,a=!!(e.max||e.min),n=(0,Hl.default)(this.trackUrls).map(d=>d.track);if(!r||!a||Br(e,n[0].quality,(l=(0,Qy.default)(n,-1))==null?void 0:l.quality)){i();return}let o=e.max?(0,Ee.isLowerOrEqual)(r,e.max):!0,u=e.min?(0,Ee.isHigherOrEqual)(r,e.min):!0;o&&u||i(e)}};var we=require("@vkontakte/videoplayer-shared/es2018");var Gy=require("@vkontakte/videoplayer-shared/es2018"),zy=["stun:videostun.mycdn.me:80"],sL=1e3,nL=3,jl=()=>null,jo=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=jl;this.externalStopCallback=jl;this.externalErrorCallback=jl;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:zy}]};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:Gy.ErrorCategory.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){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),sL)}normalizeOptions(e={}){let t={stunServerList:zy,maxRetryNumber:nL,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Bs=class{constructor(e){this.videoState=new ae("stopped");this.maxSeekBackTime$=new we.ValueSubject(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),B(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"),B(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==null?void 0:i.to)==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return(0,we.assertNever)(e)}};this.subscription=new we.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Je(e.container,e.tuning),this.liveStreamClient=new jo(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),Ze(this.video,this.params.tuning.keepVideoElement,this.params.tuning.clearVideoElementInnerHTML)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:we.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add((0,we.merge)(this.videoState.stateChangeStarted$.pipe((0,we.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,we.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=tt(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(gt(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(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.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(et(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(0,we.assertNever)(n.to)}},i)).add((0,we.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,we.observableFrom)(["init"])).pipe((0,we.debounce)(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(We(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:we.VideoQuality.INVARIANT}),this.video.srcObject=e,B(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:we.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){it(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:we.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Kr=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}};var E=require("@vkontakte/videoplayer-shared/es2018");var ii=require("@vkontakte/videoplayer-shared/es2018");var Yy=s=>new ii.Observable(e=>{let t=new ii.Subscription,i=s.desiredPlaybackState$.stateChangeStarted$.pipe((0,ii.map)(({from:c,to:l})=>`${c}-${l}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe((0,ii.map)(({type:c})=>c!==void 0)),n=new ii.Subject,o=0,u="unknown";return t.add(i.subscribe(c=>{o&&window.clearTimeout(o),u=c,o=window.setTimeout(()=>n.next(c),s.maxTransitionInterval),X({m:"hangup.set",l:c,id:o})})),t.add(r.subscribe(()=>{X({m:"hangup.cl",id:o}),window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(c=>{o&&(X({m:"hangup.rs.0",id:o}),window.clearTimeout(o),o=0,c&&(o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval),X({m:"hangup.rs.1",id:o})))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var yt=require("@vkontakte/videoplayer-shared/es2018");function Ky(){return new(window.AudioContext||window.webkitAudioContext)}var Vs=class Vs{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new ye;this.subscriptions=new yt.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,yt.filter)(a=>!!a.type),(0,yt.once)()).subscribe(({type:a})=>this.subscribe(a)))}subscribe(e){H.browser.isSafari&&e!=="MPEG"||this.subscriptions.add((0,yt.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,yt.filter)(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),(0,yt.once)()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,i=Ky();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){var t;this.volumeMultiplierError$.next({id:Vs.errorId,category:yt.ErrorCategory.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Vs.errorId} exception`,thrown:e})}};Vs.errorId="VolumeMultiplierManager";var Xr=Vs;var oL={chunkDuration:5e3,maxParallelRequests:5},_s=class{constructor(e){this.current$=new E.ValueSubject({type:void 0});this.providerError$=new E.Subject;this.noAvailableProvidersError$=new E.Subject;this.volumeMultiplierError$=new E.Subject;this.providerOutput={position$:new E.ValueSubject(0),duration$:new E.ValueSubject(1/0),volume$:new E.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new E.ValueSubject([]),currentVideoStream$:new E.ValueSubject(void 0),availableVideoTracks$:new E.ValueSubject([]),currentVideoTrack$:new E.ValueSubject(void 0),availableVideoCodecs$:new E.ValueSubject([]),availableAudioStreams$:new E.ValueSubject([]),currentAudioStream$:new E.ValueSubject(void 0),availableAudioTracks$:new E.ValueSubject([]),availableAudioCodecs$:new E.ValueSubject([]),currentVideoSegmentLength$:new E.ValueSubject(0),currentAudioSegmentLength$:new E.ValueSubject(0),isAudioAvailable$:new E.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new E.ValueSubject(!1),autoVideoTrackLimits$:new E.ValueSubject(void 0),currentBuffer$:new E.ValueSubject(void 0),currentNativeBuffer$:new E.ValueSubject(void 0),isBuffering$:new E.ValueSubject(!0),error$:new E.Subject,fetcherError$:new E.Subject,fetcherRecoverableError$:new E.Subject,warning$:new E.Subject,willSeekEvent$:new E.Subject,soundProhibitedEvent$:new E.Subject,seekedEvent$:new E.Subject,loopedEvent$:new E.Subject,endedEvent$:new E.Subject,manifestRequested$:new E.Subject,firstBytesManifest$:new E.Subject,manifestReceived$:new E.Subject,firstBytesRequested$:new E.Subject,firstBytesReceived$:new E.Subject,firstBytesEvent$:new E.Subject,loadedMetadataEvent$:new E.Subject,firstFrameEvent$:new E.Subject,canplay$:new E.Subject,isLive$:new E.ValueSubject(void 0),isLiveEnded$:new E.ValueSubject(null),canPlayLiveTailBuffer$:new E.ValueSubject(!1),isLowLatency$:new E.ValueSubject(!1),canChangePlaybackSpeed$:new E.ValueSubject(!0),liveTime$:new E.ValueSubject(void 0),liveBufferTime$:new E.ValueSubject(void 0),liveLatency$:new E.ValueSubject(void 0),severeStallOccurred$:new E.Subject,availableTextTracks$:new E.ValueSubject([]),currentTextTrack$:new E.ValueSubject(void 0),hostname$:new E.ValueSubject(void 0),httpConnectionType$:new E.ValueSubject(void 0),httpConnectionReused$:new E.ValueSubject(void 0),httpConnectionMetrics$:new E.ValueSubject(void 0),httpDownloadMetrics$:new E.ValueSubject(void 0),inPiP$:new E.ValueSubject(!1),inFullscreen$:new E.ValueSubject(!1),element$:new E.ValueSubject(void 0),elementVisible$:new E.ValueSubject(!0),availableSources$:new E.ValueSubject(void 0),is3DVideo$:new E.ValueSubject(!1),playbackState$:new E.ValueSubject(""),getCurrentTime$:new E.ValueSubject(null)};this.subscription=new E.Subscription;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=_u([...by(this.params.tuning),...my(this.params.tuning)]).filter(c=>(0,E.isNonNullable)(e.sources[c])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(c=>!(0,Wl.default)(r,c)),...t.filter(c=>(0,Wl.default)(r,c))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",(0,E.flattenObject)(a)),this.screenFormatsIterator=new Kr(a);let n=[...Rl(!0),...Rl(!1)];this.chromecastFormatsIterator=new Kr(n.filter(c=>(0,E.isNonNullable)(e.sources[c]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Xr.isSupported()&&(this.volumeMultiplierManager=new Xr(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){X.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 Kr(e))}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,E.isNullable)(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:E.ErrorCategory.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(0,E.assertNever)(e)}}createScreenProvider(e){var u,c;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 l=this.applyFailoverHost(t[e]),d=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);(0,E.assertNonNullable)(l);let{useDashProviderVirtual:p,useDashProviderVirtualMobile:h}=this.params.tuning,{isMobile:m}=H.device;return!m&&p||m&&h?new xs({...o,source:l,sourceHls:d,forceVideoCodec:(u=this.videoCodecsIterator)==null?void 0:u.getValue()}):new Ms({...o,source:l,sourceHls:d,forceVideoCodec:(c=this.videoCodecsIterator)==null?void 0:c.getValue()})}case"DASH_LIVE_CMAF":{let l=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(l),this.params.tuning.useDashProviderVirtual&&!H.device.isMobile?new Yr({...o,source:l}):this.params.tuning.useDashProviderVirtualMobile&&H.device.isMobile?new Yr({...o,source:l}):new $s({...o,source:l})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let l=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(l),new Cs({...o,source:l})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(l),new Ls({...o,source:l,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let l=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(l),new Ds({...o,source:l})}case"DASH_LIVE":{let l=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(l),new wv({...o,source:l,config:{...oL,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let l=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(l),new Bs({container:i,source:l,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(0,E.assertNever)(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 Gt){let{chromecastConnector:c}=this.params.dependencies.chromecastInitializer;return(0,E.assertNonNullable)(c),new Sa({...o,chromecastConnector:c})}let u=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,E.assertNonNullable)(u),new Ca({...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(0,E.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,E.assertNever)(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return(0,E.assertNever)(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,Xy.default)((0,Ql.default)(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new E.Subscription,t=!1,i=0;e.add((0,E.merge)(this.providerOutput.error$.pipe((0,E.filter)(a=>!this.params.tuning.ignoreAudioRendererError||!a.message||!/AUDIO_RENDERER_ERROR/ig.test(a.message))),Yy({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,E.map)(a=>({id:`ProviderHangup:${a}`,category:E.ErrorCategory.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((0,E.filter)(({to:n})=>n==="playing"),(0,E.once)()).subscribe(()=>t=!0);e.add(a)}));let r=()=>{let a=X.drain(),{logDashLiveDebug:n,sendDashLiveDebug:o}=this.params.tuning;if(n&&(0,E.getWindow)().console.log(`===== DASH_LIVE DEBUG START ====
181
181
  `,a.map(({time:u,data:c,stack:l})=>`${u}: ${JSON.stringify(c)}${l?`