@vkontakte/videoplayer-core 2.0.151-dev.6dd94264.0 → 2.0.151-dev.96546ef5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/es2018.cjs CHANGED
@@ -1,10 +1,10 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.151-dev.6dd94264.0
3
- * Mon, 02 Feb 2026 12:05:46 GMT
2
+ * @vkontakte/videoplayer-core v2.0.151-dev.96546ef5.0
3
+ * Mon, 02 Feb 2026 13:51:44 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-151/doc/
5
5
  */
6
6
  "use strict";var dT=Object.create;var Ws=Object.defineProperty;var pT=Object.getOwnPropertyDescriptor;var hT=Object.getOwnPropertyNames;var fT=Object.getPrototypeOf,mT=Object.prototype.hasOwnProperty;var g=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),bT=(a,e)=>{for(var t in e)Ws(a,t,{get:e[t],enumerable:!0})},Md=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of hT(e))!mT.call(a,r)&&r!==t&&Ws(a,r,{get:()=>e[r],enumerable:!(i=pT(e,r))||i.enumerable});return a};var G=(a,e,t)=>(t=a!=null?dT(fT(a)):{},Md(e||!a||!a.__esModule?Ws(t,"default",{value:a,enumerable:!0}):t,a)),gT=a=>Md(Ws({},"__esModule",{value:!0}),a);var we=g((zo,$d)=>{"use strict";var Zr=function(a){return a&&a.Math===Math&&a};$d.exports=Zr(typeof globalThis=="object"&&globalThis)||Zr(typeof window=="object"&&window)||Zr(typeof self=="object"&&self)||Zr(typeof global=="object"&&global)||Zr(typeof zo=="object"&&zo)||function(){return this}()||Function("return this")()});var Me=g((dC,Cd)=>{"use strict";Cd.exports=function(a){try{return!!a()}catch(e){return!0}}});var ea=g((pC,Dd)=>{"use strict";var vT=Me();Dd.exports=!vT(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Go=g((hC,_d)=>{"use strict";var ST=ea(),Vd=Function.prototype,Ld=Vd.apply,Bd=Vd.call;_d.exports=typeof Reflect=="object"&&Reflect.apply||(ST?Bd.bind(Ld):function(){return Bd.apply(Ld,arguments)})});var $e=g((fC,Fd)=>{"use strict";var Od=ea(),Nd=Function.prototype,Yo=Nd.call,yT=Od&&Nd.bind.bind(Yo,Yo);Fd.exports=Od?yT:function(a){return function(){return Yo.apply(a,arguments)}}});var Li=g((mC,Ud)=>{"use strict";var qd=$e(),TT=qd({}.toString),IT=qd("".slice);Ud.exports=function(a){return IT(TT(a),8,-1)}});var Ko=g((bC,jd)=>{"use strict";var ET=Li(),wT=$e();jd.exports=function(a){if(ET(a)==="Function")return wT(a)}});var xe=g((gC,Hd)=>{"use strict";var Xo=typeof document=="object"&&document.all;Hd.exports=typeof Xo=="undefined"&&Xo!==void 0?function(a){return typeof a=="function"||a===Xo}:function(a){return typeof a=="function"}});var at=g((vC,Qd)=>{"use strict";var xT=Me();Qd.exports=!xT(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var st=g((SC,Wd)=>{"use strict";var PT=ea(),Ys=Function.prototype.call;Wd.exports=PT?Ys.bind(Ys):function(){return Ys.apply(Ys,arguments)}});var Jo=g(Yd=>{"use strict";var zd={}.propertyIsEnumerable,Gd=Object.getOwnPropertyDescriptor,kT=Gd&&!zd.call({1:2},1);Yd.f=kT?function(e){var t=Gd(this,e);return!!t&&t.enumerable}:zd});var ta=g((TC,Kd)=>{"use strict";Kd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Jd=g((IC,Xd)=>{"use strict";var AT=$e(),RT=Me(),MT=Li(),Zo=Object,$T=AT("".split);Xd.exports=RT(function(){return!Zo("z").propertyIsEnumerable(0)})?function(a){return MT(a)==="String"?$T(a,""):Zo(a)}:Zo});var ia=g((EC,Zd)=>{"use strict";Zd.exports=function(a){return a==null}});var ui=g((wC,ep)=>{"use strict";var CT=ia(),DT=TypeError;ep.exports=function(a){if(CT(a))throw new DT("Can't call method on "+a);return a}});var Bi=g((xC,tp)=>{"use strict";var LT=Jd(),BT=ui();tp.exports=function(a){return LT(BT(a))}});var Ge=g((PC,ip)=>{"use strict";var VT=xe();ip.exports=function(a){return typeof a=="object"?a!==null:VT(a)}});var Vi=g((kC,rp)=>{"use strict";rp.exports={}});var Qt=g((AC,sp)=>{"use strict";var eu=Vi(),tu=we(),_T=xe(),ap=function(a){return _T(a)?a:void 0};sp.exports=function(a,e){return arguments.length<2?ap(eu[a])||ap(tu[a]):eu[a]&&eu[a][e]||tu[a]&&tu[a][e]}});var ra=g((RC,np)=>{"use strict";var OT=$e();np.exports=OT({}.isPrototypeOf)});var _i=g((MC,cp)=>{"use strict";var NT=we(),op=NT.navigator,up=op&&op.userAgent;cp.exports=up?String(up):""});var ru=g(($C,mp)=>{"use strict";var fp=we(),iu=_i(),lp=fp.process,dp=fp.Deno,pp=lp&&lp.versions||dp&&dp.version,hp=pp&&pp.v8,Tt,Ks;hp&&(Tt=hp.split("."),Ks=Tt[0]>0&&Tt[0]<4?1:+(Tt[0]+Tt[1]));!Ks&&iu&&(Tt=iu.match(/Edge\/(\d+)/),(!Tt||Tt[1]>=74)&&(Tt=iu.match(/Chrome\/(\d+)/),Tt&&(Ks=+Tt[1])));mp.exports=Ks});var au=g((CC,gp)=>{"use strict";var bp=ru(),FT=Me(),qT=we(),UT=qT.String;gp.exports=!!Object.getOwnPropertySymbols&&!FT(function(){var a=Symbol("symbol detection");return!UT(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&bp&&bp<41})});var su=g((DC,vp)=>{"use strict";var jT=au();vp.exports=jT&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var nu=g((LC,Sp)=>{"use strict";var HT=Qt(),QT=xe(),WT=ra(),zT=su(),GT=Object;Sp.exports=zT?function(a){return typeof a=="symbol"}:function(a){var e=HT("Symbol");return QT(e)&&WT(e.prototype,GT(a))}});var aa=g((BC,yp)=>{"use strict";var YT=String;yp.exports=function(a){try{return YT(a)}catch(e){return"Object"}}});var Dt=g((VC,Tp)=>{"use strict";var KT=xe(),XT=aa(),JT=TypeError;Tp.exports=function(a){if(KT(a))return a;throw new JT(XT(a)+" is not a function")}});var sa=g((_C,Ip)=>{"use strict";var ZT=Dt(),eI=ia();Ip.exports=function(a,e){var t=a[e];return eI(t)?void 0:ZT(t)}});var wp=g((OC,Ep)=>{"use strict";var ou=st(),uu=xe(),cu=Ge(),tI=TypeError;Ep.exports=function(a,e){var t,i;if(e==="string"&&uu(t=a.toString)&&!cu(i=ou(t,a))||uu(t=a.valueOf)&&!cu(i=ou(t,a))||e!=="string"&&uu(t=a.toString)&&!cu(i=ou(t,a)))return i;throw new tI("Can't convert object to primitive value")}});var It=g((NC,xp)=>{"use strict";xp.exports=!0});var Ap=g((FC,kp)=>{"use strict";var Pp=we(),iI=Object.defineProperty;kp.exports=function(a,e){try{iI(Pp,a,{value:e,configurable:!0,writable:!0})}catch(t){Pp[a]=e}return e}});var na=g((qC,$p)=>{"use strict";var rI=It(),aI=we(),sI=Ap(),Rp="__core-js_shared__",Mp=$p.exports=aI[Rp]||sI(Rp,{});(Mp.versions||(Mp.versions=[])).push({version:"3.43.0",mode:rI?"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 lu=g((UC,Dp)=>{"use strict";var Cp=na();Dp.exports=function(a,e){return Cp[a]||(Cp[a]=e||{})}});var hr=g((jC,Lp)=>{"use strict";var nI=ui(),oI=Object;Lp.exports=function(a){return oI(nI(a))}});var Et=g((HC,Bp)=>{"use strict";var uI=$e(),cI=hr(),lI=uI({}.hasOwnProperty);Bp.exports=Object.hasOwn||function(e,t){return lI(cI(e),t)}});var du=g((QC,Vp)=>{"use strict";var dI=$e(),pI=0,hI=Math.random(),fI=dI(1.1.toString);Vp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+fI(++pI+hI,36)}});var Ne=g((WC,Op)=>{"use strict";var mI=we(),bI=lu(),_p=Et(),gI=du(),vI=au(),SI=su(),fr=mI.Symbol,pu=bI("wks"),yI=SI?fr.for||fr:fr&&fr.withoutSetter||gI;Op.exports=function(a){return _p(pu,a)||(pu[a]=vI&&_p(fr,a)?fr[a]:yI("Symbol."+a)),pu[a]}});var Up=g((zC,qp)=>{"use strict";var TI=st(),Np=Ge(),Fp=nu(),II=sa(),EI=wp(),wI=Ne(),xI=TypeError,PI=wI("toPrimitive");qp.exports=function(a,e){if(!Np(a)||Fp(a))return a;var t=II(a,PI),i;if(t){if(e===void 0&&(e="default"),i=TI(t,a,e),!Np(i)||Fp(i))return i;throw new xI("Can't convert object to primitive value")}return e===void 0&&(e="number"),EI(a,e)}});var hu=g((GC,jp)=>{"use strict";var kI=Up(),AI=nu();jp.exports=function(a){var e=kI(a,"string");return AI(e)?e:e+""}});var Xs=g((YC,Qp)=>{"use strict";var RI=we(),Hp=Ge(),fu=RI.document,MI=Hp(fu)&&Hp(fu.createElement);Qp.exports=function(a){return MI?fu.createElement(a):{}}});var mu=g((KC,Wp)=>{"use strict";var $I=at(),CI=Me(),DI=Xs();Wp.exports=!$I&&!CI(function(){return Object.defineProperty(DI("div"),"a",{get:function(){return 7}}).a!==7})});var Yp=g(Gp=>{"use strict";var LI=at(),BI=st(),VI=Jo(),_I=ta(),OI=Bi(),NI=hu(),FI=Et(),qI=mu(),zp=Object.getOwnPropertyDescriptor;Gp.f=LI?zp:function(e,t){if(e=OI(e),t=NI(t),qI)try{return zp(e,t)}catch(i){}if(FI(e,t))return _I(!BI(VI.f,e,t),e[t])}});var bu=g((JC,Kp)=>{"use strict";var UI=Me(),jI=xe(),HI=/#|\.prototype\./,oa=function(a,e){var t=WI[QI(a)];return t===GI?!0:t===zI?!1:jI(e)?UI(e):!!e},QI=oa.normalize=function(a){return String(a).replace(HI,".").toLowerCase()},WI=oa.data={},zI=oa.NATIVE="N",GI=oa.POLYFILL="P";Kp.exports=oa});var mr=g((ZC,Jp)=>{"use strict";var Xp=Ko(),YI=Dt(),KI=ea(),XI=Xp(Xp.bind);Jp.exports=function(a,e){return YI(a),e===void 0?a:KI?XI(a,e):function(){return a.apply(e,arguments)}}});var gu=g((eD,Zp)=>{"use strict";var JI=at(),ZI=Me();Zp.exports=JI&&ZI(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Lt=g((tD,eh)=>{"use strict";var eE=Ge(),tE=String,iE=TypeError;eh.exports=function(a){if(eE(a))return a;throw new iE(tE(a)+" is not an object")}});var Oi=g(ih=>{"use strict";var rE=at(),aE=mu(),sE=gu(),Js=Lt(),th=hu(),nE=TypeError,vu=Object.defineProperty,oE=Object.getOwnPropertyDescriptor,Su="enumerable",yu="configurable",Tu="writable";ih.f=rE?sE?function(e,t,i){if(Js(e),t=th(t),Js(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Tu in i&&!i[Tu]){var r=oE(e,t);r&&r[Tu]&&(e[t]=i.value,i={configurable:yu in i?i[yu]:r[yu],enumerable:Su in i?i[Su]:r[Su],writable:!1})}return vu(e,t,i)}:vu:function(e,t,i){if(Js(e),t=th(t),Js(i),aE)try{return vu(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new nE("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var br=g((rD,rh)=>{"use strict";var uE=at(),cE=Oi(),lE=ta();rh.exports=uE?function(a,e,t){return cE.f(a,e,lE(1,t))}:function(a,e,t){return a[e]=t,a}});var ke=g((aD,sh)=>{"use strict";var ua=we(),dE=Go(),pE=Ko(),hE=xe(),fE=Yp().f,mE=bu(),gr=Vi(),bE=mr(),vr=br(),ah=Et();na();var gE=function(a){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,i)}return new a(t,i,r)}return dE(a,this,arguments)};return e.prototype=a.prototype,e};sh.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?ua:r?ua[t]:ua[t]&&ua[t].prototype,o=i?gr:gr[t]||vr(gr,t,{})[t],u=o.prototype,c,d,l,p,h,m,b,S,v;for(p in e)c=mE(i?p:t+(r?".":"#")+p,a.forced),d=!c&&n&&ah(n,p),m=o[p],d&&(a.dontCallGetSet?(v=fE(n,p),b=v&&v.value):b=n[p]),h=d&&b?b:e[p],!(!c&&!s&&typeof m==typeof h)&&(a.bind&&d?S=bE(h,ua):a.wrap&&d?S=gE(h):s&&hE(h)?S=pE(h):S=h,(a.sham||h&&h.sham||m&&m.sham)&&vr(S,"sham",!0),vr(o,p,S),s&&(l=t+"Prototype",ah(gr,l)||vr(gr,l,{}),vr(gr[l],p,h),a.real&&u&&(c||!u[p])&&vr(u,p,h)))}});var Zs=g((sD,oh)=>{"use strict";var vE=lu(),SE=du(),nh=vE("keys");oh.exports=function(a){return nh[a]||(nh[a]=SE(a))}});var ch=g((nD,uh)=>{"use strict";var yE=Me();uh.exports=!yE(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var en=g((oD,dh)=>{"use strict";var TE=Et(),IE=xe(),EE=hr(),wE=Zs(),xE=ch(),lh=wE("IE_PROTO"),Iu=Object,PE=Iu.prototype;dh.exports=xE?Iu.getPrototypeOf:function(a){var e=EE(a);if(TE(e,lh))return e[lh];var t=e.constructor;return IE(t)&&e instanceof t?t.prototype:e instanceof Iu?PE:null}});var hh=g((uD,ph)=>{"use strict";var kE=Math.ceil,AE=Math.floor;ph.exports=Math.trunc||function(e){var t=+e;return(t>0?AE:kE)(t)}});var ca=g((cD,fh)=>{"use strict";var RE=hh();fh.exports=function(a){var e=+a;return e!==e||e===0?0:RE(e)}});var bh=g((lD,mh)=>{"use strict";var ME=ca(),$E=Math.max,CE=Math.min;mh.exports=function(a,e){var t=ME(a);return t<0?$E(t+e,0):CE(t,e)}});var Eu=g((dD,gh)=>{"use strict";var DE=ca(),LE=Math.min;gh.exports=function(a){var e=DE(a);return e>0?LE(e,9007199254740991):0}});var Sr=g((pD,vh)=>{"use strict";var BE=Eu();vh.exports=function(a){return BE(a.length)}});var wu=g((hD,yh)=>{"use strict";var VE=Bi(),_E=bh(),OE=Sr(),Sh=function(a){return function(e,t,i){var r=VE(e),s=OE(r);if(s===0)return!a&&-1;var n=_E(i,s),o;if(a&&t!==t){for(;s>n;)if(o=r[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in r)&&r[n]===t)return a||n||0;return!a&&-1}};yh.exports={includes:Sh(!0),indexOf:Sh(!1)}});var tn=g((fD,Th)=>{"use strict";Th.exports={}});var wh=g((mD,Eh)=>{"use strict";var NE=$e(),xu=Et(),FE=Bi(),qE=wu().indexOf,UE=tn(),Ih=NE([].push);Eh.exports=function(a,e){var t=FE(a),i=0,r=[],s;for(s in t)!xu(UE,s)&&xu(t,s)&&Ih(r,s);for(;e.length>i;)xu(t,s=e[i++])&&(~qE(r,s)||Ih(r,s));return r}});var Pu=g((bD,xh)=>{"use strict";xh.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var ku=g((gD,Ph)=>{"use strict";var jE=wh(),HE=Pu();Ph.exports=Object.keys||function(e){return jE(e,HE)}});var Au=g((vD,$h)=>{"use strict";var Ah=at(),QE=Me(),Rh=$e(),WE=en(),zE=ku(),GE=Bi(),YE=Jo().f,Mh=Rh(YE),KE=Rh([].push),XE=Ah&&QE(function(){var a=Object.create(null);return a[2]=2,!Mh(a,2)}),kh=function(a){return function(e){for(var t=GE(e),i=zE(t),r=XE&&WE(t)===null,s=i.length,n=0,o=[],u;s>n;)u=i[n++],(!Ah||(r?u in t:Mh(t,u)))&&KE(o,a?[u,t[u]]:t[u]);return o}};$h.exports={entries:kh(!0),values:kh(!1)}});var Ch=g(()=>{"use strict";var JE=ke(),ZE=Au().values;JE({target:"Object",stat:!0},{values:function(e){return ZE(e)}})});var Lh=g((TD,Dh)=>{"use strict";Ch();var ew=Vi();Dh.exports=ew.Object.values});var Vh=g((ID,Bh)=>{"use strict";var tw=Lh();Bh.exports=tw});var Ni=g((ED,_h)=>{"use strict";var iw=Vh();_h.exports=iw});var la=g((wD,Oh)=>{"use strict";Oh.exports=function(){}});var Nh=g(()=>{"use strict";var rw=ke(),aw=wu().includes,sw=Me(),nw=la(),ow=sw(function(){return!Array(1).includes()});rw({target:"Array",proto:!0,forced:ow},{includes:function(e){return aw(this,e,arguments.length>1?arguments[1]:void 0)}});nw("includes")});var ci=g((kD,Fh)=>{"use strict";var uw=Qt();Fh.exports=uw});var Uh=g((AD,qh)=>{"use strict";Nh();var cw=ci();qh.exports=cw("Array","includes")});var Hh=g((RD,jh)=>{"use strict";var lw=Uh();jh.exports=lw});var Ye=g((MD,Qh)=>{"use strict";var dw=Hh();Qh.exports=dw});var of=g(()=>{"use strict";var Tw=ke(),Iw=Au().entries;Tw({target:"Object",stat:!0},{entries:function(e){return Iw(e)}})});var cf=g((g0,uf)=>{"use strict";of();var Ew=Vi();uf.exports=Ew.Object.entries});var df=g((v0,lf)=>{"use strict";var ww=cf();lf.exports=ww});var pi=g((S0,pf)=>{"use strict";var xw=df();pf.exports=xw});var qi=g((y0,hf)=>{"use strict";hf.exports={}});var bf=g((T0,mf)=>{"use strict";var Pw=we(),kw=xe(),ff=Pw.WeakMap;mf.exports=kw(ff)&&/native code/.test(String(ff))});var Vu=g((I0,Sf)=>{"use strict";var Aw=bf(),vf=we(),Rw=Ge(),Mw=br(),Du=Et(),Lu=na(),$w=Zs(),Cw=tn(),gf="Object already initialized",Bu=vf.TypeError,Dw=vf.WeakMap,bn,ma,gn,Lw=function(a){return gn(a)?ma(a):bn(a,{})},Bw=function(a){return function(e){var t;if(!Rw(e)||(t=ma(e)).type!==a)throw new Bu("Incompatible receiver, "+a+" required");return t}};Aw||Lu.state?(wt=Lu.state||(Lu.state=new Dw),wt.get=wt.get,wt.has=wt.has,wt.set=wt.set,bn=function(a,e){if(wt.has(a))throw new Bu(gf);return e.facade=a,wt.set(a,e),e},ma=function(a){return wt.get(a)||{}},gn=function(a){return wt.has(a)}):(Ui=$w("state"),Cw[Ui]=!0,bn=function(a,e){if(Du(a,Ui))throw new Bu(gf);return e.facade=a,Mw(a,Ui,e),e},ma=function(a){return Du(a,Ui)?a[Ui]:{}},gn=function(a){return Du(a,Ui)});var wt,Ui;Sf.exports={set:bn,get:ma,has:gn,enforce:Lw,getterFor:Bw}});var Nu=g((E0,Tf)=>{"use strict";var _u=at(),Vw=Et(),yf=Function.prototype,_w=_u&&Object.getOwnPropertyDescriptor,Ou=Vw(yf,"name"),Ow=Ou&&function(){}.name==="something",Nw=Ou&&(!_u||_u&&_w(yf,"name").configurable);Tf.exports={EXISTS:Ou,PROPER:Ow,CONFIGURABLE:Nw}});var Ef=g(If=>{"use strict";var Fw=at(),qw=gu(),Uw=Oi(),jw=Lt(),Hw=Bi(),Qw=ku();If.f=Fw&&!qw?Object.defineProperties:function(e,t){jw(e);for(var i=Hw(t),r=Qw(t),s=r.length,n=0,o;s>n;)Uw.f(e,o=r[n++],i[o]);return e}});var Fu=g((x0,wf)=>{"use strict";var Ww=Qt();wf.exports=Ww("document","documentElement")});var Hu=g((P0,$f)=>{"use strict";var zw=Lt(),Gw=Ef(),xf=Pu(),Yw=tn(),Kw=Fu(),Xw=Xs(),Jw=Zs(),Pf=">",kf="<",Uu="prototype",ju="script",Rf=Jw("IE_PROTO"),qu=function(){},Mf=function(a){return kf+ju+Pf+a+kf+"/"+ju+Pf},Af=function(a){a.write(Mf("")),a.close();var e=a.parentWindow.Object;return a=null,e},Zw=function(){var a=Xw("iframe"),e="java"+ju+":",t;return a.style.display="none",Kw.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Mf("document.F=Object")),t.close(),t.F},vn,Sn=function(){try{vn=new ActiveXObject("htmlfile")}catch(e){}Sn=typeof document!="undefined"?document.domain&&vn?Af(vn):Zw():Af(vn);for(var a=xf.length;a--;)delete Sn[Uu][xf[a]];return Sn()};Yw[Rf]=!0;$f.exports=Object.create||function(e,t){var i;return e!==null?(qu[Uu]=zw(e),i=new qu,qu[Uu]=null,i[Rf]=e):i=Sn(),t===void 0?i:Gw.f(i,t)}});var Tr=g((k0,Cf)=>{"use strict";var ex=br();Cf.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:ex(a,e,t),a}});var Gu=g((A0,Bf)=>{"use strict";var tx=Me(),ix=xe(),rx=Ge(),ax=Hu(),Df=en(),sx=Tr(),nx=Ne(),ox=It(),zu=nx("iterator"),Lf=!1,zt,Qu,Wu;[].keys&&(Wu=[].keys(),"next"in Wu?(Qu=Df(Df(Wu)),Qu!==Object.prototype&&(zt=Qu)):Lf=!0);var ux=!rx(zt)||tx(function(){var a={};return zt[zu].call(a)!==a});ux?zt={}:ox&&(zt=ax(zt));ix(zt[zu])||sx(zt,zu,function(){return this});Bf.exports={IteratorPrototype:zt,BUGGY_SAFARI_ITERATORS:Lf}});var yn=g((R0,_f)=>{"use strict";var cx=Ne(),lx=cx("toStringTag"),Vf={};Vf[lx]="z";_f.exports=String(Vf)==="[object z]"});var ba=g((M0,Of)=>{"use strict";var dx=yn(),px=xe(),Tn=Li(),hx=Ne(),fx=hx("toStringTag"),mx=Object,bx=Tn(function(){return arguments}())==="Arguments",gx=function(a,e){try{return a[e]}catch(t){}};Of.exports=dx?Tn:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=gx(e=mx(a),fx))=="string"?t:bx?Tn(e):(i=Tn(e))==="Object"&&px(e.callee)?"Arguments":i}});var Ff=g(($0,Nf)=>{"use strict";var vx=yn(),Sx=ba();Nf.exports=vx?{}.toString:function(){return"[object "+Sx(this)+"]"}});var ga=g((C0,Uf)=>{"use strict";var yx=yn(),Tx=Oi().f,Ix=br(),Ex=Et(),wx=Ff(),xx=Ne(),qf=xx("toStringTag");Uf.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(Ex(r,qf)||Tx(r,qf,{configurable:!0,value:e}),i&&!yx&&Ix(r,"toString",wx))}});var Hf=g((D0,jf)=>{"use strict";var Px=Gu().IteratorPrototype,kx=Hu(),Ax=ta(),Rx=ga(),Mx=qi(),$x=function(){return this};jf.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=kx(Px,{next:Ax(+!i,t)}),Rx(a,r,!1,!0),Mx[r]=$x,a}});var Wf=g((L0,Qf)=>{"use strict";var Cx=$e(),Dx=Dt();Qf.exports=function(a,e,t){try{return Cx(Dx(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(i){}}});var Gf=g((B0,zf)=>{"use strict";var Lx=Ge();zf.exports=function(a){return Lx(a)||a===null}});var Kf=g((V0,Yf)=>{"use strict";var Bx=Gf(),Vx=String,_x=TypeError;Yf.exports=function(a){if(Bx(a))return a;throw new _x("Can't set "+Vx(a)+" as a prototype")}});var Yu=g((_0,Xf)=>{"use strict";var Ox=Wf(),Nx=Ge(),Fx=ui(),qx=Kf();Xf.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=Ox(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(i){}return function(r,s){return Fx(r),qx(s),Nx(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var um=g((O0,om)=>{"use strict";var Ux=ke(),jx=st(),In=It(),sm=Nu(),Hx=xe(),Qx=Hf(),Jf=en(),Zf=Yu(),Wx=ga(),zx=br(),Ku=Tr(),Gx=Ne(),em=qi(),nm=Gu(),Yx=sm.PROPER,Kx=sm.CONFIGURABLE,tm=nm.IteratorPrototype,En=nm.BUGGY_SAFARI_ITERATORS,va=Gx("iterator"),im="keys",Sa="values",rm="entries",am=function(){return this};om.exports=function(a,e,t,i,r,s,n){Qx(t,e,i);var o=function(v){if(v===r&&p)return p;if(!En&&v&&v in d)return d[v];switch(v){case im:return function(){return new t(this,v)};case Sa:return function(){return new t(this,v)};case rm:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",c=!1,d=a.prototype,l=d[va]||d["@@iterator"]||r&&d[r],p=!En&&l||o(r),h=e==="Array"&&d.entries||l,m,b,S;if(h&&(m=Jf(h.call(new a)),m!==Object.prototype&&m.next&&(!In&&Jf(m)!==tm&&(Zf?Zf(m,tm):Hx(m[va])||Ku(m,va,am)),Wx(m,u,!0,!0),In&&(em[u]=am))),Yx&&r===Sa&&l&&l.name!==Sa&&(!In&&Kx?zx(d,"name",Sa):(c=!0,p=function(){return jx(l,this)})),r)if(b={values:o(Sa),keys:s?p:o(im),entries:o(rm)},n)for(S in b)(En||c||!(S in d))&&Ku(d,S,b[S]);else Ux({target:e,proto:!0,forced:En||c},b);return(!In||n)&&d[va]!==p&&Ku(d,va,p,{name:r}),em[e]=p,b}});var lm=g((N0,cm)=>{"use strict";cm.exports=function(a,e){return{value:a,done:e}}});var Ju=g((F0,mm)=>{"use strict";var Xx=Bi(),Xu=la(),dm=qi(),hm=Vu(),Jx=Oi().f,Zx=um(),wn=lm(),eP=It(),tP=at(),fm="Array Iterator",iP=hm.set,rP=hm.getterFor(fm);mm.exports=Zx(Array,"Array",function(a,e){iP(this,{type:fm,target:Xx(a),index:0,kind:e})},function(){var a=rP(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=null,wn(void 0,!0);switch(a.kind){case"keys":return wn(t,!1);case"values":return wn(e[t],!1)}return wn([t,e[t]],!1)},"values");var pm=dm.Arguments=dm.Array;Xu("keys");Xu("values");Xu("entries");if(!eP&&tP&&pm.name!=="values")try{Jx(pm,"name",{value:"values"})}catch(a){}});var gm=g((q0,bm)=>{"use strict";var aP=Ne(),sP=qi(),nP=aP("iterator"),oP=Array.prototype;bm.exports=function(a){return a!==void 0&&(sP.Array===a||oP[nP]===a)}});var Zu=g((U0,Sm)=>{"use strict";var uP=ba(),vm=sa(),cP=ia(),lP=qi(),dP=Ne(),pP=dP("iterator");Sm.exports=function(a){if(!cP(a))return vm(a,pP)||vm(a,"@@iterator")||lP[uP(a)]}});var Tm=g((j0,ym)=>{"use strict";var hP=st(),fP=Dt(),mP=Lt(),bP=aa(),gP=Zu(),vP=TypeError;ym.exports=function(a,e){var t=arguments.length<2?gP(a):e;if(fP(t))return mP(hP(t,a));throw new vP(bP(a)+" is not iterable")}});var wm=g((H0,Em)=>{"use strict";var SP=st(),Im=Lt(),yP=sa();Em.exports=function(a,e,t){var i,r;Im(a);try{if(i=yP(a,"return"),!i){if(e==="throw")throw t;return t}i=SP(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return Im(i),t}});var Pn=g((Q0,Am)=>{"use strict";var TP=mr(),IP=st(),EP=Lt(),wP=aa(),xP=gm(),PP=Sr(),xm=ra(),kP=Tm(),AP=Zu(),Pm=wm(),RP=TypeError,xn=function(a,e){this.stopped=a,this.result=e},km=xn.prototype;Am.exports=function(a,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=TP(e,i),c,d,l,p,h,m,b,S=function(y){return c&&Pm(c,"normal"),new xn(!0,y)},v=function(y){return r?(EP(y),o?u(y[0],y[1],S):u(y[0],y[1])):o?u(y,S):u(y)};if(s)c=a.iterator;else if(n)c=a;else{if(d=AP(a),!d)throw new RP(wP(a)+" is not iterable");if(xP(d)){for(l=0,p=PP(a);p>l;l++)if(h=v(a[l]),h&&xm(km,h))return h;return new xn(!1)}c=kP(a,d)}for(m=s?a.next:c.next;!(b=IP(m,c)).done;){try{h=v(b.value)}catch(y){Pm(c,"throw",y)}if(typeof h=="object"&&h&&xm(km,h))return h}return new xn(!1)}});var Mm=g((W0,Rm)=>{"use strict";var MP=at(),$P=Oi(),CP=ta();Rm.exports=function(a,e,t){MP?$P.f(a,e,CP(0,t)):a[e]=t}});var $m=g(()=>{"use strict";var DP=ke(),LP=Pn(),BP=Mm();DP({target:"Object",stat:!0},{fromEntries:function(e){var t={};return LP(e,function(i,r){BP(t,i,r)},{AS_ENTRIES:!0}),t}})});var Dm=g((Y0,Cm)=>{"use strict";Ju();$m();var VP=Vi();Cm.exports=VP.Object.fromEntries});var Bm=g((K0,Lm)=>{"use strict";Lm.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 _m=g(()=>{"use strict";Ju();var _P=Bm(),OP=we(),NP=ga(),Vm=qi();for(kn in _P)NP(OP[kn],kn),Vm[kn]=Vm.Array;var kn});var Nm=g((Z0,Om)=>{"use strict";var FP=Dm();_m();Om.exports=FP});var ec=g((eB,Fm)=>{"use strict";var qP=Nm();Fm.exports=qP});var qm=g(()=>{"use strict"});var tc=g((rB,Um)=>{"use strict";var ya=we(),UP=_i(),jP=Li(),An=function(a){return UP.slice(0,a.length)===a};Um.exports=function(){return An("Bun/")?"BUN":An("Cloudflare-Workers")?"CLOUDFLARE":An("Deno/")?"DENO":An("Node.js/")?"NODE":ya.Bun&&typeof Bun.version=="string"?"BUN":ya.Deno&&typeof Deno.version=="object"?"DENO":jP(ya.process)==="process"?"NODE":ya.window&&ya.document?"BROWSER":"REST"}()});var Rn=g((aB,jm)=>{"use strict";var HP=tc();jm.exports=HP==="NODE"});var Qm=g((sB,Hm)=>{"use strict";var QP=Oi();Hm.exports=function(a,e,t){return QP.f(a,e,t)}});var Gm=g((nB,zm)=>{"use strict";var WP=Qt(),zP=Qm(),GP=Ne(),YP=at(),Wm=GP("species");zm.exports=function(a){var e=WP(a);YP&&e&&!e[Wm]&&zP(e,Wm,{configurable:!0,get:function(){return this}})}});var Km=g((oB,Ym)=>{"use strict";var KP=ra(),XP=TypeError;Ym.exports=function(a,e){if(KP(e,a))return a;throw new XP("Incorrect invocation")}});var rc=g((uB,Xm)=>{"use strict";var JP=$e(),ZP=xe(),ic=na(),ek=JP(Function.toString);ZP(ic.inspectSource)||(ic.inspectSource=function(a){return ek(a)});Xm.exports=ic.inspectSource});var sc=g((cB,ib)=>{"use strict";var tk=$e(),ik=Me(),Jm=xe(),rk=ba(),ak=Qt(),sk=rc(),Zm=function(){},eb=ak("Reflect","construct"),ac=/^\s*(?:class|function)\b/,nk=tk(ac.exec),ok=!ac.test(Zm),Ta=function(e){if(!Jm(e))return!1;try{return eb(Zm,[],e),!0}catch(t){return!1}},tb=function(e){if(!Jm(e))return!1;switch(rk(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return ok||!!nk(ac,sk(e))}catch(t){return!0}};tb.sham=!0;ib.exports=!eb||ik(function(){var a;return Ta(Ta.call)||!Ta(Object)||!Ta(function(){a=!0})||a})?tb:Ta});var ab=g((lB,rb)=>{"use strict";var uk=sc(),ck=aa(),lk=TypeError;rb.exports=function(a){if(uk(a))return a;throw new lk(ck(a)+" is not a constructor")}});var nc=g((dB,nb)=>{"use strict";var sb=Lt(),dk=ab(),pk=ia(),hk=Ne(),fk=hk("species");nb.exports=function(a,e){var t=sb(a).constructor,i;return t===void 0||pk(i=sb(t)[fk])?e:dk(i)}});var ub=g((pB,ob)=>{"use strict";var mk=$e();ob.exports=mk([].slice)});var lb=g((hB,cb)=>{"use strict";var bk=TypeError;cb.exports=function(a,e){if(a<e)throw new bk("Not enough arguments");return a}});var oc=g((fB,db)=>{"use strict";var gk=_i();db.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(gk)});var bc=g((mB,yb)=>{"use strict";var ot=we(),vk=Go(),Sk=mr(),pb=xe(),yk=Et(),Sb=Me(),hb=Fu(),Tk=ub(),fb=Xs(),Ik=lb(),Ek=oc(),wk=Rn(),hc=ot.setImmediate,fc=ot.clearImmediate,xk=ot.process,uc=ot.Dispatch,Pk=ot.Function,mb=ot.MessageChannel,kk=ot.String,cc=0,Ia={},bb="onreadystatechange",Ea,ji,lc,dc;Sb(function(){Ea=ot.location});var mc=function(a){if(yk(Ia,a)){var e=Ia[a];delete Ia[a],e()}},pc=function(a){return function(){mc(a)}},gb=function(a){mc(a.data)},vb=function(a){ot.postMessage(kk(a),Ea.protocol+"//"+Ea.host)};(!hc||!fc)&&(hc=function(e){Ik(arguments.length,1);var t=pb(e)?e:Pk(e),i=Tk(arguments,1);return Ia[++cc]=function(){vk(t,void 0,i)},ji(cc),cc},fc=function(e){delete Ia[e]},wk?ji=function(a){xk.nextTick(pc(a))}:uc&&uc.now?ji=function(a){uc.now(pc(a))}:mb&&!Ek?(lc=new mb,dc=lc.port2,lc.port1.onmessage=gb,ji=Sk(dc.postMessage,dc)):ot.addEventListener&&pb(ot.postMessage)&&!ot.importScripts&&Ea&&Ea.protocol!=="file:"&&!Sb(vb)?(ji=vb,ot.addEventListener("message",gb,!1)):bb in fb("script")?ji=function(a){hb.appendChild(fb("script"))[bb]=function(){hb.removeChild(this),mc(a)}}:ji=function(a){setTimeout(pc(a),0)});yb.exports={set:hc,clear:fc}});var Eb=g((bB,Ib)=>{"use strict";var Tb=we(),Ak=at(),Rk=Object.getOwnPropertyDescriptor;Ib.exports=function(a){if(!Ak)return Tb[a];var e=Rk(Tb,a);return e&&e.value}});var gc=g((gB,xb)=>{"use strict";var wb=function(){this.head=null,this.tail=null};wb.prototype={add:function(a){var e={item:a,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var a=this.head;if(a){var e=this.head=a.next;return e===null&&(this.tail=null),a.item}}};xb.exports=wb});var kb=g((vB,Pb)=>{"use strict";var Mk=_i();Pb.exports=/ipad|iphone|ipod/i.test(Mk)&&typeof Pebble!="undefined"});var Rb=g((SB,Ab)=>{"use strict";var $k=_i();Ab.exports=/web0s(?!.*chrome)/i.test($k)});var Vb=g((yB,Bb)=>{"use strict";var Er=we(),Ck=Eb(),Mb=mr(),vc=bc().set,Dk=gc(),Lk=oc(),Bk=kb(),Vk=Rb(),Sc=Rn(),$b=Er.MutationObserver||Er.WebKitMutationObserver,Cb=Er.document,Db=Er.process,Mn=Er.Promise,Ic=Ck("queueMicrotask"),Ir,yc,Tc,$n,Lb;Ic||(wa=new Dk,xa=function(){var a,e;for(Sc&&(a=Db.domain)&&a.exit();e=wa.get();)try{e()}catch(t){throw wa.head&&Ir(),t}a&&a.enter()},!Lk&&!Sc&&!Vk&&$b&&Cb?(yc=!0,Tc=Cb.createTextNode(""),new $b(xa).observe(Tc,{characterData:!0}),Ir=function(){Tc.data=yc=!yc}):!Bk&&Mn&&Mn.resolve?($n=Mn.resolve(void 0),$n.constructor=Mn,Lb=Mb($n.then,$n),Ir=function(){Lb(xa)}):Sc?Ir=function(){Db.nextTick(xa)}:(vc=Mb(vc,Er),Ir=function(){vc(xa)}),Ic=function(a){wa.head||Ir(),wa.add(a)});var wa,xa;Bb.exports=Ic});var Ob=g((TB,_b)=>{"use strict";_b.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Cn=g((IB,Nb)=>{"use strict";Nb.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Hi=g((EB,Fb)=>{"use strict";var _k=we();Fb.exports=_k.Promise});var wr=g((wB,Hb)=>{"use strict";var Ok=we(),Pa=Hi(),Nk=xe(),Fk=bu(),qk=rc(),Uk=Ne(),qb=tc(),jk=It(),Ec=ru(),Ub=Pa&&Pa.prototype,Hk=Uk("species"),wc=!1,jb=Nk(Ok.PromiseRejectionEvent),Qk=Fk("Promise",function(){var a=qk(Pa),e=a!==String(Pa);if(!e&&Ec===66||jk&&!(Ub.catch&&Ub.finally))return!0;if(!Ec||Ec<51||!/native code/.test(a)){var t=new Pa(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[Hk]=i,wc=t.then(function(){})instanceof i,!wc)return!0}return!e&&(qb==="BROWSER"||qb==="DENO")&&!jb});Hb.exports={CONSTRUCTOR:Qk,REJECTION_EVENT:jb,SUBCLASSING:wc}});var xr=g((xB,Wb)=>{"use strict";var Qb=Dt(),Wk=TypeError,zk=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new Wk("Bad Promise constructor");e=i,t=r}),this.resolve=Qb(e),this.reject=Qb(t)};Wb.exports.f=function(a){return new zk(a)}});var pg=g(()=>{"use strict";var Gk=ke(),Yk=It(),Vn=Rn(),hi=we(),Kk=Vi(),Rr=st(),zb=Tr(),Gb=Yu(),Xk=ga(),Jk=Gm(),Zk=Dt(),Bn=xe(),eA=Ge(),tA=Km(),iA=nc(),Zb=bc().set,Rc=Vb(),rA=Ob(),aA=Cn(),sA=gc(),eg=Vu(),_n=Hi(),Mc=wr(),tg=xr(),On="Promise",ig=Mc.CONSTRUCTOR,nA=Mc.REJECTION_EVENT,oA=Mc.SUBCLASSING,xc=eg.getterFor(On),uA=eg.set,Pr=_n&&_n.prototype,Qi=_n,Dn=Pr,rg=hi.TypeError,Pc=hi.document,$c=hi.process,kc=tg.f,cA=kc,lA=!!(Pc&&Pc.createEvent&&hi.dispatchEvent),ag="unhandledrejection",dA="rejectionhandled",Yb=0,sg=1,pA=2,Cc=1,ng=2,Ln,Kb,og,Xb,ug=function(a){var e;return eA(a)&&Bn(e=a.then)?e:!1},cg=function(a,e){var t=e.value,i=e.state===sg,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,c,d;try{r?(i||(e.rejection===ng&&fA(e),e.rejection=Cc),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===a.promise?n(new rg("Promise-chain cycle")):(c=ug(u))?Rr(c,u,s,n):s(u)):n(t)}catch(l){o&&!d&&o.exit(),n(l)}},lg=function(a,e){a.notified||(a.notified=!0,Rc(function(){for(var t=a.reactions,i;i=t.get();)cg(i,a);a.notified=!1,e&&!a.rejection&&hA(a)}))},dg=function(a,e,t){var i,r;lA?(i=Pc.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),hi.dispatchEvent(i)):i={promise:e,reason:t},!nA&&(r=hi["on"+a])?r(i):a===ag&&rA("Unhandled promise rejection",t)},hA=function(a){Rr(Zb,hi,function(){var e=a.facade,t=a.value,i=Jb(a),r;if(i&&(r=aA(function(){Vn?$c.emit("unhandledRejection",t,e):dg(ag,e,t)}),a.rejection=Vn||Jb(a)?ng:Cc,r.error))throw r.value})},Jb=function(a){return a.rejection!==Cc&&!a.parent},fA=function(a){Rr(Zb,hi,function(){var e=a.facade;Vn?$c.emit("rejectionHandled",e):dg(dA,e,a.value)})},kr=function(a,e,t){return function(i){a(e,i,t)}},Ar=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=pA,lg(a,!0))},Ac=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new rg("Promise can't be resolved itself");var i=ug(e);i?Rc(function(){var r={done:!1};try{Rr(i,e,kr(Ac,r,a),kr(Ar,r,a))}catch(s){Ar(r,s,a)}}):(a.value=e,a.state=sg,lg(a,!1))}catch(r){Ar({done:!1},r,a)}}};if(ig&&(Qi=function(e){tA(this,Dn),Zk(e),Rr(Ln,this);var t=xc(this);try{e(kr(Ac,t),kr(Ar,t))}catch(i){Ar(t,i)}},Dn=Qi.prototype,Ln=function(e){uA(this,{type:On,done:!1,notified:!1,parent:!1,reactions:new sA,rejection:!1,state:Yb,value:null})},Ln.prototype=zb(Dn,"then",function(e,t){var i=xc(this),r=kc(iA(this,Qi));return i.parent=!0,r.ok=Bn(e)?e:!0,r.fail=Bn(t)&&t,r.domain=Vn?$c.domain:void 0,i.state===Yb?i.reactions.add(r):Rc(function(){cg(r,i)}),r.promise}),Kb=function(){var a=new Ln,e=xc(a);this.promise=a,this.resolve=kr(Ac,e),this.reject=kr(Ar,e)},tg.f=kc=function(a){return a===Qi||a===og?new Kb(a):cA(a)},!Yk&&Bn(_n)&&Pr!==Object.prototype)){Xb=Pr.then,oA||zb(Pr,"then",function(e,t){var i=this;return new Qi(function(r,s){Rr(Xb,i,r,s)}).then(e,t)},{unsafe:!0});try{delete Pr.constructor}catch(a){}Gb&&Gb(Pr,Dn)}Gk({global:!0,constructor:!0,wrap:!0,forced:ig},{Promise:Qi});og=Kk.Promise;Xk(Qi,On,!1,!0);Jk(On)});var gg=g((AB,bg)=>{"use strict";var mA=Ne(),fg=mA("iterator"),mg=!1;try{hg=0,Dc={next:function(){return{done:!!hg++}},return:function(){mg=!0}},Dc[fg]=function(){return this},Array.from(Dc,function(){throw 2})}catch(a){}var hg,Dc;bg.exports=function(a,e){try{if(!e&&!mg)return!1}catch(r){return!1}var t=!1;try{var i={};i[fg]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch(r){}return t}});var Lc=g((RB,vg)=>{"use strict";var bA=Hi(),gA=gg(),vA=wr().CONSTRUCTOR;vg.exports=vA||!gA(function(a){bA.all(a).then(void 0,function(){})})});var Sg=g(()=>{"use strict";var SA=ke(),yA=st(),TA=Dt(),IA=xr(),EA=Cn(),wA=Pn(),xA=Lc();SA({target:"Promise",stat:!0,forced:xA},{all:function(e){var t=this,i=IA.f(t),r=i.resolve,s=i.reject,n=EA(function(){var o=TA(t.resolve),u=[],c=0,d=1;wA(e,function(l){var p=c++,h=!1;d++,yA(o,t,l).then(function(m){h||(h=!0,u[p]=m,--d||r(u))},s)}),--d||r(u)});return n.error&&s(n.value),i.promise}})});var Tg=g(()=>{"use strict";var PA=ke(),kA=It(),AA=wr().CONSTRUCTOR,Vc=Hi(),RA=Qt(),MA=xe(),$A=Tr(),yg=Vc&&Vc.prototype;PA({target:"Promise",proto:!0,forced:AA,real:!0},{catch:function(a){return this.then(void 0,a)}});!kA&&MA(Vc)&&(Bc=RA("Promise").prototype.catch,yg.catch!==Bc&&$A(yg,"catch",Bc,{unsafe:!0}));var Bc});var Ig=g(()=>{"use strict";var CA=ke(),DA=st(),LA=Dt(),BA=xr(),VA=Cn(),_A=Pn(),OA=Lc();CA({target:"Promise",stat:!0,forced:OA},{race:function(e){var t=this,i=BA.f(t),r=i.reject,s=VA(function(){var n=LA(t.resolve);_A(e,function(o){DA(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var Eg=g(()=>{"use strict";var NA=ke(),FA=xr(),qA=wr().CONSTRUCTOR;NA({target:"Promise",stat:!0,forced:qA},{reject:function(e){var t=FA.f(this),i=t.reject;return i(e),t.promise}})});var _c=g((OB,wg)=>{"use strict";var UA=Lt(),jA=Ge(),HA=xr();wg.exports=function(a,e){if(UA(a),jA(e)&&e.constructor===a)return e;var t=HA.f(a),i=t.resolve;return i(e),t.promise}});var kg=g(()=>{"use strict";var QA=ke(),WA=Qt(),xg=It(),zA=Hi(),Pg=wr().CONSTRUCTOR,GA=_c(),YA=WA("Promise"),KA=xg&&!Pg;QA({target:"Promise",stat:!0,forced:xg||Pg},{resolve:function(e){return GA(KA&&this===YA?zA:this,e)}})});var Ag=g(()=>{"use strict";pg();Sg();Tg();Ig();Eg();kg()});var Cg=g(()=>{"use strict";var XA=ke(),JA=It(),Nn=Hi(),ZA=Me(),Mg=Qt(),$g=xe(),eR=nc(),Rg=_c(),tR=Tr(),Nc=Nn&&Nn.prototype,iR=!!Nn&&ZA(function(){Nc.finally.call({then:function(){}},function(){})});XA({target:"Promise",proto:!0,real:!0,forced:iR},{finally:function(a){var e=eR(this,Mg("Promise")),t=$g(a);return this.then(t?function(i){return Rg(e,a()).then(function(){return i})}:a,t?function(i){return Rg(e,a()).then(function(){throw i})}:a)}});!JA&&$g(Nn)&&(Oc=Mg("Promise").prototype.finally,Nc.finally!==Oc&&tR(Nc,"finally",Oc,{unsafe:!0}));var Oc});var Lg=g((QB,Dg)=>{"use strict";qm();Ag();Cg();var rR=ci();Dg.exports=rR("Promise","finally")});var Vg=g((WB,Bg)=>{"use strict";var aR=Lg();Bg.exports=aR});var Fc=g((zB,_g)=>{"use strict";var sR=Vg();_g.exports=sR});var Qg=g(()=>{"use strict";var hR=ke(),fR=hr(),mR=Sr(),bR=ca(),gR=la();hR({target:"Array",proto:!0},{at:function(e){var t=fR(this),i=mR(t),r=bR(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});gR("at")});var zg=g((NV,Wg)=>{"use strict";Qg();var vR=ci();Wg.exports=vR("Array","at")});var Yg=g((FV,Gg)=>{"use strict";var SR=zg();Gg.exports=SR});var ft=g((qV,Kg)=>{"use strict";var yR=Yg();Kg.exports=yR});var ol=g((ON,Av)=>{"use strict";var BR=Li();Av.exports=Array.isArray||function(e){return BR(e)==="Array"}});var Mv=g((NN,Rv)=>{"use strict";var VR=TypeError,_R=9007199254740991;Rv.exports=function(a){if(a>_R)throw VR("Maximum allowed index exceeded");return a}});var Dv=g((FN,Cv)=>{"use strict";var OR=ol(),NR=Sr(),FR=Mv(),qR=mr(),$v=function(a,e,t,i,r,s,n,o){for(var u=r,c=0,d=n?qR(n,o):!1,l,p;c<i;)c in t&&(l=d?d(t[c],c,e):t[c],s>0&&OR(l)?(p=NR(l),u=$v(a,e,l,p,u,s-1)-1):(FR(u+1),a[u]=l),u++),c++;return u};Cv.exports=$v});var _v=g((qN,Vv)=>{"use strict";var Lv=ol(),UR=sc(),jR=Ge(),HR=Ne(),QR=HR("species"),Bv=Array;Vv.exports=function(a){var e;return Lv(a)&&(e=a.constructor,UR(e)&&(e===Bv||Lv(e.prototype))?e=void 0:jR(e)&&(e=e[QR],e===null&&(e=void 0))),e===void 0?Bv:e}});var Nv=g((UN,Ov)=>{"use strict";var WR=_v();Ov.exports=function(a,e){return new(WR(a))(e===0?0:e)}});var Fv=g(()=>{"use strict";var zR=ke(),GR=Dv(),YR=Dt(),KR=hr(),XR=Sr(),JR=Nv();zR({target:"Array",proto:!0},{flatMap:function(e){var t=KR(this),i=XR(t),r;return YR(e),r=JR(t,0),r.length=GR(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var qv=g(()=>{"use strict";var ZR=la();ZR("flatMap")});var jv=g((zN,Uv)=>{"use strict";Fv();qv();var eM=ci();Uv.exports=eM("Array","flatMap")});var Qv=g((GN,Hv)=>{"use strict";var tM=jv();Hv.exports=tM});var Fa=g((YN,Wv)=>{"use strict";var iM=Qv();Wv.exports=iM});var Ua=g((pF,Kv)=>{"use strict";var aM=ba(),sM=String;Kv.exports=function(a){if(aM(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return sM(a)}});var cl=g((hF,Xv)=>{"use strict";Xv.exports=`
7
- \v\f\r                 \u2028\u2029\uFEFF`});var eS=g((fF,Zv)=>{"use strict";var nM=$e(),oM=ui(),uM=Ua(),dl=cl(),Jv=nM("".replace),cM=RegExp("^["+dl+"]+"),lM=RegExp("(^|[^"+dl+"])["+dl+"]+$"),ll=function(a){return function(e){var t=uM(oM(e));return a&1&&(t=Jv(t,cM,"")),a&2&&(t=Jv(t,lM,"$1")),t}};Zv.exports={start:ll(1),end:ll(2),trim:ll(3)}});var aS=g((mF,rS)=>{"use strict";var dM=Nu().PROPER,pM=Me(),tS=cl(),iS="​…᠎";rS.exports=function(a){return pM(function(){return!!tS[a]()||iS[a]()!==iS||dM&&tS[a].name!==a})}});var pl=g((bF,sS)=>{"use strict";var hM=eS().start,fM=aS();sS.exports=fM("trimStart")?function(){return hM(this)}:"".trimStart});var oS=g(()=>{"use strict";var mM=ke(),nS=pl();mM({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==nS},{trimLeft:nS})});var cS=g(()=>{"use strict";oS();var bM=ke(),uS=pl();bM({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==uS},{trimStart:uS})});var dS=g((TF,lS)=>{"use strict";cS();var gM=ci();lS.exports=gM("String","trimLeft")});var hS=g((IF,pS)=>{"use strict";var vM=dS();pS.exports=vM});var mS=g((EF,fS)=>{"use strict";var SM=hS();fS.exports=SM});var gS=g(()=>{"use strict"});var vS=g(()=>{"use strict"});var yS=g((aq,SS)=>{"use strict";var yM=Ge(),TM=Li(),IM=Ne(),EM=IM("match");SS.exports=function(a){var e;return yM(a)&&((e=a[EM])!==void 0?!!e:TM(a)==="RegExp")}});var ES=g((sq,IS)=>{"use strict";var wM=we(),xM=Me(),TS=wM.RegExp,PM=!xM(function(){var a=!0;try{TS(".","d")}catch(u){a=!1}var e={},t="",i=a?"dgimsy":"gimsy",r=function(u,c){Object.defineProperty(e,u,{get:function(){return t+=c,!0}})},s={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};a&&(s.hasIndices="d");for(var n in s)r(n,s[n]);var o=Object.getOwnPropertyDescriptor(TS.prototype,"flags").get.call(e);return o!==i||t!==i});IS.exports={correct:PM}});var xS=g((nq,wS)=>{"use strict";var kM=Lt();wS.exports=function(){var a=kM(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var AS=g((oq,kS)=>{"use strict";var AM=st(),RM=Et(),MM=ra(),PS=ES(),$M=xS(),CM=RegExp.prototype;kS.exports=PS.correct?function(a){return a.flags}:function(a){return!PS.correct&&MM(CM,a)&&!RM(a,"flags")?AM($M,a):a.flags}});var MS=g((uq,RS)=>{"use strict";var bl=$e(),DM=hr(),LM=Math.floor,fl=bl("".charAt),BM=bl("".replace),ml=bl("".slice),VM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,_M=/\$([$&'`]|\d{1,2})/g;RS.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=_M;return r!==void 0&&(r=DM(r),u=VM),BM(s,u,function(c,d){var l;switch(fl(d,0)){case"$":return"$";case"&":return a;case"`":return ml(e,0,t);case"'":return ml(e,n);case"<":l=r[ml(d,1,-1)];break;default:var p=+d;if(p===0)return c;if(p>o){var h=LM(p/10);return h===0?c:h<=o?i[h-1]===void 0?fl(d,1):i[h-1]+fl(d,1):c}l=i[p-1]}return l===void 0?"":l})}});var DS=g(()=>{"use strict";var OM=ke(),NM=st(),vl=$e(),$S=ui(),FM=xe(),qM=Ge(),UM=yS(),Or=Ua(),jM=sa(),HM=AS(),QM=MS(),WM=Ne(),zM=It(),GM=WM("replace"),YM=TypeError,gl=vl("".indexOf),KM=vl("".replace),CS=vl("".slice),XM=Math.max;OM({target:"String",proto:!0},{replaceAll:function(e,t){var i=$S(this),r,s,n,o,u,c,d,l,p,h,m=0,b="";if(qM(e)){if(r=UM(e),r&&(s=Or($S(HM(e))),!~gl(s,"g")))throw new YM("`.replaceAll` does not allow non-global regexes");if(n=jM(e,GM),n)return NM(n,e,i,t);if(zM&&r)return KM(Or(i),e,t)}for(o=Or(i),u=Or(e),c=FM(t),c||(t=Or(t)),d=u.length,l=XM(1,d),p=gl(o,u);p!==-1;)h=c?Or(t(u,p,o)):QM(u,o,p,[],void 0,t),b+=CS(o,m,p)+h,m=p+d,p=p+l>o.length?-1:gl(o,u,p+l);return m<o.length&&(b+=CS(o,m)),b}})});var BS=g((dq,LS)=>{"use strict";gS();vS();DS();var JM=ci();LS.exports=JM("String","replaceAll")});var _S=g((pq,VS)=>{"use strict";var ZM=BS();VS.exports=ZM});var NS=g((hq,OS)=>{"use strict";var e$=_S();OS.exports=e$});var qS=g((fq,FS)=>{"use strict";var t$=ca(),i$=Ua(),r$=ui(),a$=RangeError;FS.exports=function(e){var t=i$(r$(this)),i="",r=t$(e);if(r<0||r===1/0)throw new a$("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var WS=g((mq,QS)=>{"use strict";var HS=$e(),s$=Eu(),US=Ua(),n$=qS(),o$=ui(),u$=HS(n$),c$=HS("".slice),l$=Math.ceil,jS=function(a){return function(e,t,i){var r=US(o$(e)),s=s$(t),n=r.length,o=i===void 0?" ":US(i),u,c;return s<=n||o===""?r:(u=s-n,c=u$(o,l$(u/o.length)),c.length>u&&(c=c$(c,0,u)),a?r+c:c+r)}};QS.exports={start:jS(!1),end:jS(!0)}});var GS=g((bq,zS)=>{"use strict";var d$=_i();zS.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(d$)});var YS=g(()=>{"use strict";var p$=ke(),h$=WS().start,f$=GS();p$({target:"String",proto:!0,forced:f$},{padStart:function(e){return h$(this,e,arguments.length>1?arguments[1]:void 0)}})});var XS=g((Sq,KS)=>{"use strict";YS();var m$=ci();KS.exports=m$("String","padStart")});var ZS=g((yq,JS)=>{"use strict";var b$=XS();JS.exports=b$});var ty=g((Tq,ey)=>{"use strict";var g$=ZS();ey.exports=g$});var oC={};bT(oC,{ChromecastState:()=>pr,HttpConnectionType:()=>zs,Observable:()=>qt.Observable,PlaybackState:()=>Oe,Player:()=>$s,PredefinedQualityLimits:()=>Jr,SDK_VERSION:()=>nC,Subject:()=>qt.Subject,Subscription:()=>qt.Subscription,Surface:()=>Gs,VERSION:()=>Wo,ValueSubject:()=>qt.ValueSubject,VideoFormat:()=>Ct,VideoQuality:()=>qt.VideoQuality,WebmCodecStrategy:()=>Ha,areValidLiveRecordSources:()=>af,clientChecker:()=>H,isMobile:()=>li});module.exports=gT(oC);var Wo="2.0.151-dev.6dd94264.0";var Oe=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Oe||{}),Ct=(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))(Ct||{});var pr=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(pr||{}),zs=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(zs||{});var Gs=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Gs||{}),Jr=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Jr||{});var Ql=G(Ni(),1),rT=G(Ye(),1);var ie=require("@vkontakte/videoplayer-shared/es2018");var Wh=a=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var rn=class{constructor(e){this.connection$=new ie.ValueSubject(void 0);this.castState$=new ie.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new ie.Subject;this.realCastState$=new ie.ValueSubject("NOT_AVAILABLE");this.subscription=new ie.Subscription;this.isDestroyed=!1;var s;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,ie.isNonNullable)((s=window.chrome)==null?void 0:s.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||Wh("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:ie.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,s;(s=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,ie.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,ie.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,ie.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,ie.fromEvent)(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var s,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=(s=i.getCurrentSession())==null?void 0:s.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,ie.assertNever)(r.sessionState)}})).add((0,ie.merge)((0,ie.fromEvent)(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,ie.tap)(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),(0,ie.map)(r=>r.castState)),(0,ie.observableFrom)([i.getCastState()])).pipe((0,ie.filterChanged)(),(0,ie.map)(pw),(0,ie.tap)(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let s=r==="CONNECTED",n=(0,ie.isNonNullable)(this.connection$.getValue());if(s&&!n){let c=i.getCurrentSession();(0,ie.assertNonNullable)(c);let d=c.getCastDevice(),l=(u=(o=c.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;((0,ie.isNullable)(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:c,castDevice:d}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?(0,ie.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(s){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:ie.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},pw=a=>{switch(a){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,ie.assertNever)(a)}};var ae=require("@vkontakte/videoplayer-shared/es2018");var Ce=require("@vkontakte/videoplayer-shared/es2018");var Ru=require("@vkontakte/videoplayer-shared/es2018");var Fe=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:(0,Ru.assertNever)(t)}return a},an=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(a);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(a);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:(0,Ru.assertNever)(e)}};var nn=a=>{var l;let{source:e,format:t,meta:i,output:r}=a,s,n,o;switch(t){case"MPEG":{let p=e[t];(0,Ce.assertNonNullable)(p);let h=(0,Ce.getHighestQuality)(Object.keys(p));(0,Ce.assertNonNullable)(h);let m=p[h];(0,Ce.assertNonNullable)(m),s=m,n="video/mp4",o=sn();break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let p=e[t];(0,Ce.assertNonNullable)(p),s=p.url,n="application/x-mpegurl",o=sn();break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let p=e[t];(0,Ce.assertNonNullable)(p),s=p.url,n="application/dash+xml",o=sn();break}case"DASH_LIVE_CMAF":{let p=e[t];(0,Ce.assertNonNullable)(p),s=p.url,n="application/dash+xml",o=zh();break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let p=e[t];(0,Ce.assertNonNullable)(p),s=Fe(p.url),n="application/x-mpegurl",o=zh();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:Ce.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,Ce.assertNever)(t)}let u=hw((l=i.videoId)!=null?l:s,n);u.contentUrl=s,u.streamType=o,u.metadata=fw();let{title:c,subtitle:d}=i;return(0,Ce.isNonNullable)(c)&&(u.metadata.title=c),(0,Ce.isNonNullable)(d)&&(u.metadata.subtitle=d),u};function sn(){var a,e,t,i;return(i=(t=(e=(a=chrome.cast)==null?void 0:a.media)==null?void 0:e.StreamType)==null?void 0:t.BUFFERED)!=null?i:"BUFFERED"}function zh(){var a,e,t,i;return(i=(t=(e=(a=chrome.cast)==null?void 0:a.media)==null?void 0:e.StreamType)==null?void 0:t.LIVE)!=null?i:"LIVE"}function hw(a,e){var t,i;return(i=(t=chrome.cast)==null?void 0:t.media)!=null&&i.MediaInfo?new chrome.cast.media.MediaInfo(a,e):{contentId:a,contentType:e,metadata:{title:"",subtitle:""},streamType:sn()}}function fw(){var a,e;return(e=(a=chrome.cast)==null?void 0:a.media)!=null&&e.GenericMediaMetadata?new chrome.cast.media.GenericMediaMetadata:{images:[],metadataType:0,releaseDate:"",subtitle:"",title:"",releaseYear:1970,type:0}}var B=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};var on=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 $u=require("@vkontakte/videoplayer-shared/es2018");var mn=require("@vkontakte/videoplayer-shared/es2018");var Gh=G(Ye(),1),Yh=require("@vkontakte/videoplayer-shared/es2018");var un=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isChromiumBased(){return(0,Gh.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,s=/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||s||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,Yh.getWindow)().navigator,i=t.match(e);if(!i)return;let r=i[1],s=parseInt(r,10);if(!isNaN(s))return this._current_version=s,s}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 Kh=G(Ye(),1),di=require("@vkontakte/videoplayer-shared/es2018");var li=()=>{var a,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((a=navigator.appVersion)!=null?a:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var cn=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,Kh.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,di.getWindow)();if(!(0,di.isBrowserWindow)(e))return;let{userAgent:t}=e.navigator;try{this._isMobile=li()}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,di.getWindow)();if(!(0,di.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,s=/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||s||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 s=e.match(i);if(s){let n=r.length>0,o=r.length>1,u="Unknown",c="Unknown";if(n){let d=r[0];typeof d=="number"?d<s.length&&s[d]!==void 0&&(u=s[d]):u=d}if(o){let d=r[1];typeof d=="number"?d<s.length&&s[d]!==void 0&&(c=s[d]):d!==void 0&&(c=d)}else s[2]!==void 0?c=s[2]:s[1]!==void 0&&n&&typeof r[0]=="string"&&(c=s[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 s=e.match(i);if(s){let n=r[0],o=r[1],u=typeof n=="number"?s[n]!==void 0?this.normalizeVendorName(s[n]):"Unknown":this.normalizeVendorName(n),c="Unknown";typeof o=="number"?c=s[o]!==void 0?s[o]:"Unknown":o!==void 0?c=o:s[1]!==void 0?c=s[1]:s[0]!==void 0&&(c=s[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,di.getWindow)();if(!(0,di.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 da=require("@vkontakte/videoplayer-shared/es2018"),ln=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in(0,da.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 s;let e=(0,da.getWindow)();if(!(0,da.isBrowserWindow)(e))return;let{navigator:t,screen:i}=e,{maxTouchPoints:r}=t;try{this._maxTouchPoints=r!=null?r:0,this._isHdr=!!((s=e.matchMedia("(dynamic-range: high)"))!=null&&s.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 Fi=require("@vkontakte/videoplayer-shared/es2018");var nt=()=>window.ManagedMediaSource||window.MediaSource,yr=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Xh=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},dn=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var Jh,mw=(Jh=(0,Fi.getWindow)().document)==null?void 0:Jh.createElement("video"),bw='video/mp4; codecs="avc1.42000a,mp4a.40.2"',gw='video/mp4; codecs="hev1.1.6.L93.B0"',Zh='video/webm; codecs="vp09.00.10.08"',ef='video/webm; codecs="av01.0.00M.08"',vw='audio/mp4; codecs="mp4a.40.2"',Sw='audio/webm; codecs="opus"',tf,yw=async()=>{let a=(0,Fi.getWindow)();if(!(0,Fi.isBrowserWindow)(a))return;let e={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[t,i]=await Promise.all([a.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:ef}}),a.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:Zh}})]);tf={DASH_WEBM_AV1:t,DASH_WEBM:i}};yw().catch(a=>{console.log(mw),console.error(a)});var pn=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 tf}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var i,r,s,n,o,u,c,d,l,p,h,m,b,S,v,y,x,w,M,_;let e=(0,Fi.getWindow)();if(!(0,Fi.isBrowserWindow)(e))return;let t=e.document;this._video=t.createElement("video");try{this._protocols={mms:yr(),mse:Xh(),hls:!!((r=(i=this._video).canPlayType)!=null&&r.call(i,"application/x-mpegurl")||(n=(s=this._video).canPlayType)!=null&&n.call(s,"vnd.apple.mpegURL")),webrtc:!!e.RTCPeerConnection,ws:!!e.WebSocket},this._containers={mp4:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/mp4")),webm:!!((d=(c=this._video).canPlayType)!=null&&d.call(c,"video/webm")),cmaf:!0};let F=!!((p=(l=nt())==null?void 0:l.isTypeSupported)!=null&&p.call(l,bw)),O=!!((m=(h=nt())==null?void 0:h.isTypeSupported)!=null&&m.call(h,gw)),j=!!((S=(b=nt())==null?void 0:b.isTypeSupported)!=null&&S.call(b,vw));this._codecs={h264:F,h265:O,vp9:!!((y=(v=nt())==null?void 0:v.isTypeSupported)!=null&&y.call(v,Zh)),av1:!!((w=(x=nt())==null?void 0:x.isTypeSupported)!=null&&w.call(x,ef)),aac:j,opus:!!((_=(M=nt())==null?void 0:M.isTypeSupported)!=null&&_.call(M,Sw)),mpeg:(F||O)&&j},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(F){console.error(F)}try{this.destroyVideoElement()}catch(F){console.error("Error destroying video element:",F)}}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 fn=require("@vkontakte/videoplayer-shared/es2018");var rf="audio/mpeg",hn=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var i,r,s,n;let e=(0,fn.getWindow)();if(!(0,fn.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,rf))},this._codecs={mp3:!!((n=(s=nt())==null?void 0:s.isTypeSupported)!=null&&n.call(s,rf))}}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 Mu=class{constructor(){this.isInited$=new mn.ValueSubject(!1);this._displayChecker=new ln,this._deviceChecker=new cn(this._displayChecker),this._browserChecker=new un,this._videoChecker=new pn(this._deviceChecker,this._browserChecker),this._audioChecker=new hn,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,mn.isBrowserWindow)()&&(this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0))}},H=new Mu;var Cu=a=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=H.video,s=(i.h264||i.h265)&&i.aac,n=t.mse||t.mms;return a.filter(o=>{switch(o){case"DASH_SEP":return n&&e.mp4&&s;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&&s||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return n&&e.mp4&&s;case"DASH_LIVE_CMAF":return n&&e.mp4&&s&&e.cmaf;case"DASH_ONDEMAND":return n&&e.mp4&&s;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,$u.assertNever)(o)}})},pa=a=>{switch(a){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,$u.assertNever)(a)}},af=a=>{let t=Object.keys(a).filter(i=>!pa(i));return Cu(t).length>0};var ha=class{constructor(e){this.subscription=new ae.Subscription;this.sessionId$=new ae.ValueSubject(null);this.mediaSessionId$=new ae.ValueSubject(null);this.contentId$=new ae.ValueSubject(null);this.isMobile=li();this.mobileVolumeState={muted:!1,volume:0};this.media=null;this.lastRequestedVolume=null;this.syncMediaState=e=>{var s,n,o;if((0,ae.isNullable)(e))return;this.media=e,this.mediaSessionId$.next((s=e.mediaSessionId)!=null?s: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,ae.isNonNullable)(i)&&this.params.output.duration$.next(Math.max(0,i));let r=e.currentTime;if((0,ae.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 on(e),this.log=this.params.dependencies.logger.createComponentLog("ChromecastPresentationApiProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(pa(e.format)),this.subscribe()}subscribe(){let e=r=>{var s;this.params.output.error$.next({category:ae.ErrorCategory.WTF,id:"ChromecastPresentationApiProvider",message:(s=r==null?void 0:r.message)!=null?s:"Unknown error",thrown:r})};this.subscription.add(this.params.chromecastConnector.message$.pipe((0,ae.filter)(r=>!!r)).subscribe(r=>{this.handleMessage(r)},e)),this.subscription.add(this.sessionId$.pipe((0,ae.filter)(ae.isNonNullable),(0,ae.filterChanged)(),(0,ae.debounce)(0)).subscribe(()=>{this.loadMedia()},e));let t=this.contentId$.pipe((0,ae.filterChanged)(),(0,ae.map)(Boolean));this.subscription.add((0,ae.combine)({seekState:this.params.desiredState.seekState.stateChangeEnded$,mediaLoaded:t}).pipe((0,ae.filter)(({mediaLoaded:r})=>r)).subscribe(()=>{let r=this.params.desiredState.seekState.getState();r.state==="requested"&&this.seek(r.position/1e3)},e));let i=(0,ae.combine)({playbackState:this.params.desiredState.playbackState.stateChangeStarted$,mediaLoaded:t});this.subscription.add(i.pipe((0,ae.filter)(({mediaLoaded:r})=>r),(0,ae.debounce)(0)).subscribe(()=>{this.syncPlayback()},e)),this.subscription.add(i.pipe((0,ae.filter)(({mediaLoaded:r,playbackState:{from:s,to:n}})=>!r&&s==="stopped"&&n==="playing")).subscribe(()=>{this.loadMedia()},e)),this.subscription.add((0,ae.combine)({volumeState:this.params.desiredState.volume.stateChangeStarted$.pipe((0,ae.debounce)(30)),mediaLoaded:t}).pipe((0,ae.filter)(({mediaLoaded:r})=>r)).subscribe(({volumeState:r})=>{let{muted:s,volume:n}=r.to;this.setVolume(n,s)},e))}handleMessage(e){var t,i,r,s,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((s=e.message)==null?void 0:s.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=nn(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,ae.assertNonNullable)(e,"play on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PLAY",mediaSessionId:e,customData:null})}pause(){let e=this.mediaSessionId$.getValue();(0,ae.assertNonNullable)(e,"pause on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PAUSE",mediaSessionId:e,customData:null})}seek(e){let t=this.mediaSessionId$.getValue();(0,ae.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,ae.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 s=`[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,s+=`, volume passed to state machine: ${r.volume}`),this.log({message:s}),this.params.output.volume$.next(r)}destroy(){this.progressTicker.destroy(),this.subscription.unsubscribe()}};var pe=require("@vkontakte/videoplayer-shared/es2018");var sf=a=>({castDevice:{friendlyName:a},remotePlayer:{},remotePlayerController:{},session:{}}),nf=()=>String(Date.now())+String(Math.floor(Math.random()*1e5));var fa=class{constructor(e){this.capabilities=["WEB"];this.presentationRequest$=new pe.ValueSubject(null);this.sessionId$=new pe.ValueSubject(null);this.broadcastChannel=new BroadcastChannel("vk_player_chromecast_events");this.subscription=new pe.Subscription;this.subscriptionEvents=new pe.Subscription;this.isDestroyed=!1;this.sequenceNumber=0;this.presentationAvailable$=new pe.ValueSubject(!1);this.presentationConnection$=new pe.ValueSubject(null);this.message$=new pe.ValueSubject(null);this.friendlyName$=new pe.ValueSubject(null);this.errorEvent$=new pe.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 s=()=>{this.log({message:`PresentationRequest presentation availability: ${r.value}`}),this.presentationAvailable$.next(r.value)};this.subscriptionEvents.add((0,pe.fromEvent)(r,"change").subscribe(()=>{s()})),s()}).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,pe.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:pe.ErrorCategory.WTF,id:"ChromecastPresentationApiConnector",message:(e=t==null?void 0:t.message)!=null?e:"connect error",thrown:t});break}}}subscribe(){this.subscription.add((0,pe.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,pe.tap)(e=>{this.log({message:`presentationConnection$: ${!!e}`})}),(0,pe.filter)(e=>!!e)).subscribe(e=>{let t=(0,pe.fromEvent)(e,"message").subscribe(s=>{let n=JSON.parse(s.data);n.clientId===this.clientId&&(this.log({message:`[onmessage] ${s.data}`}),this.handleMessage(n),this.message$.next(n))}),i=(0,pe.fromEvent)(e,"connect").subscribe(()=>{this.send("client_connect")}),r=(0,pe.fromEvent)(e,"close").subscribe(s=>{switch(s.reason){case"error":this.errorEvent$.next({category:pe.ErrorCategory.WTF,id:"ChromecastPresentationApiConnector",message:"Session error",thrown:s});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:pe.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]||nf()}resetSubscriptionEvents(){this.subscriptionEvents.unsubscribe(),this.subscriptionEvents=new pe.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 qe=require("@vkontakte/videoplayer-shared/es2018");var Wt=class a{constructor(e){this.subscription=new qe.Subscription;this.connection$=new qe.ValueSubject(void 0);this.castState$=new qe.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new qe.Subject;let t=a.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 fa({appId:e.receiverApplicationId,logger:e.dependencies.logger}),this.subscribe())}static isSupported(){return"chrome"in window&&"presentation"in navigator&&"BroadcastChannel"in window}subscribe(){(0,qe.assertNonNullable)(this.chromecastConnector,"subscribe with null chromecastConnector"),this.subscription.add(this.chromecastConnector.errorEvent$.subscribe(this.errorEvent$));let e=(0,qe.combine)({connection:this.chromecastConnector.presentationConnection$,available:this.chromecastConnector.presentationAvailable$,friendlyName:this.chromecastConnector.friendlyName$.pipe((0,qe.filterChanged)())});this.subscription.add(e.pipe((0,qe.map)(({connection:t,friendlyName:i})=>!!(t&&i)),(0,qe.filterChanged)()).subscribe(t=>{var r,s;let i=(s=(r=this.chromecastConnector)==null?void 0:r.friendlyName$.getValue())!=null?s:"";this.connection$.next(t?sf(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 Fl=G(Ye(),1),ql=G(pi(),1),Hy=G(ec(),1);var Ng=G(Fc(),1);var Vt=require("@vkontakte/videoplayer-shared/es2018"),re=class{constructor(e){this.transitionStarted$=new Vt.Subject;this.transitionEnded$=new Vt.Subject;this.transitionUpdated$=new Vt.Subject;this.forceChanged$=new Vt.Subject;this.stateChangeStarted$=(0,Vt.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,Vt.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,Vt.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 oe=require("@vkontakte/videoplayer-shared/es2018");var nR=5,oR=5,uR=500,Og=7e3,ka=class{constructor(e){this.subscription=new oe.Subscription;this.loadMediaTimeoutSubscription=new oe.Subscription;this.videoState=new re("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,oe.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,oe.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,oe.assertNever)(e)}break}default:(0,oe.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(pa(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 oe.Subscription;this.subscription.add(e),this.subscription.add((0,oe.merge)(this.videoState.stateChangeStarted$.pipe((0,oe.map)(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe((0,oe.map)(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new oe.Subject;e.add(r.pipe((0,oe.debounce)(uR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,oe.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>nR)&&r.next(o),s=o})),e.add((0,oe.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,oe.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,oe.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,oe.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=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()&&s.duration-s.currentTime<oR&&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,oe.assertNever)(n)}}),t((0,oe.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t((0,oe.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=(0,oe.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,oe.observableFrom)(["init"])).pipe((0,oe.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=nn(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,s;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(s=e.muted)!=null?s: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,s)=>{this.loadMediaTimeoutSubscription.add((0,oe.timeout)(Og).subscribe(()=>s(`timeout(${Og})`)))});(0,Ng.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 s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:oe.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var tl=G(Ye(),1);var Aa=require("@vkontakte/videoplayer-shared/es2018");var Fg=require("@vkontakte/videoplayer-shared/es2018"),qg=a=>{try{a.pause(),a.playbackRate=0,(0,Fg.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var qn=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)}},Fn=(0,Aa.getWindow)(),Uc=Fn.WeakMap?new Fn.WeakMap:new qc,jc=Fn.WeakMap?new Fn.WeakMap:new Map,cR=(a,e=20)=>{let t=0;return(0,qn.fromEvent)(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Ke=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?(0,Aa.clearVideoElement)(i):(i=document.createElement("video"),a.appendChild(i)),Uc.set(i,r);let s=new qn.Subscription;return s.add(cR(i,e)),jc.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},Xe=a=>{let e=jc.get(a);e==null||e.unsubscribe(),jc.delete(a);let t=Uc.get(a);Uc.delete(a),t?(0,Aa.clearVideoElement)(a):qg(a)};var Hc=G(Ni(),1),z=require("@vkontakte/videoplayer-shared/es2018");var fi=require("@vkontakte/videoplayer-shared/es2018"),Un=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=(0,fi.isNullable)(r),c=new fi.Subscription;return r&&c.add(r.subscribe(d=>{let l=a.getState();i(d,l)&&a.setState(d)},s)),i(o,n)||(t(n),u&&a.setState(n)),c.add(a.stateChangeStarted$.subscribe(d=>{t(d.to),u&&a.setState(d.to)},s)),c},_t=(a,e,t)=>Un(e,()=>a.loop,i=>{(0,fi.isNonNullable)(i)&&(a.loop=i)},{onError:t}),Je=(a,e,t,i)=>Un(e,()=>({muted:a.muted,volume:a.volume}),r=>{(0,fi.isNonNullable)(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||(r==null?void 0:r.muted)===(s==null?void 0:s.muted)&&(r==null?void 0:r.volume)===(s==null?void 0:s.volume),changed$:t,onError:i}),pt=(a,e,t,i)=>Un(e,()=>a.playbackRate,r=>{(0,fi.isNonNullable)(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),Ra=Un;var lR=a=>["__",a.language,a.label].join("|"),dR=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},Qc=class a{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=s=>{this.error$.next({id:"TextTracksManager",category:z.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Ra(t.internalTextTracks,()=>(0,Hc.default)(this.internalTracks),s=>{(0,z.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,z.isNonNullable)(s)&&(0,z.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,z.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Ra(t.externalTextTracks,()=>(0,Hc.default)(this.externalTracks),s=>{(0,z.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,z.isNonNullable)(s)&&(0,z.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,z.map)(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Ra(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:r})),this.subscription.add(Ra(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.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:s},n)=>s===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,s;return this.applyCueSettings((s=(r=i.target)==null?void 0:r.activeCues)!=null?s:null)};this.subscription.add((0,z.fromEvent)(e,"addtrack").subscribe(i=>{var s,n;(s=i.track)==null||s.addEventListener("cuechange",t);let r=o=>{var c,d,l,p,h;let u=(d=(c=o.target)==null?void 0:c.cues)!=null?d:null;u&&u.length&&(this.applyCueSettings((p=(l=o.target)==null?void 0:l.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(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,c,d,l;let{language:t,label:i}=e,r=e.id?e.id:lR(e),s=this.externalTracks.has(r),n=(c=s?(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 s?{id:r,type:"external",isAuto:n,language:t,label:i,url:(d=this.externalTracks.get(r))==null?void 0:d.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(l=this.internalTracks.get(r))==null?void 0:l.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:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===s)).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)||!dR(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)}},ht=Qc;var Wi=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 Ug=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},Wc=a=>{let e=Ug(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},jg=a=>{let e=Ug(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var C=require("@vkontakte/videoplayer-shared/es2018");var pR=3,Hg=(a,e,t=pR)=>{let i=0,r=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=s-1;u>=0;u--)a.end(u)+t>=i&&(i=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=r&&(r=a.end(u))}}return{from:i,to:r}};var Ze=a=>{let e=V=>(0,C.fromEvent)(a,V).pipe((0,C.mapTo)(void 0),(0,C.shareReplay)(1)),t=new C.Subscription,i=()=>t.unsubscribe(),r=(0,C.merge)((0,C.fromEvent)(a,"progress"),(0,C.fromEvent)(a,"timeupdate")).pipe((0,C.map)(()=>Hg(a.buffered,a.currentTime)),(0,C.shareReplay)(1)),s=H.browser.isSafari?(0,C.combine)({play:e("play").pipe((0,C.once)()),playing:e("playing")}).pipe((0,C.mapTo)(void 0),(0,C.shareReplay)(1)):e("playing"),n=(0,C.fromEvent)(a,"volumechange").pipe((0,C.map)(()=>({muted:a.muted,volume:a.volume})),(0,C.shareReplay)(1)),o=(0,C.fromEvent)(a,"ratechange").pipe((0,C.map)(()=>a.playbackRate),(0,C.shareReplay)(1)),u=(0,C.fromEvent)(a,"error").pipe((0,C.filter)(()=>!!(a.error||a.played.length)),(0,C.map)(()=>{var W;let V=a.error;return{id:V?`MediaError#${V.code}`:"HtmlVideoError",category:C.ErrorCategory.VIDEO_PIPELINE,message:V?V.message:"Error event from HTML video element",thrown:(W=a.error)!=null?W:void 0}}),(0,C.shareReplay)(1)),c=(0,C.fromEvent)(a,"timeupdate").pipe((0,C.map)(()=>a.currentTime),(0,C.shareReplay)(1)),d=["waiting","seeking","seeked","timeupdate"],l=new C.Subject,p=.3,h;t.add((0,C.merge)(...d.map(V=>(0,C.fromEvent)(a,V))).subscribe(V=>{let W=a.currentTime;a.loop&&(0,C.isNonNullable)(h)&&(0,C.isNonNullable)(W)&&h>=a.duration-p&&W<=p&&l.next(h),h=W}));let m=e("pause").pipe((0,C.filter)(()=>!a.error&&h!==a.duration),(0,C.shareReplay)(1)),b=(0,C.fromEvent)(a,"enterpictureinpicture").pipe((0,C.shareReplay)(1)),S=(0,C.fromEvent)(a,"leavepictureinpicture").pipe((0,C.shareReplay)(1)),v=new C.ValueSubject(jg(a));t.add(b.subscribe(()=>v.next(!0))),t.add(S.subscribe(()=>v.next(!1)));let y=new C.ValueSubject(Wc(a)),x=(0,C.fromEvent)(a,"fullscreenchange").pipe((0,C.shareReplay)(1));t.add(x.pipe((0,C.map)(()=>Wc(a))).subscribe(y));let w=.1,M=1e3,_=(0,C.fromEvent)(a,"timeupdate").pipe((0,C.map)(V=>a.duration-a.currentTime<w),(0,C.filterChanged)(),(0,C.shareReplay)(1)),F=(0,C.merge)(_.pipe((0,C.filter)(V=>!a.loop&&V)),(0,C.fromEvent)(a,"ended")).pipe((0,C.throttle)(M),(0,C.mapTo)(void 0),(0,C.shareReplay)(1)),j=(0,C.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(V=>(0,C.fromEvent)(a,V)),_.pipe((0,C.map)(V=>({type:V?"ended":"unknown"})))).pipe((0,C.map)(V=>H.browser.isFirefox&&V.type==="ended"?a.readyState<2:a.readyState<3),(0,C.filterChanged)(),(0,C.shareReplay)(1));return{playing$:s,pause$:m,canplay$:e("canplay"),ended$:F,looped$:l,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:(0,C.fromEvent)(a,"durationchange").pipe((0,C.map)(()=>a.duration),(0,C.shareReplay)(1)),isBuffering$:j,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:v,inFullscreen$:y,enterPip$:b,leavePip$:S,destroy:i}};var Gt=require("@vkontakte/videoplayer-shared/es2018"),mi=a=>{switch(a){case"mobile":return Gt.VideoQuality.Q_144P;case"lowest":return Gt.VideoQuality.Q_240P;case"low":return Gt.VideoQuality.Q_360P;case"sd":case"medium":return Gt.VideoQuality.Q_480P;case"hd":case"high":return Gt.VideoQuality.Q_720P;case"fullhd":case"full":return Gt.VideoQuality.Q_1080P;case"quadhd":case"quad":return Gt.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return Gt.VideoQuality.Q_2160P}};var Qe=G(ft(),1),Gc=G(Ye(),1),zi=G(pi(),1),L=require("@vkontakte/videoplayer-shared/es2018");var zc=!1,Yt={},Xg=a=>{zc=a},Jg=()=>{Yt={}},Zg=a=>{a(Yt)},Ma=(a,e)=>{var t;zc&&(Yt.meta=(t=Yt.meta)!=null?t:{},Yt.meta[a]=e)},He=class{constructor(e){this.name=e}next(e){var i,r;if(!zc)return;Yt.series=(i=Yt.series)!=null?i:{};let t=(r=Yt.series[this.name])!=null?r:[];t.push([Date.now(),e]),Yt.series[this.name]=t}};var Ae=require("@vkontakte/videoplayer-shared/es2018");function ev(a,e,t){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function Mr(a,e,t){return(0,Ae.isNullable)(a)||(0,Ae.isNonNullable)(a.min)&&(0,Ae.isNonNullable)(a.max)&&(0,Ae.isLower)(a.max,a.min)||(0,Ae.isNonNullable)(a.min)&&e&&(0,Ae.isHigher)(a.min,e)||(0,Ae.isNonNullable)(a.max)&&t&&(0,Ae.isLower)(a.max,t)}function tv({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return Mr({max:a!=null&&a.max?(0,Ae.videoHeightToQuality)(a.max):void 0,min:a!=null&&a.min?(0,Ae.videoHeightToQuality)(a.min):void 0},e?(0,Ae.videoHeightToQuality)(e):void 0,t?(0,Ae.videoHeightToQuality)(t):void 0)}var nv=new He("best_bitrate"),Hn=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var $r=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),bi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,L.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Qn='Assertion "ABR Tracks is empty array" failed',jn=new WeakMap,iv=new WeakMap,rv=new WeakMap,$a=(a,e,t,i)=>{var u;let r=[...e].sort($r(1)),s=[...t].sort($r(1)),n=s.filter(c=>(0,L.isNonNullable)(c.bitrate)&&(0,L.isNonNullable)(a.bitrate)?a.bitrate/c.bitrate>i:!0),o=(u=(0,Qe.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Qe.default)(s,-1);return o&&(0,Gc.default)(n,o)?o:n.length?(0,Qe.default)(n,-1):(0,Qe.default)(s,0)},Ca=(a,e,t,i)=>{var u;let r=jn.get(e);r||(r=[...e].sort($r(1)),jn.set(e,r));let s=jn.get(t);s||(s=[...t].sort($r(1)),jn.set(t,s));let n=rv.get(a);n||(n=s.filter(c=>(0,L.isNonNullable)(c.bitrate)&&(0,L.isNonNullable)(a.bitrate)?a.bitrate/c.bitrate>i:!0),rv.set(a,n));let o=(u=(0,Qe.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Qe.default)(s,-1);return o&&(0,Gc.default)(n,o)?o:n.length?(0,Qe.default)(n,-1):(0,Qe.default)(s,0)},av=a=>"quality"in a,Wn=(a,e,t,i)=>{var n;let r=(0,L.isNonNullable)((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&(0,L.isNonNullable)(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&(0,L.now)()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!s&&i.recordSelection(t),s&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=av(o)?"video":"audio",c=av(o)?o.quality:o.bitrate;return e({message:`
7
+ \v\f\r                 \u2028\u2029\uFEFF`});var eS=g((fF,Zv)=>{"use strict";var nM=$e(),oM=ui(),uM=Ua(),dl=cl(),Jv=nM("".replace),cM=RegExp("^["+dl+"]+"),lM=RegExp("(^|[^"+dl+"])["+dl+"]+$"),ll=function(a){return function(e){var t=uM(oM(e));return a&1&&(t=Jv(t,cM,"")),a&2&&(t=Jv(t,lM,"$1")),t}};Zv.exports={start:ll(1),end:ll(2),trim:ll(3)}});var aS=g((mF,rS)=>{"use strict";var dM=Nu().PROPER,pM=Me(),tS=cl(),iS="​…᠎";rS.exports=function(a){return pM(function(){return!!tS[a]()||iS[a]()!==iS||dM&&tS[a].name!==a})}});var pl=g((bF,sS)=>{"use strict";var hM=eS().start,fM=aS();sS.exports=fM("trimStart")?function(){return hM(this)}:"".trimStart});var oS=g(()=>{"use strict";var mM=ke(),nS=pl();mM({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==nS},{trimLeft:nS})});var cS=g(()=>{"use strict";oS();var bM=ke(),uS=pl();bM({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==uS},{trimStart:uS})});var dS=g((TF,lS)=>{"use strict";cS();var gM=ci();lS.exports=gM("String","trimLeft")});var hS=g((IF,pS)=>{"use strict";var vM=dS();pS.exports=vM});var mS=g((EF,fS)=>{"use strict";var SM=hS();fS.exports=SM});var gS=g(()=>{"use strict"});var vS=g(()=>{"use strict"});var yS=g((aq,SS)=>{"use strict";var yM=Ge(),TM=Li(),IM=Ne(),EM=IM("match");SS.exports=function(a){var e;return yM(a)&&((e=a[EM])!==void 0?!!e:TM(a)==="RegExp")}});var ES=g((sq,IS)=>{"use strict";var wM=we(),xM=Me(),TS=wM.RegExp,PM=!xM(function(){var a=!0;try{TS(".","d")}catch(u){a=!1}var e={},t="",i=a?"dgimsy":"gimsy",r=function(u,c){Object.defineProperty(e,u,{get:function(){return t+=c,!0}})},s={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};a&&(s.hasIndices="d");for(var n in s)r(n,s[n]);var o=Object.getOwnPropertyDescriptor(TS.prototype,"flags").get.call(e);return o!==i||t!==i});IS.exports={correct:PM}});var xS=g((nq,wS)=>{"use strict";var kM=Lt();wS.exports=function(){var a=kM(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var AS=g((oq,kS)=>{"use strict";var AM=st(),RM=Et(),MM=ra(),PS=ES(),$M=xS(),CM=RegExp.prototype;kS.exports=PS.correct?function(a){return a.flags}:function(a){return!PS.correct&&MM(CM,a)&&!RM(a,"flags")?AM($M,a):a.flags}});var MS=g((uq,RS)=>{"use strict";var bl=$e(),DM=hr(),LM=Math.floor,fl=bl("".charAt),BM=bl("".replace),ml=bl("".slice),VM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,_M=/\$([$&'`]|\d{1,2})/g;RS.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=_M;return r!==void 0&&(r=DM(r),u=VM),BM(s,u,function(c,d){var l;switch(fl(d,0)){case"$":return"$";case"&":return a;case"`":return ml(e,0,t);case"'":return ml(e,n);case"<":l=r[ml(d,1,-1)];break;default:var p=+d;if(p===0)return c;if(p>o){var h=LM(p/10);return h===0?c:h<=o?i[h-1]===void 0?fl(d,1):i[h-1]+fl(d,1):c}l=i[p-1]}return l===void 0?"":l})}});var DS=g(()=>{"use strict";var OM=ke(),NM=st(),vl=$e(),$S=ui(),FM=xe(),qM=Ge(),UM=yS(),Or=Ua(),jM=sa(),HM=AS(),QM=MS(),WM=Ne(),zM=It(),GM=WM("replace"),YM=TypeError,gl=vl("".indexOf),KM=vl("".replace),CS=vl("".slice),XM=Math.max;OM({target:"String",proto:!0},{replaceAll:function(e,t){var i=$S(this),r,s,n,o,u,c,d,l,p,h,m=0,b="";if(qM(e)){if(r=UM(e),r&&(s=Or($S(HM(e))),!~gl(s,"g")))throw new YM("`.replaceAll` does not allow non-global regexes");if(n=jM(e,GM),n)return NM(n,e,i,t);if(zM&&r)return KM(Or(i),e,t)}for(o=Or(i),u=Or(e),c=FM(t),c||(t=Or(t)),d=u.length,l=XM(1,d),p=gl(o,u);p!==-1;)h=c?Or(t(u,p,o)):QM(u,o,p,[],void 0,t),b+=CS(o,m,p)+h,m=p+d,p=p+l>o.length?-1:gl(o,u,p+l);return m<o.length&&(b+=CS(o,m)),b}})});var BS=g((dq,LS)=>{"use strict";gS();vS();DS();var JM=ci();LS.exports=JM("String","replaceAll")});var _S=g((pq,VS)=>{"use strict";var ZM=BS();VS.exports=ZM});var NS=g((hq,OS)=>{"use strict";var e$=_S();OS.exports=e$});var qS=g((fq,FS)=>{"use strict";var t$=ca(),i$=Ua(),r$=ui(),a$=RangeError;FS.exports=function(e){var t=i$(r$(this)),i="",r=t$(e);if(r<0||r===1/0)throw new a$("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var WS=g((mq,QS)=>{"use strict";var HS=$e(),s$=Eu(),US=Ua(),n$=qS(),o$=ui(),u$=HS(n$),c$=HS("".slice),l$=Math.ceil,jS=function(a){return function(e,t,i){var r=US(o$(e)),s=s$(t),n=r.length,o=i===void 0?" ":US(i),u,c;return s<=n||o===""?r:(u=s-n,c=u$(o,l$(u/o.length)),c.length>u&&(c=c$(c,0,u)),a?r+c:c+r)}};QS.exports={start:jS(!1),end:jS(!0)}});var GS=g((bq,zS)=>{"use strict";var d$=_i();zS.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(d$)});var YS=g(()=>{"use strict";var p$=ke(),h$=WS().start,f$=GS();p$({target:"String",proto:!0,forced:f$},{padStart:function(e){return h$(this,e,arguments.length>1?arguments[1]:void 0)}})});var XS=g((Sq,KS)=>{"use strict";YS();var m$=ci();KS.exports=m$("String","padStart")});var ZS=g((yq,JS)=>{"use strict";var b$=XS();JS.exports=b$});var ty=g((Tq,ey)=>{"use strict";var g$=ZS();ey.exports=g$});var oC={};bT(oC,{ChromecastState:()=>pr,HttpConnectionType:()=>zs,Observable:()=>qt.Observable,PlaybackState:()=>Oe,Player:()=>$s,PredefinedQualityLimits:()=>Jr,SDK_VERSION:()=>nC,Subject:()=>qt.Subject,Subscription:()=>qt.Subscription,Surface:()=>Gs,VERSION:()=>Wo,ValueSubject:()=>qt.ValueSubject,VideoFormat:()=>Ct,VideoQuality:()=>qt.VideoQuality,WebmCodecStrategy:()=>Ha,areValidLiveRecordSources:()=>af,clientChecker:()=>H,isMobile:()=>li});module.exports=gT(oC);var Wo="2.0.151-dev.96546ef5.0";var Oe=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Oe||{}),Ct=(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))(Ct||{});var pr=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(pr||{}),zs=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(zs||{});var Gs=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Gs||{}),Jr=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Jr||{});var Ql=G(Ni(),1),rT=G(Ye(),1);var ie=require("@vkontakte/videoplayer-shared/es2018");var Wh=a=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var rn=class{constructor(e){this.connection$=new ie.ValueSubject(void 0);this.castState$=new ie.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new ie.Subject;this.realCastState$=new ie.ValueSubject("NOT_AVAILABLE");this.subscription=new ie.Subscription;this.isDestroyed=!1;var s;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,ie.isNonNullable)((s=window.chrome)==null?void 0:s.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||Wh("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:ie.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,s;(s=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,ie.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,ie.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,ie.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,ie.fromEvent)(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var s,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=(s=i.getCurrentSession())==null?void 0:s.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,ie.assertNever)(r.sessionState)}})).add((0,ie.merge)((0,ie.fromEvent)(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,ie.tap)(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),(0,ie.map)(r=>r.castState)),(0,ie.observableFrom)([i.getCastState()])).pipe((0,ie.filterChanged)(),(0,ie.map)(pw),(0,ie.tap)(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let s=r==="CONNECTED",n=(0,ie.isNonNullable)(this.connection$.getValue());if(s&&!n){let c=i.getCurrentSession();(0,ie.assertNonNullable)(c);let d=c.getCastDevice(),l=(u=(o=c.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;((0,ie.isNullable)(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:c,castDevice:d}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?(0,ie.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(s){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:ie.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},pw=a=>{switch(a){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,ie.assertNever)(a)}};var ae=require("@vkontakte/videoplayer-shared/es2018");var Ce=require("@vkontakte/videoplayer-shared/es2018");var Ru=require("@vkontakte/videoplayer-shared/es2018");var Fe=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:(0,Ru.assertNever)(t)}return a},an=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(a);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(a);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:(0,Ru.assertNever)(e)}};var nn=a=>{var l;let{source:e,format:t,meta:i,output:r}=a,s,n,o;switch(t){case"MPEG":{let p=e[t];(0,Ce.assertNonNullable)(p);let h=(0,Ce.getHighestQuality)(Object.keys(p));(0,Ce.assertNonNullable)(h);let m=p[h];(0,Ce.assertNonNullable)(m),s=m,n="video/mp4",o=sn();break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let p=e[t];(0,Ce.assertNonNullable)(p),s=p.url,n="application/x-mpegurl",o=sn();break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let p=e[t];(0,Ce.assertNonNullable)(p),s=p.url,n="application/dash+xml",o=sn();break}case"DASH_LIVE_CMAF":{let p=e[t];(0,Ce.assertNonNullable)(p),s=p.url,n="application/dash+xml",o=zh();break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let p=e[t];(0,Ce.assertNonNullable)(p),s=Fe(p.url),n="application/x-mpegurl",o=zh();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:Ce.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,Ce.assertNever)(t)}let u=hw((l=i.videoId)!=null?l:s,n);u.contentUrl=s,u.streamType=o,u.metadata=fw();let{title:c,subtitle:d}=i;return(0,Ce.isNonNullable)(c)&&(u.metadata.title=c),(0,Ce.isNonNullable)(d)&&(u.metadata.subtitle=d),u};function sn(){var a,e,t,i;return(i=(t=(e=(a=chrome.cast)==null?void 0:a.media)==null?void 0:e.StreamType)==null?void 0:t.BUFFERED)!=null?i:"BUFFERED"}function zh(){var a,e,t,i;return(i=(t=(e=(a=chrome.cast)==null?void 0:a.media)==null?void 0:e.StreamType)==null?void 0:t.LIVE)!=null?i:"LIVE"}function hw(a,e){var t,i;return(i=(t=chrome.cast)==null?void 0:t.media)!=null&&i.MediaInfo?new chrome.cast.media.MediaInfo(a,e):{contentId:a,contentType:e,metadata:{title:"",subtitle:""},streamType:sn()}}function fw(){var a,e;return(e=(a=chrome.cast)==null?void 0:a.media)!=null&&e.GenericMediaMetadata?new chrome.cast.media.GenericMediaMetadata:{images:[],metadataType:0,releaseDate:"",subtitle:"",title:"",releaseYear:1970,type:0}}var B=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};var on=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 $u=require("@vkontakte/videoplayer-shared/es2018");var mn=require("@vkontakte/videoplayer-shared/es2018");var Gh=G(Ye(),1),Yh=require("@vkontakte/videoplayer-shared/es2018");var un=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isChromiumBased(){return(0,Gh.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,s=/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||s||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,Yh.getWindow)().navigator,i=t.match(e);if(!i)return;let r=i[1],s=parseInt(r,10);if(!isNaN(s))return this._current_version=s,s}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 Kh=G(Ye(),1),di=require("@vkontakte/videoplayer-shared/es2018");var li=()=>{var a,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((a=navigator.appVersion)!=null?a:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var cn=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,Kh.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,di.getWindow)();if(!(0,di.isBrowserWindow)(e))return;let{userAgent:t}=e.navigator;try{this._isMobile=li()}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,di.getWindow)();if(!(0,di.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,s=/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||s||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 s=e.match(i);if(s){let n=r.length>0,o=r.length>1,u="Unknown",c="Unknown";if(n){let d=r[0];typeof d=="number"?d<s.length&&s[d]!==void 0&&(u=s[d]):u=d}if(o){let d=r[1];typeof d=="number"?d<s.length&&s[d]!==void 0&&(c=s[d]):d!==void 0&&(c=d)}else s[2]!==void 0?c=s[2]:s[1]!==void 0&&n&&typeof r[0]=="string"&&(c=s[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 s=e.match(i);if(s){let n=r[0],o=r[1],u=typeof n=="number"?s[n]!==void 0?this.normalizeVendorName(s[n]):"Unknown":this.normalizeVendorName(n),c="Unknown";typeof o=="number"?c=s[o]!==void 0?s[o]:"Unknown":o!==void 0?c=o:s[1]!==void 0?c=s[1]:s[0]!==void 0&&(c=s[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,di.getWindow)();if(!(0,di.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 da=require("@vkontakte/videoplayer-shared/es2018"),ln=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in(0,da.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 s;let e=(0,da.getWindow)();if(!(0,da.isBrowserWindow)(e))return;let{navigator:t,screen:i}=e,{maxTouchPoints:r}=t;try{this._maxTouchPoints=r!=null?r:0,this._isHdr=!!((s=e.matchMedia("(dynamic-range: high)"))!=null&&s.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 Fi=require("@vkontakte/videoplayer-shared/es2018");var nt=()=>window.ManagedMediaSource||window.MediaSource,yr=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Xh=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},dn=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var Jh,mw=(Jh=(0,Fi.getWindow)().document)==null?void 0:Jh.createElement("video"),bw='video/mp4; codecs="avc1.42000a,mp4a.40.2"',gw='video/mp4; codecs="hev1.1.6.L93.B0"',Zh='video/webm; codecs="vp09.00.10.08"',ef='video/webm; codecs="av01.0.00M.08"',vw='audio/mp4; codecs="mp4a.40.2"',Sw='audio/webm; codecs="opus"',tf,yw=async()=>{let a=(0,Fi.getWindow)();if(!(0,Fi.isBrowserWindow)(a))return;let e={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[t,i]=await Promise.all([a.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:ef}}),a.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:Zh}})]);tf={DASH_WEBM_AV1:t,DASH_WEBM:i}};yw().catch(a=>{console.log(mw),console.error(a)});var pn=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 tf}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var i,r,s,n,o,u,c,d,l,p,h,m,b,S,v,y,x,w,M,_;let e=(0,Fi.getWindow)();if(!(0,Fi.isBrowserWindow)(e))return;let t=e.document;this._video=t.createElement("video");try{this._protocols={mms:yr(),mse:Xh(),hls:!!((r=(i=this._video).canPlayType)!=null&&r.call(i,"application/x-mpegurl")||(n=(s=this._video).canPlayType)!=null&&n.call(s,"vnd.apple.mpegURL")),webrtc:!!e.RTCPeerConnection,ws:!!e.WebSocket},this._containers={mp4:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/mp4")),webm:!!((d=(c=this._video).canPlayType)!=null&&d.call(c,"video/webm")),cmaf:!0};let F=!!((p=(l=nt())==null?void 0:l.isTypeSupported)!=null&&p.call(l,bw)),O=!!((m=(h=nt())==null?void 0:h.isTypeSupported)!=null&&m.call(h,gw)),j=!!((S=(b=nt())==null?void 0:b.isTypeSupported)!=null&&S.call(b,vw));this._codecs={h264:F,h265:O,vp9:!!((y=(v=nt())==null?void 0:v.isTypeSupported)!=null&&y.call(v,Zh)),av1:!!((w=(x=nt())==null?void 0:x.isTypeSupported)!=null&&w.call(x,ef)),aac:j,opus:!!((_=(M=nt())==null?void 0:M.isTypeSupported)!=null&&_.call(M,Sw)),mpeg:(F||O)&&j},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(F){console.error(F)}try{this.destroyVideoElement()}catch(F){console.error("Error destroying video element:",F)}}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 fn=require("@vkontakte/videoplayer-shared/es2018");var rf="audio/mpeg",hn=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var i,r,s,n;let e=(0,fn.getWindow)();if(!(0,fn.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,rf))},this._codecs={mp3:!!((n=(s=nt())==null?void 0:s.isTypeSupported)!=null&&n.call(s,rf))}}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 Mu=class{constructor(){this.isInited$=new mn.ValueSubject(!1);this._displayChecker=new ln,this._deviceChecker=new cn(this._displayChecker),this._browserChecker=new un,this._videoChecker=new pn(this._deviceChecker,this._browserChecker),this._audioChecker=new hn,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,mn.isBrowserWindow)()&&(this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0))}},H=new Mu;var Cu=a=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=H.video,s=(i.h264||i.h265)&&i.aac,n=t.mse||t.mms;return a.filter(o=>{switch(o){case"DASH_SEP":return n&&e.mp4&&s;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&&s||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return n&&e.mp4&&s;case"DASH_LIVE_CMAF":return n&&e.mp4&&s&&e.cmaf;case"DASH_ONDEMAND":return n&&e.mp4&&s;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,$u.assertNever)(o)}})},pa=a=>{switch(a){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,$u.assertNever)(a)}},af=a=>{let t=Object.keys(a).filter(i=>!pa(i));return Cu(t).length>0};var ha=class{constructor(e){this.subscription=new ae.Subscription;this.sessionId$=new ae.ValueSubject(null);this.mediaSessionId$=new ae.ValueSubject(null);this.contentId$=new ae.ValueSubject(null);this.isMobile=li();this.mobileVolumeState={muted:!1,volume:0};this.media=null;this.lastRequestedVolume=null;this.syncMediaState=e=>{var s,n,o;if((0,ae.isNullable)(e))return;this.media=e,this.mediaSessionId$.next((s=e.mediaSessionId)!=null?s: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,ae.isNonNullable)(i)&&this.params.output.duration$.next(Math.max(0,i));let r=e.currentTime;if((0,ae.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 on(e),this.log=this.params.dependencies.logger.createComponentLog("ChromecastPresentationApiProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(pa(e.format)),this.subscribe()}subscribe(){let e=r=>{var s;this.params.output.error$.next({category:ae.ErrorCategory.WTF,id:"ChromecastPresentationApiProvider",message:(s=r==null?void 0:r.message)!=null?s:"Unknown error",thrown:r})};this.subscription.add(this.params.chromecastConnector.message$.pipe((0,ae.filter)(r=>!!r)).subscribe(r=>{this.handleMessage(r)},e)),this.subscription.add(this.sessionId$.pipe((0,ae.filter)(ae.isNonNullable),(0,ae.filterChanged)(),(0,ae.debounce)(0)).subscribe(()=>{this.loadMedia()},e));let t=this.contentId$.pipe((0,ae.filterChanged)(),(0,ae.map)(Boolean));this.subscription.add((0,ae.combine)({seekState:this.params.desiredState.seekState.stateChangeEnded$,mediaLoaded:t}).pipe((0,ae.filter)(({mediaLoaded:r})=>r)).subscribe(()=>{let r=this.params.desiredState.seekState.getState();r.state==="requested"&&this.seek(r.position/1e3)},e));let i=(0,ae.combine)({playbackState:this.params.desiredState.playbackState.stateChangeStarted$,mediaLoaded:t});this.subscription.add(i.pipe((0,ae.filter)(({mediaLoaded:r})=>r),(0,ae.debounce)(0)).subscribe(()=>{this.syncPlayback()},e)),this.subscription.add(i.pipe((0,ae.filter)(({mediaLoaded:r,playbackState:{from:s,to:n}})=>!r&&s==="stopped"&&n==="playing")).subscribe(()=>{this.loadMedia()},e)),this.subscription.add((0,ae.combine)({volumeState:this.params.desiredState.volume.stateChangeStarted$.pipe((0,ae.debounce)(30)),mediaLoaded:t}).pipe((0,ae.filter)(({mediaLoaded:r})=>r)).subscribe(({volumeState:r})=>{let{muted:s,volume:n}=r.to;this.setVolume(n,s)},e))}handleMessage(e){var t,i,r,s,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((s=e.message)==null?void 0:s.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=nn(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,ae.assertNonNullable)(e,"play on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PLAY",mediaSessionId:e,customData:null})}pause(){let e=this.mediaSessionId$.getValue();(0,ae.assertNonNullable)(e,"pause on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PAUSE",mediaSessionId:e,customData:null})}seek(e){let t=this.mediaSessionId$.getValue();(0,ae.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,ae.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 s=`[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,s+=`, volume passed to state machine: ${r.volume}`),this.log({message:s}),this.params.output.volume$.next(r)}destroy(){this.progressTicker.destroy(),this.subscription.unsubscribe()}};var pe=require("@vkontakte/videoplayer-shared/es2018");var sf=a=>({castDevice:{friendlyName:a},remotePlayer:{},remotePlayerController:{},session:{}}),nf=()=>String(Date.now())+String(Math.floor(Math.random()*1e5));var fa=class{constructor(e){this.capabilities=["WEB"];this.presentationRequest$=new pe.ValueSubject(null);this.sessionId$=new pe.ValueSubject(null);this.broadcastChannel=new BroadcastChannel("vk_player_chromecast_events");this.subscription=new pe.Subscription;this.subscriptionEvents=new pe.Subscription;this.isDestroyed=!1;this.sequenceNumber=0;this.presentationAvailable$=new pe.ValueSubject(!1);this.presentationConnection$=new pe.ValueSubject(null);this.message$=new pe.ValueSubject(null);this.friendlyName$=new pe.ValueSubject(null);this.errorEvent$=new pe.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 s=()=>{this.log({message:`PresentationRequest presentation availability: ${r.value}`}),this.presentationAvailable$.next(r.value)};this.subscriptionEvents.add((0,pe.fromEvent)(r,"change").subscribe(()=>{s()})),s()}).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,pe.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:pe.ErrorCategory.WTF,id:"ChromecastPresentationApiConnector",message:(e=t==null?void 0:t.message)!=null?e:"connect error",thrown:t});break}}}subscribe(){this.subscription.add((0,pe.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,pe.tap)(e=>{this.log({message:`presentationConnection$: ${!!e}`})}),(0,pe.filter)(e=>!!e)).subscribe(e=>{let t=(0,pe.fromEvent)(e,"message").subscribe(s=>{let n=JSON.parse(s.data);n.clientId===this.clientId&&(this.log({message:`[onmessage] ${s.data}`}),this.handleMessage(n),this.message$.next(n))}),i=(0,pe.fromEvent)(e,"connect").subscribe(()=>{this.send("client_connect")}),r=(0,pe.fromEvent)(e,"close").subscribe(s=>{switch(s.reason){case"error":this.errorEvent$.next({category:pe.ErrorCategory.WTF,id:"ChromecastPresentationApiConnector",message:"Session error",thrown:s});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:pe.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]||nf()}resetSubscriptionEvents(){this.subscriptionEvents.unsubscribe(),this.subscriptionEvents=new pe.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 qe=require("@vkontakte/videoplayer-shared/es2018");var Wt=class a{constructor(e){this.subscription=new qe.Subscription;this.connection$=new qe.ValueSubject(void 0);this.castState$=new qe.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new qe.Subject;let t=a.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 fa({appId:e.receiverApplicationId,logger:e.dependencies.logger}),this.subscribe())}static isSupported(){return"chrome"in window&&"presentation"in navigator&&"BroadcastChannel"in window}subscribe(){(0,qe.assertNonNullable)(this.chromecastConnector,"subscribe with null chromecastConnector"),this.subscription.add(this.chromecastConnector.errorEvent$.subscribe(this.errorEvent$));let e=(0,qe.combine)({connection:this.chromecastConnector.presentationConnection$,available:this.chromecastConnector.presentationAvailable$,friendlyName:this.chromecastConnector.friendlyName$.pipe((0,qe.filterChanged)())});this.subscription.add(e.pipe((0,qe.map)(({connection:t,friendlyName:i})=>!!(t&&i)),(0,qe.filterChanged)()).subscribe(t=>{var r,s;let i=(s=(r=this.chromecastConnector)==null?void 0:r.friendlyName$.getValue())!=null?s:"";this.connection$.next(t?sf(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 Fl=G(Ye(),1),ql=G(pi(),1),Hy=G(ec(),1);var Ng=G(Fc(),1);var Vt=require("@vkontakte/videoplayer-shared/es2018"),re=class{constructor(e){this.transitionStarted$=new Vt.Subject;this.transitionEnded$=new Vt.Subject;this.transitionUpdated$=new Vt.Subject;this.forceChanged$=new Vt.Subject;this.stateChangeStarted$=(0,Vt.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,Vt.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,Vt.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 oe=require("@vkontakte/videoplayer-shared/es2018");var nR=5,oR=5,uR=500,Og=7e3,ka=class{constructor(e){this.subscription=new oe.Subscription;this.loadMediaTimeoutSubscription=new oe.Subscription;this.videoState=new re("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,oe.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,oe.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,oe.assertNever)(e)}break}default:(0,oe.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(pa(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 oe.Subscription;this.subscription.add(e),this.subscription.add((0,oe.merge)(this.videoState.stateChangeStarted$.pipe((0,oe.map)(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe((0,oe.map)(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new oe.Subject;e.add(r.pipe((0,oe.debounce)(uR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,oe.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>nR)&&r.next(o),s=o})),e.add((0,oe.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,oe.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,oe.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,oe.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=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()&&s.duration-s.currentTime<oR&&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,oe.assertNever)(n)}}),t((0,oe.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t((0,oe.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=(0,oe.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,oe.observableFrom)(["init"])).pipe((0,oe.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=nn(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,s;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(s=e.muted)!=null?s: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,s)=>{this.loadMediaTimeoutSubscription.add((0,oe.timeout)(Og).subscribe(()=>s(`timeout(${Og})`)))});(0,Ng.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 s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:oe.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var tl=G(Ye(),1);var Aa=require("@vkontakte/videoplayer-shared/es2018");var Fg=require("@vkontakte/videoplayer-shared/es2018"),qg=a=>{try{a.pause(),a.playbackRate=0,(0,Fg.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var qn=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)}},Fn=(0,Aa.getWindow)(),Uc=Fn.WeakMap?new Fn.WeakMap:new qc,jc=Fn.WeakMap?new Fn.WeakMap:new Map,cR=(a,e=20)=>{let t=0;return(0,qn.fromEvent)(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Ke=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?(0,Aa.clearVideoElement)(i):(i=document.createElement("video"),a.appendChild(i)),Uc.set(i,r);let s=new qn.Subscription;return s.add(cR(i,e)),jc.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},Xe=a=>{let e=jc.get(a);e==null||e.unsubscribe(),jc.delete(a);let t=Uc.get(a);Uc.delete(a),t?(0,Aa.clearVideoElement)(a):qg(a)};var Hc=G(Ni(),1),z=require("@vkontakte/videoplayer-shared/es2018");var fi=require("@vkontakte/videoplayer-shared/es2018"),Un=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=(0,fi.isNullable)(r),c=new fi.Subscription;return r&&c.add(r.subscribe(d=>{let l=a.getState();i(d,l)&&a.setState(d)},s)),i(o,n)||(t(n),u&&a.setState(n)),c.add(a.stateChangeStarted$.subscribe(d=>{t(d.to),u&&a.setState(d.to)},s)),c},_t=(a,e,t)=>Un(e,()=>a.loop,i=>{(0,fi.isNonNullable)(i)&&(a.loop=i)},{onError:t}),Je=(a,e,t,i)=>Un(e,()=>({muted:a.muted,volume:a.volume}),r=>{(0,fi.isNonNullable)(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||(r==null?void 0:r.muted)===(s==null?void 0:s.muted)&&(r==null?void 0:r.volume)===(s==null?void 0:s.volume),changed$:t,onError:i}),pt=(a,e,t,i)=>Un(e,()=>a.playbackRate,r=>{(0,fi.isNonNullable)(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),Ra=Un;var lR=a=>["__",a.language,a.label].join("|"),dR=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},Qc=class a{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=s=>{this.error$.next({id:"TextTracksManager",category:z.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Ra(t.internalTextTracks,()=>(0,Hc.default)(this.internalTracks),s=>{(0,z.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,z.isNonNullable)(s)&&(0,z.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,z.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Ra(t.externalTextTracks,()=>(0,Hc.default)(this.externalTracks),s=>{(0,z.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,z.isNonNullable)(s)&&(0,z.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,z.map)(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Ra(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:r})),this.subscription.add(Ra(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.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:s},n)=>s===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,s;return this.applyCueSettings((s=(r=i.target)==null?void 0:r.activeCues)!=null?s:null)};this.subscription.add((0,z.fromEvent)(e,"addtrack").subscribe(i=>{var s,n;(s=i.track)==null||s.addEventListener("cuechange",t);let r=o=>{var c,d,l,p,h;let u=(d=(c=o.target)==null?void 0:c.cues)!=null?d:null;u&&u.length&&(this.applyCueSettings((p=(l=o.target)==null?void 0:l.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(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,c,d,l;let{language:t,label:i}=e,r=e.id?e.id:lR(e),s=this.externalTracks.has(r),n=(c=s?(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 s?{id:r,type:"external",isAuto:n,language:t,label:i,url:(d=this.externalTracks.get(r))==null?void 0:d.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(l=this.internalTracks.get(r))==null?void 0:l.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:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===s)).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)||!dR(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)}},ht=Qc;var Wi=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 Ug=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},Wc=a=>{let e=Ug(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},jg=a=>{let e=Ug(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var C=require("@vkontakte/videoplayer-shared/es2018");var pR=3,Hg=(a,e,t=pR)=>{let i=0,r=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=s-1;u>=0;u--)a.end(u)+t>=i&&(i=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=r&&(r=a.end(u))}}return{from:i,to:r}};var Ze=a=>{let e=V=>(0,C.fromEvent)(a,V).pipe((0,C.mapTo)(void 0),(0,C.shareReplay)(1)),t=new C.Subscription,i=()=>t.unsubscribe(),r=(0,C.merge)((0,C.fromEvent)(a,"progress"),(0,C.fromEvent)(a,"timeupdate")).pipe((0,C.map)(()=>Hg(a.buffered,a.currentTime)),(0,C.shareReplay)(1)),s=H.browser.isSafari?(0,C.combine)({play:e("play").pipe((0,C.once)()),playing:e("playing")}).pipe((0,C.mapTo)(void 0),(0,C.shareReplay)(1)):e("playing"),n=(0,C.fromEvent)(a,"volumechange").pipe((0,C.map)(()=>({muted:a.muted,volume:a.volume})),(0,C.shareReplay)(1)),o=(0,C.fromEvent)(a,"ratechange").pipe((0,C.map)(()=>a.playbackRate),(0,C.shareReplay)(1)),u=(0,C.fromEvent)(a,"error").pipe((0,C.filter)(()=>!!(a.error||a.played.length)),(0,C.map)(()=>{var W;let V=a.error;return{id:V?`MediaError#${V.code}`:"HtmlVideoError",category:C.ErrorCategory.VIDEO_PIPELINE,message:V?V.message:"Error event from HTML video element",thrown:(W=a.error)!=null?W:void 0}}),(0,C.shareReplay)(1)),c=(0,C.fromEvent)(a,"timeupdate").pipe((0,C.map)(()=>a.currentTime),(0,C.shareReplay)(1)),d=["waiting","seeking","seeked","timeupdate"],l=new C.Subject,p=.3,h;t.add((0,C.merge)(...d.map(V=>(0,C.fromEvent)(a,V))).subscribe(V=>{let W=a.currentTime;a.loop&&(0,C.isNonNullable)(h)&&(0,C.isNonNullable)(W)&&h>=a.duration-p&&W<=p&&l.next(h),h=W}));let m=e("pause").pipe((0,C.filter)(()=>!a.error&&h!==a.duration),(0,C.shareReplay)(1)),b=(0,C.fromEvent)(a,"enterpictureinpicture").pipe((0,C.shareReplay)(1)),S=(0,C.fromEvent)(a,"leavepictureinpicture").pipe((0,C.shareReplay)(1)),v=new C.ValueSubject(jg(a));t.add(b.subscribe(()=>v.next(!0))),t.add(S.subscribe(()=>v.next(!1)));let y=new C.ValueSubject(Wc(a)),x=(0,C.fromEvent)(a,"fullscreenchange").pipe((0,C.shareReplay)(1));t.add(x.pipe((0,C.map)(()=>Wc(a))).subscribe(y));let w=.1,M=1e3,_=(0,C.fromEvent)(a,"timeupdate").pipe((0,C.map)(V=>a.duration-a.currentTime<w),(0,C.filterChanged)(),(0,C.shareReplay)(1)),F=(0,C.merge)(_.pipe((0,C.filter)(V=>!a.loop&&V)),(0,C.fromEvent)(a,"ended")).pipe((0,C.throttle)(M),(0,C.mapTo)(void 0),(0,C.shareReplay)(1)),j=(0,C.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(V=>(0,C.fromEvent)(a,V)),_.pipe((0,C.map)(V=>({type:V?"ended":"unknown"})))).pipe((0,C.map)(V=>H.browser.isFirefox&&V.type==="ended"?a.readyState<2:a.readyState<3),(0,C.filterChanged)(),(0,C.shareReplay)(1));return{playing$:s,pause$:m,canplay$:e("canplay"),ended$:F,looped$:l,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:(0,C.fromEvent)(a,"durationchange").pipe((0,C.map)(()=>a.duration),(0,C.shareReplay)(1)),isBuffering$:j,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:v,inFullscreen$:y,enterPip$:b,leavePip$:S,destroy:i}};var Gt=require("@vkontakte/videoplayer-shared/es2018"),mi=a=>{switch(a){case"mobile":return Gt.VideoQuality.Q_144P;case"lowest":return Gt.VideoQuality.Q_240P;case"low":return Gt.VideoQuality.Q_360P;case"sd":case"medium":return Gt.VideoQuality.Q_480P;case"hd":case"high":return Gt.VideoQuality.Q_720P;case"fullhd":case"full":return Gt.VideoQuality.Q_1080P;case"quadhd":case"quad":return Gt.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return Gt.VideoQuality.Q_2160P}};var Qe=G(ft(),1),Gc=G(Ye(),1),zi=G(pi(),1),L=require("@vkontakte/videoplayer-shared/es2018");var zc=!1,Yt={},Xg=a=>{zc=a},Jg=()=>{Yt={}},Zg=a=>{a(Yt)},Ma=(a,e)=>{var t;zc&&(Yt.meta=(t=Yt.meta)!=null?t:{},Yt.meta[a]=e)},He=class{constructor(e){this.name=e}next(e){var i,r;if(!zc)return;Yt.series=(i=Yt.series)!=null?i:{};let t=(r=Yt.series[this.name])!=null?r:[];t.push([Date.now(),e]),Yt.series[this.name]=t}};var Ae=require("@vkontakte/videoplayer-shared/es2018");function ev(a,e,t){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function Mr(a,e,t){return(0,Ae.isNullable)(a)||(0,Ae.isNonNullable)(a.min)&&(0,Ae.isNonNullable)(a.max)&&(0,Ae.isLower)(a.max,a.min)||(0,Ae.isNonNullable)(a.min)&&e&&(0,Ae.isHigher)(a.min,e)||(0,Ae.isNonNullable)(a.max)&&t&&(0,Ae.isLower)(a.max,t)}function tv({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return Mr({max:a!=null&&a.max?(0,Ae.videoHeightToQuality)(a.max):void 0,min:a!=null&&a.min?(0,Ae.videoHeightToQuality)(a.min):void 0},e?(0,Ae.videoHeightToQuality)(e):void 0,t?(0,Ae.videoHeightToQuality)(t):void 0)}var nv=new He("best_bitrate"),Hn=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var $r=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),bi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,L.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Qn='Assertion "ABR Tracks is empty array" failed',jn=new WeakMap,iv=new WeakMap,rv=new WeakMap,$a=(a,e,t,i)=>{var u;let r=[...e].sort($r(1)),s=[...t].sort($r(1)),n=s.filter(c=>(0,L.isNonNullable)(c.bitrate)&&(0,L.isNonNullable)(a.bitrate)?a.bitrate/c.bitrate>i:!0),o=(u=(0,Qe.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Qe.default)(s,-1);return o&&(0,Gc.default)(n,o)?o:n.length?(0,Qe.default)(n,-1):(0,Qe.default)(s,0)},Ca=(a,e,t,i)=>{var u;let r=jn.get(e);r||(r=[...e].sort($r(1)),jn.set(e,r));let s=jn.get(t);s||(s=[...t].sort($r(1)),jn.set(t,s));let n=rv.get(a);n||(n=s.filter(c=>(0,L.isNonNullable)(c.bitrate)&&(0,L.isNonNullable)(a.bitrate)?a.bitrate/c.bitrate>i:!0),rv.set(a,n));let o=(u=(0,Qe.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Qe.default)(s,-1);return o&&(0,Gc.default)(n,o)?o:n.length?(0,Qe.default)(n,-1):(0,Qe.default)(s,0)},av=a=>"quality"in a,Wn=(a,e,t,i)=>{var n;let r=(0,L.isNonNullable)((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&(0,L.isNonNullable)(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&(0,L.now)()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!s&&i.recordSelection(t),s&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=av(o)?"video":"audio",c=av(o)?o.quality:o.bitrate;return e({message:`
8
8
  [last ${u} selected] ${c}
9
9
  `}),o}return i==null||i.recordSwitch(t),t},TR=(a,e)=>Math.log(e)/Math.log(a),ov=({tuning:a,container:e,limits:t,panelSize:i})=>{let r=a.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(a.usePixelRatio&&H.display.pixelRatio){let s=H.display.pixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(s-1)+1;else{let n=a.pixelRatioLogBase,[o=0,u=0,c=0]=a.pixelRatioLogCoefficients,d=TR(n,o*s+u)+c;Number.isFinite(d)&&(r*=d)}}return(0,L.isNonNullable)(t==null?void 0:t.min)&&(0,L.isHigherOrEqual)(t.min,a.highQualityLimit)&&(r*=2),{containerSizeLimit:a.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},sv=new WeakMap,Ot=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:c,visible:d,droppedVideoMaxQualityLimit:l,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:m,panelSize:b})=>{var te,ce,ne,A,$;(0,L.assertNotEmptyArray)(a,Qn);let{containerSizeFactor:S,containerSizeLimit:v}=ov({container:e,tuning:i,limits:r,panelSize:b}),y=i.considerPlaybackRate&&(0,L.isNonNullable)(o)?o:1,x=sv.get(a);x||(x=a.filter(k=>!(0,L.isInvariantQuality)(k.quality)).sort((k,R)=>(0,L.isHigher)(k.quality,R.quality)?-1:1),sv.set(a,x));let w=(te=(0,Qe.default)(x,-1))==null?void 0:te.quality,M=(ce=(0,Qe.default)(x,0))==null?void 0:ce.quality,_=Mr(r,M,w),F=y*Hn(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),O={},j=null;for(let k of x){let R=!0;if(v)if(k.size)R=k.size.width<=v.width&&k.size.height<=v.height;else{let rt=v&&(0,L.videoSizeToQuality)(v);R=rt?(0,L.isLowerOrEqual)(k.quality,rt):!0}if(!R){O[k.quality]="FitsContainer";continue}let X=h||t,Y=(0,L.isNonNullable)(X)&&isFinite(X)&&(0,L.isNonNullable)(k.bitrate)?X-s>=k.bitrate*F:!0,At=(r==null?void 0:r.min)===k.quality;if(!Y&&!At){O[k.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&(0,L.isNonNullable)(i.minBufferToSwitchUp)&&u&&!(0,L.isInvariantQuality)(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&(0,L.isHigher)(k.quality,u.quality)){O[k.quality]="Buffer";continue}if(!!l&&(0,L.isHigherOrEqual)(k.quality,l)&&!At){O[k.quality]="DroppedFramesLimit";continue}if(!!p&&(0,L.isHigherOrEqual)(k.quality,p)&&!At){O[k.quality]="StallsLimit";continue}let Ve=_||((0,L.isNullable)(r==null?void 0:r.max)||(0,L.isLowerOrEqual)(k.quality,r.max))&&((0,L.isNullable)(r==null?void 0:r.min)||(0,L.isHigherOrEqual)(k.quality,r.min)),_e=(0,L.isNonNullable)(d)&&!d?(0,L.isLowerOrEqual)(k.quality,i.backgroundVideoQualityLimit):!0;if(!Ve||!_e){O[k.quality]="FitsQualityLimits";continue}j||(j=k)}j&&j.bitrate&&nv.next(j.bitrate);let V=(ne=j!=null?j:(0,Qe.default)(x,-1))!=null?ne:a[0],W=c==null?void 0:c.last,N=Wn(i,m,V,c);return(0,L.isNonNullable)(c)&&N.quality!==(W==null?void 0:W.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(d,"i")}var sy=a=>{if(!(a!=null&&a.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(a),r=(i==null?void 0:i[1])==="-"?-1:1,s={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 s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},Pt=(a,e)=>{let t=a;t=(0,yl.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,ny.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,yl.default)(t,n,(o,u)=>(0,ja.isNullable)(s)?o:(0,ja.isNullable)(u)?s:(0,oy.default)(s,parseInt(u,10),"0"))}return t},fo=(a,e)=>{var j,V,W,N,te,ce,ne,A,$,k,R,X,Y,At,Rt,de,Be,Ve,_e,rt,Ut,jt,ki,ar,sr,Wl,zl,Gl,Yl,Kl,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;let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(vt=>{var be,Ai;return(Ai=(be=vt.textContent)==null?void 0:be.trim())!=null?Ai:""}),o=(j=(0,uy.default)(n,0))!=null?j:"",u=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),d=s.getAttribute("publishTime"),l=s.getElementsByTagName("vk:Attrs")[0],p=l==null?void 0:l.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=l==null?void 0:l.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=l==null?void 0:l.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=l==null?void 0:l.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,S;u&&(S={availabilityStartTime:c?new Date(c).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:p?new Date(p).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:m==="yes"});let v,y=s.getAttribute("mediaPresentationDuration"),x=[...s.getElementsByTagName("Period")],w=x.reduce((vt,be)=>({...vt,[be.id]:be.children}),{}),M=x.reduce((vt,be)=>({...vt,[be.id]:be.getAttribute("duration")}),{});y?v=sy(y):(0,Tl.default)(M).filter(vt=>vt).length&&!u?v=(0,Tl.default)(M).reduce((vt,be)=>{var Ai;return vt+((Ai=sy(be))!=null?Ai:0)},0):b&&(v=parseInt(b,10));let _=0,F=(W=(V=s.getAttribute("profiles"))==null?void 0:V.split(","))!=null?W:[];for(let vt of x.map(be=>be.id))for(let be of w[vt]){let Ai=(N=be.getAttribute("id"))!=null?N:"id"+(_++).toString(10),zr=(te=be.getAttribute("mimeType"))!=null?te:"",qo=(ce=be.getAttribute("codecs"))!=null?ce:"",Uo=(ne=be.getAttribute("contentType"))!=null?ne:zr==null?void 0:zr.split("/")[0],aT=($=(A=be.getAttribute("profiles"))==null?void 0:A.split(","))!=null?$:[],Ad=(R=ay((k=be.getAttribute("lang"))!=null?k:""))!=null?R:{},Cs=(At=(Y=(X=be.querySelector("Label"))==null?void 0:X.textContent)==null?void 0:Y.trim())!=null?At:void 0,sT=be.querySelectorAll("Representation"),nT=be.querySelector("SegmentTemplate"),oT=(de=(Rt=be.querySelector("Role"))==null?void 0:Rt.getAttribute("value"))!=null?de:void 0,nr=Uo,Pe={id:Ai,language:Ad.language,isDefault:oT==="main",label:Cs,codecs:qo,hdr:nr==="video"&&Sl(qo),mime:zr,representations:[]};for(let fe of sT){let ii=(Be=fe.getAttribute("lang"))!=null?Be:void 0,Ds=(_e=(Ve=Cs!=null?Cs:be.getAttribute("label"))!=null?Ve:fe.getAttribute("label"))!=null?_e:void 0,Ls=(jt=(Ut=(rt=fe.querySelector("BaseURL"))==null?void 0:rt.textContent)==null?void 0:Ut.trim())!=null?jt:"",Ri=new URL(Ls||o,e).toString(),ri=(ki=fe.getAttribute("mimeType"))!=null?ki:zr,Bs=(sr=(ar=fe.getAttribute("codecs"))!=null?ar:qo)!=null?sr:"",Vs;if(Uo==="text"){let ai=fe.getAttribute("id")||"",_s=((Wl=Ad.privateuse)==null?void 0:Wl.includes("x-auto"))||ai.includes("_auto"),Mi=fe.querySelector("SegmentTemplate");if(Mi){let Gr={representationId:(zl=fe.getAttribute("id"))!=null?zl:void 0,bandwidth:(Gl=fe.getAttribute("bandwidth"))!=null?Gl:void 0},Os=parseInt((Yl=fe.getAttribute("bandwidth"))!=null?Yl:"",10)/1e3,Ns=(Xl=parseInt((Kl=Mi.getAttribute("startNumber"))!=null?Kl:"",10))!=null?Xl:1,or=parseInt((Jl=Mi.getAttribute("timescale"))!=null?Jl:"",10),jo=(Zl=Mi.querySelectorAll("SegmentTimeline S"))!=null?Zl:[],ur=Mi.getAttribute("media");if(!ur)continue;let Fs=[],qs=0,Us="",cr=0,Yr=Ns,je=0;for(let St of jo){let $i=parseInt((ed=St.getAttribute("d"))!=null?ed:"",10),dt=parseInt((td=St.getAttribute("r"))!=null?td:"",10)||0,si=parseInt((id=St.getAttribute("t"))!=null?id:"",10);je=Number.isFinite(si)?si:je;let Ci=$i/or*1e3,ni=je/or*1e3;for(let Mt=0;Mt<dt+1;Mt++){let oi=Pt(ur,{...Gr,segmentNumber:Yr.toString(10),segmentTime:(je+Mt*$i).toString(10)}),lr=(ni!=null?ni:0)+Mt*Ci,Xr=lr+Ci;Yr++,Fs.push({time:{from:lr,to:Xr},url:oi})}je+=(dt+1)*$i,qs+=(dt+1)*Ci}cr=je/or*1e3,Us=Pt(ur,{...Gr,segmentNumber:Yr.toString(10),segmentTime:je.toString(10)});let Kr={time:{from:cr,to:1/0},url:Us},Ht={type:"template",baseUrl:Ri,segmentTemplateUrl:ur,initUrl:"",totalSegmentsDurationMs:qs,segments:Fs,nextSegmentBeyondManifest:Kr,timescale:or};Vs={id:ai,kind:"text",segmentReference:Ht,profiles:[],duration:v,bitrate:Os,mime:"",codecs:"",width:0,height:0,isAuto:_s}}else Vs={id:ai,isAuto:_s,kind:"text",url:Ri}}else{let ai=(ad=(rd=fe.getAttribute("contentType"))!=null?rd:ri==null?void 0:ri.split("/")[0])!=null?ad:Uo,_s=(nd=(sd=be.getAttribute("profiles"))==null?void 0:sd.split(","))!=null?nd:[],Mi=parseInt((od=fe.getAttribute("width"))!=null?od:"",10),Gr=parseInt((ud=fe.getAttribute("height"))!=null?ud:"",10),Os=parseInt((cd=fe.getAttribute("bandwidth"))!=null?cd:"",10)/1e3,Ns=(ld=fe.getAttribute("frameRate"))!=null?ld:"",or=(dd=fe.getAttribute("quality"))!=null?dd:void 0,jo=Ns?ry(Ns):void 0,ur=(pd=fe.getAttribute("id"))!=null?pd:"id"+(_++).toString(10),Fs=ai==="video"?`${Gr}p`:ai==="audio"?`${Os}Kbps`:Bs,qs=`${ur}@${Fs}`,Us=[...F,...aT,..._s],cr,Yr=fe.querySelector("SegmentBase"),je=(hd=fe.querySelector("SegmentTemplate"))!=null?hd:nT;if(Yr){let Ht=(md=(fd=fe.querySelector("SegmentBase Initialization"))==null?void 0:fd.getAttribute("range"))!=null?md:"",[St,$i]=Ht.split("-").map(oi=>parseInt(oi,10)),dt={from:St,to:$i},si=(bd=fe.querySelector("SegmentBase"))==null?void 0:bd.getAttribute("indexRange"),[Ci,ni]=si?si.split("-").map(oi=>parseInt(oi,10)):[],Mt=si?{from:Ci,to:ni}:void 0;cr={type:"byteRange",url:Ri,initRange:dt,indexRange:Mt}}else if(je){let Ht={representationId:(gd=fe.getAttribute("id"))!=null?gd:void 0,bandwidth:(vd=fe.getAttribute("bandwidth"))!=null?vd:void 0},St=parseInt((Sd=je.getAttribute("timescale"))!=null?Sd:"",10),$i=(yd=je.getAttribute("initialization"))!=null?yd:"",dt=je.getAttribute("media"),si=(Id=parseInt((Td=je.getAttribute("startNumber"))!=null?Td:"",10))!=null?Id:1,Ci=Pt($i,Ht);if(!dt)throw new ReferenceError("No media attribute in SegmentTemplate");let ni=(Ed=je.querySelectorAll("SegmentTimeline S"))!=null?Ed:[],Mt=[],oi=0,lr="",Xr=0;if(ni.length){let js=si,yt=0;for(let dr of ni){let $t=parseInt((wd=dr.getAttribute("d"))!=null?wd:"",10),Di=parseInt((xd=dr.getAttribute("r"))!=null?xd:"",10)||0,Hs=parseInt((Pd=dr.getAttribute("t"))!=null?Pd:"",10);yt=Number.isFinite(Hs)?Hs:yt;let Ho=$t/St*1e3,Qo=yt/St*1e3;for(let Qs=0;Qs<Di+1;Qs++){let cT=Pt(dt,{...Ht,segmentNumber:js.toString(10),segmentTime:(yt+Qs*$t).toString(10)}),Rd=(Qo!=null?Qo:0)+Qs*Ho,lT=Rd+Ho;js++,Mt.push({time:{from:Rd,to:lT},url:cT})}yt+=(Di+1)*$t,oi+=(Di+1)*Ho}Xr=yt/St*1e3,lr=Pt(dt,{...Ht,segmentNumber:js.toString(10),segmentTime:yt.toString(10)})}else if((0,ja.isNonNullable)(v)){let yt=parseInt((kd=je.getAttribute("duration"))!=null?kd:"",10)/St*1e3,dr=Math.ceil(v/yt),$t=0;for(let Di=1;Di<dr;Di++){let Hs=Pt(dt,{...Ht,segmentNumber:Di.toString(10),segmentTime:$t.toString(10)});Mt.push({time:{from:$t,to:$t+yt},url:Hs}),$t+=yt}Xr=$t,lr=Pt(dt,{...Ht,segmentNumber:dr.toString(10),segmentTime:$t.toString(10)})}let uT={time:{from:Xr,to:1/0},url:lr};cr={type:"template",baseUrl:Ri,segmentTemplateUrl:dt,initUrl:Ci,totalSegmentsDurationMs:oi,segments:Mt,nextSegmentBeyondManifest:uT,timescale:St}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ai||!ri)continue;let Kr={video:"video",audio:"audio",text:"text"}[ai];if(!Kr)continue;nr||(nr=Kr),Vs={id:qs,kind:Kr,segmentReference:cr,profiles:Us,duration:v,bitrate:Os,mime:ri,codecs:Bs,width:Mi,height:Gr,fps:jo,quality:or}}Pe.language||(Pe.language=ii),Pe.label||(Pe.label=Ds),Pe.mime||(Pe.mime=ri),Pe.codecs||(Pe.codecs=Bs),Pe.hdr||(Pe.hdr=nr==="video"&&Sl(Bs)),Pe.representations.push(Vs)}if(nr){let fe=r[nr].find(ii=>ii.id===Pe.id);if(fe&&Pe.representations.every(ii=>ii.segmentReference.type==="template"))for(let ii of fe.representations){let Ds=Pe.representations.find(ri=>ri.id===ii.id);if(!Ds)continue;let Ls=Ds.segmentReference,Ri=ii.segmentReference;Ri.segments.push(...Ls.segments),Ri.nextSegmentBeyondManifest=Ls.nextSegmentBeyondManifest}else r[nr].push(Pe)}}return{duration:v,streams:r,baseUrls:n,live:S}};var bo=G(ft(),1),Il=G(Ye(),1),Qa=require("@vkontakte/videoplayer-shared/es2018");var Ha=(s=>(s.VP9="vp9",s.AV1="av1",s.NONE="none",s.SMOOTH="smooth",s.POWER_EFFICIENT="power_efficient",s))(Ha||{});var mo=a=>{let{webmDecodingInfo:e}=H.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(a){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,Qa.assertNever)(a)}},cy=({webmCodec:a,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...mo(a),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],s=[...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[...s,"MPEG",...mo(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...mo(a),"MPEG",...s,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...mo(a),...s,"HLS","HLS_ONDEMAND"];default:(0,Qa.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,Qa.assertNever)(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},ly=({androidPreferredFormat:a,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"],s=[...i,...r],n=[...r,...i],o,u=H.device.isMac&&H.browser.isSafari;if(H.device.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:(0,Qa.assertNever)(a)}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=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},El=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],go=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,bo.default)(t.value.split("."),0)}for(let t of a){let i=(0,bo.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,bo.default)(e.value.split("."),0)},vo=a=>{let e=a.map(i=>Nr(i)),{codecs:t}=H.video;return T$().filter(i=>{if((0,Il.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})},So=a=>{let e=a.map(i=>Nr(i)),{codecs:t}=H.video;return I$().filter(i=>{if((0,Il.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},Nr=a=>a.split(".")[0].replace("0",""),T$=()=>["av1","vp9","hev1","avc1"],I$=()=>["opus","mp4a"];var xy=G(ft(),1);var E$=(a,e={})=>{let i=e.timeout||1,r=performance.now();return Re.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},w$=a=>Re.clearTimeout(a),dy=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),py=!dy(Re.requestIdleCallback)||!dy(Re.cancelIdleCallback),Yi=py?E$:Re.requestIdleCallback,Ki=py?w$:Re.cancelIdleCallback;var D=require("@vkontakte/videoplayer-shared/es2018");var fy=G(ft(),1);var yo=a=>a.valid,ue=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,s;i===0?(this.size=void 0,this.valid=!1,s=void 0):i===1?(this.size=void 0,this.valid=!1,s=void 0):i>e.byteLength?(this.size=i,this.valid=!1,s=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,s=i-this.cursor),this.content=new DataView(e.buffer,r,s)}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 Fr=class extends ue{};var hy=require("@vkontakte/videoplayer-shared/es2018");var Wa=class extends ue{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,hy.assertNever)(e)}}};var za=class extends ue{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 s=this.readString(4);this.compatibleBrands.push(s)}}};var Ga=class extends ue{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ye=class extends ue{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 Ya=class extends ye{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 Ka=class extends ue{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Xa=class extends ue{constructor(e,t){super(e,t),this.data=this.content}};var Xi=class extends ye{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(),s=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,c=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:c})}}}};var Ja=class extends ue{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Za=class extends ue{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var es=class extends ye{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 ts=class extends ye{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var is=class extends ye{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 rs=class extends ue{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var as=class extends ye{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 ss=class extends ue{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ns=class extends ue{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var os=class extends ye{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var us=class extends ue{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var cs=class extends ye{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 ls=class extends ye{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 ds=class extends ye{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 ps=class extends ue{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var hs=class extends ye{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 fs=class extends ue{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 P$={ftyp:za,moov:Ga,mvhd:Ya,moof:Ka,mdat:Xa,sidx:Xi,trak:Ja,mdia:rs,mfhd:os,tkhd:as,traf:us,tfhd:cs,tfdt:ls,trun:ds,minf:ss,sv3d:Za,st3d:es,prhd:ts,proj:ns,equi:is,uuid:Wa,stbl:ps,stsd:hs,avc1:fs,unknown:Fr},Xt=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n;try{n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(o){if(!(o instanceof RangeError))throw o}if(!n||!yo(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=P$[e];return i?new i(t,new a):new Fr(t,new a)}};var yi=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,s;yo(t)&&((s=(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 A$=new TextDecoder("ascii"),R$=a=>A$.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",M$=a=>{let e=new Xi(a,new Xt),t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},$$=(a,e)=>{let i=new Xt().parse(a),r=new yi(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],c=o.source.byteOffset,l=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,c,l)},C$=a=>{let t=new Xt().parse(a),i=new yi(t),r={},s=i.findAll("uuid"),n=(0,fy.default)(s,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},D$=a=>{var r;let t=new Xt().parse(a);return(r=new yi(t).find("sidx"))==null?void 0:r.timescale},L$=(a,e)=>{let i=new Xt().parse(a),s=new yi(i).findAll("traf"),n=s[s.length-1].children.find(l=>l.type==="tfhd"),o=s[s.length-1].children.find(l=>l.type==="tfdt"),u=s[s.length-1].children.find(l=>l.type==="trun"),c=0;return u.sampleDuration.length?c=u.sampleDuration.reduce((l,p)=>l+p,0):c=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+c)/e*1e3},B$=a=>{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 Xt().parse(a),r=new yi(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},my={validateData:R$,parseInit:B$,getIndexRange:()=>{},parseSegments:M$,parseFeedableSegmentChunk:$$,getChunkEndTime:L$,getServerLatencyTimestamps:C$,getTimescaleFromIndex:D$};var bs=G(Ye(),1),Jt=require("@vkontakte/videoplayer-shared/es2018");var gy=require("@vkontakte/videoplayer-shared/es2018");var by={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"}},vy=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=ms(a,t),r=i in by,s=r?by[i].type:"binary",n=a.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(a.buffer,a.byteOffset+t+1,o-1),c=n&255>>o,d=ms(u),l=c*2**((o-1)*8)+d,p=t+o,h;return p+l>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,l),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+l,value:h,valueSize:l}},ms=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},kt=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return ms(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:(0,gy.assertNever)(e)}},Ji=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=vy(i);if(!e(r))return;r.type==="master"&&Ji(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},Sy=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=vy(a);return Ji(r.value,({tag:s,type:n,value:o})=>(s===17143?e=kt(o,n):s===17026?t=kt(o,n):s===17029&&(i=kt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var yy=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],V$=[231,22612,22743,167,171,163,160,175],_$=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,c,d=!1,l=0;return Ji(a,({tag:p,type:h,value:m,valueSize:b})=>{if(p===21419){let S=kt(m,h);c=ms(S)}else p!==21420&&(c=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?i=kt(m,h):p===17545?r=kt(m,h):p===21420&&c===475249515?u=kt(m,h):p===374648427?Ji(m,({tag:S,type:v,value:y})=>S===30321?(d=kt(y,v)===1,!1):!0):s&&n&&(0,bs.default)(yy,p)&&(o=!0),!o}),(0,Jt.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,Jt.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,Jt.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:d,stereoMode:l,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},O$=a=>{if((0,Jt.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},N$=(a,e)=>{let t=!1,i=!1,r=o=>(0,Jt.isNonNullable)(o.time)&&(0,Jt.isNonNullable)(o.position),s=[],n;return Ji(a,({tag:o,type:u,value:c})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=kt(c,u));break;case 183:break;case 241:n&&(n.position=kt(c,u));break;default:t&&(0,bs.default)(yy,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((o,u)=>{let{time:c,position:d}=o,l=s[u+1];return{status:"none",time:{from:c,to:l?l.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:l?e.segmentStart+l.position-1:e.segmentEnd-1}}})},F$=a=>{let e=0,t=!1;try{Ji(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,bs.default)(V$,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||(t=(0,bs.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},Ty={validateData:Sy,parseInit:_$,getIndexRange:O$,parseSegments:N$,parseFeedableSegmentChunk:F$};var Zi=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Ty;case"mp4":return my}}throw new ReferenceError(`Unsupported mime type ${a}`)};var wl=G(ft(),1);var Iy=require("@vkontakte/videoplayer-shared/es2018"),Ti=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?mi(s):void 0)!=null?u:(0,Iy.videoSizeToQuality)({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},gs=({id:a,bitrate:e})=>({id:a,bitrate:e}),Ey=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),wy=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),xl=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,wl.default)(i.split("."),0),isDefault:r}),Pl=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,wl.default)(r.split("."),0)}),kl=a=>"url"in a,ct=a=>a.type==="template";var qr=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,manifest:o}){this.error$=new D.Subject;this.playingRepresentation$=new D.ValueSubject(void 0);this.playingRepresentationInit$=new D.ValueSubject(void 0);this.currentSegmentLength$=new D.ValueSubject(0);this.onLastSegment$=new D.ValueSubject(!1);this.fullyBuffered$=new D.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 ve;this.downloadAbortController=new ve;this.subscription=new D.Subscription;this.startWith=(0,D.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,D.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.containerParser=Zi(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),s=this.parsedInitData.get(t.id);(0,D.assertNonNullable)(i,"No init buffer for starting representation"),(0,D.assertNonNullable)(r,"No segments for starting representation"),await this.nativeBufferManager.addInitSegment(i),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s)}.bind(this));this.switchTo=(0,D.abortable)(this.destroyAbortController.signal,async function*(e,t=!0){var l;if((0,D.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,D.assertNonNullable)(r,`No such representation ${e}`),(0,D.assertNonNullable)(i,`No such representation ${this.downloadingRepresentationId}`),yield this.loadInitIfNeeded(r,"high");let s=this.initData.get(r.id),n=this.segments.get(r.id);(0,D.assertNonNullable)(s,"No init buffer for switching representation"),(0,D.assertNonNullable)(n,"No segments for switching representation");let o=(l=this.getCurrentPosition())!=null?l:0,u=p=>p.segment.networkStatus!=="downloaded"||p.segment.time.to-o>this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment,c=p=>{let h=this.representations.get(p.representationId);return(0,D.assertNonNullable)(h,"No itemRepresentation for previous track before switch"),p.segment.networkStatus!=="downloaded"||this.forceSwitchCondition(h,r)},d=p=>t?u(p)&&c(p):u(p);this.bufferPlaybackQueue.filter(d).forEach(p=>p.segment.bufferStatus="none"),this.bufferPlaybackQueue=this.bufferPlaybackQueue.filter(p=>!d(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,D.abortable)(this.downloadAbortController.signal,async function*(){let e=(0,D.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(t=>{let i=(0,D.getWindow)();this.loadByteRangeSegmentsTimeoutId=i.setTimeout(t,e),this.subscription.add((0,D.fromEvent)(i,"online").pipe((0,D.once)()).subscribe(()=>{t(),i.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}))})}.bind(this));var u;this.kind=e,this.nativeBufferManager=t,this.fetcher=r,this.tuning=s,this.getCurrentPosition=n,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.baseUrls=(u=o==null?void 0:o.baseUrls)!=null?u:[],this.representations=new Map(i.map(c=>[c.id,c]))}async seek(e){await this.abort(),await this.clearBuffer(),await this.maintain(e)}async maintain(e=this.getCurrentPosition()){(0,D.isNullable)(e)||(await this.maintainPlaybackBuffer(e),await this.maintainNativeBuffer(),this.actualizeLastSegmentInfo(e))}getForwardPlaybackBufferDuration(e=this.getCurrentPosition()){let t=this.getPlaybackBufferState();return(0,D.isNonNullable)(t)&&(0,D.isNonNullable)(e)?t.to-e:0}getPlaybackBufferState(){if(!this.bufferPlaybackQueue.length)return null;let t=this.bufferPlaybackQueue[0].segment.time.from,i=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segment.time.to;return{from:t,to:i}}async abort(){this.abortDownload(),await this.abortNativeBuffer()}findSegmentStartTime(e){var s,n;let t=(n=(s=this.downloadingRepresentationId)!=null?s: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,D.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(){var t;if((0,D.isNullable)(this.playingRepresentationId))return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(t=(0,xy.default)(e,-1))==null?void 0:t.time.to:0)||0}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){let e=(0,D.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_bgan9da8h1hj)for(let t of this.idleCallbacks.values())e.__polyfill_cancelIdleCallback_bgan9da8h1hj(t);this.idleCallbacks.clear(),e.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}forceSwitchCondition(e,t){let i=!0;if(this.kind==="video"){let r=Ti(e),s=Ti(t);i=(0,D.isNonNullable)(r)&&(0,D.isNonNullable)(s)&&(0,D.isHigher)(s.quality,r.quality)}else if(this.kind==="audio"){let r=gs(e),s=gs(t);i=(0,D.isNonNullable)(r==null?void 0:r.bitrate)&&(0,D.isNonNullable)(s==null?void 0:s.bitrate)&&s.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 ve,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,Yi(async r=>await this.loadInitIfNeeded(i,"low",!1)))}async loadInitIfNeeded(e,t="auto",i=!1){let r=this.initDataPromises.get(e.id),s;this.initData.has(e.id)&&this.segments.has(e.id)?s=Promise.resolve():(0,D.isNonNullable)(r)?s=r:s=this.loadInit(e,t,i),await s}async loadInit(e,t="auto",i=!1){var r;try{let s=this.tuning.dash.useFetchPriorityHints?t:"auto",n=this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,s);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,D.isNullable)(u)||(0,D.isNullable)(c))return;o&&this.parsedInitData.set(e.id,o);let d=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,d),this.segments.set(e.id,c),this.failedDownloads=0}catch(s){i&&this.error$.next({id:"LoadInits",category:D.ErrorCategory.WTF,message:"loadInit threw",thrown:s})}}async maintainNativeBuffer(){var o;let e=this.getCurrentPosition();if((0,D.isNullable)(e)||this.maintainNativeBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex||this.preloadOnly)return;this.maintainNativeBufferMutex=!0;let t=this.bufferPlaybackQueue.find(u=>this.withinInterval(e,u.segment.time)),i=this.bufferPlaybackQueue.find(u=>u.segment.bufferStatus!=="fed"),r=this.initData.get((o=i==null?void 0:i.representationId)!=null?o:""),s=this.bufferPlaybackQueue[0],n=this.downloadAbortController.signal;(0,D.isNonNullable)(r)&&(0,D.isNonNullable)(i)&&(0,D.isNonNullable)(t)&&this.playingRepresentationId!==i.representationId&&this.withinAppendInterval(e,i.segment.time)&&(i===t||t.segment.bufferStatus==="fed")&&(await this.abortNativeBuffer(),await this.nativeBufferManager.addInitSegment(r,this.downloadAbortController.signal),this.playingRepresentationId=i.representationId,this.playingRepresentation$.next(this.playingRepresentationId)),(0,D.isNonNullable)(i)&&this.withinAppendInterval(e,i.segment.time)&&(i.segment.loadedBytes===i.segment.size&&i.segment.bufferStatus==="none"?await this.appendSegmentFully(i,n):await this.appendSegmentPartially(i,n)),(0,D.isNonNullable)(s)&&this.withinRemoveInterval(e,s.segment.time)&&await this.removeSegment(s,n),this.pruneVirtualBuffer(e),this.maintainNativeBufferMutex=!1}async maintainPlaybackBuffer(e){(0,D.assertNonNullable)(this.downloadingRepresentationId);let t=this.segments.get(this.downloadingRepresentationId),i=this.representations.get(this.downloadingRepresentationId);if((0,D.isNullable)(t)||(0,D.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,D.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 s=this.selectItemsToLoad();await this.loadItems(s,i),this.maintainPlaybackBufferMutex=!1}actualizeLastSegmentInfo(e){var r;let t=this.segments.get((r=this.downloadingRepresentationId)!=null?r:"");if((0,D.isNullable)(t)||t.length===0)return;let i=t[(t==null?void 0:t.length)-1];(0,D.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,D.assertNonNullable)(this.downloadingRepresentationId);let i=this.getPlaybackBufferState(),r,s;(0,D.isNonNullable)(i)&&this.withinInterval(e,i)?(s=this.forwardBufferTarget-this.getForwardPlaybackBufferDuration(e),r=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segmentIndex+1):(s=this.forwardBufferTarget,r=t.findIndex(o=>this.withinInterval(e,o.time))),r=r===-1?0:r;let n=[];for(;r<t.length&&s>0;){n.push({representationId:this.downloadingRepresentationId,segmentIndex:r,segment:t[r]});let{from:o,to:u}=t[r].time;s-=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,D.isNonNullable)(e)?e+r>=t&&e<i:!1}withinAppendInterval(e,{from:t,to:i}){let{actionTimeShiftFromSegment:r}=this.tuning.dash;return(0,D.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,D.isNonNullable)(e)?e-i>t:!1}async appendSegmentFully(e,t){if((0,D.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,D.isNullable)(e.segment.data)||(0,D.isNullable)(e.segment.loadedBytes)||(0,D.isNullable)(e.segment.feedingBytes)||(0,D.isNullable)(e.segment.fedBytes)||(0,D.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),s=e.segment.loadedBytes!==e.segment.size?this.parseFeedableSegmentChunk(r):r;s!=null&&s.byteLength&&(e.segment.bufferStatus="partially_fed",e.segment.feedingBytes+=s.byteLength,await this.nativeBufferManager.append(s,t)&&(e.segment.fedBytes+=s.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,s=(r-i)/4;await this.nativeBufferManager.remove(0,r-s,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,D.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 s=this.currentVirtualBufferSize-t+i;for(let n of this.segments.values())for(let o of n)(0,D.isNonNullable)(o.size)&&s>0&&o.time.to<=e-r&&o.bufferStatus==="none"&&o.networkStatus==="downloaded"&&(o.data=null,o.networkStatus="none",this.currentVirtualBufferSize-=o.size,s-=o.size);for(let n of this.segments.values())for(let o of[...n].reverse())(0,D.isNonNullable)(o.size)&&s>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,s-=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 Ft=require("@vkontakte/videoplayer-shared/es2018");var To=class extends qr{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:s,...n}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),!r.aborted)try{await this.fetcher.fetch(s,{...n,priority:i}),this.lastDataObtainedTimestampMs=(0,Ft.now)(),this.failedDownloads=0}catch(o){this.abortDownloadingItems(),xt(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=0,t=0,i=[],r=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,s=this.preloadOnly?this.forwardBufferTarget:0,n=0;for(;n<this.downloadingBufferItems.length&&this.downloadingBufferItems[n].segment.networkStatus==="none"&&(e<=r||t<=s);){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(We(t.segmentReference))throw new Error("Representation is not byte range type");let{signal:i}=this.downloadAbortController,r=t.segmentReference.url,s={from:e[0].segment.byte.from,to:e[e.length-1].segment.byte.to};return{url:r,range:s,onProgress:async(o,u)=>{if(!i.aborted)try{this.lastDataObtainedTimestampMs=(0,Ft.now)(),await this.onSomeDataLoaded({downloadingItems:e,dataView:o,loaded:u,signal:i,globalFrom:s?s.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:Ft.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:s,signal:n}){let o=this.representations.get(i);if(!(!this.downloadingBufferItems.length||(0,Ft.isNullable)(o)||(0,Ft.isNullable)(r)||n.aborted))for(let u of e){let{segment:c}=u,d=c.byte.from-r,l=c.byte.to-r,p=l-d+1,h=d<s,m=l<=s;c.size=p,h&&(c.networkStatus==="downloading"&&c.bufferStatus==="none"&&m?(c.data=new DataView(t.buffer,t.byteOffset+d,p),this.currentVirtualBufferSize+=c.size,this.onItemFullyDownloaded(u),c.loadedBytes=Math.min(p,s-d),await this.onDownloadItem(u)):(0,Ft.isNonNullable)(c.feedingBytes)&&this.tuning.dash.enableSubSegmentBufferFeeding&&c.networkStatus==="downloading"&&(c.loadedBytes=Math.min(p,s-d),m&&(this.currentVirtualBufferSize+=c.size,this.onItemFullyDownloaded(u)),c.loadedBytes>c.feedingBytes&&(c.data=new DataView(t.buffer,t.byteOffset+d,c.loadedBytes),await this.onDownloadItem(u))))}}updateRepresentationBaseUrl(e,t){if(We(e.segmentReference))throw new Error("Representation is not byte range type");e.segmentReference.url=t}};var Zt=require("@vkontakte/videoplayer-shared/es2018");var Ur=class extends qr{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:s,...n}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),!r.aborted)try{let o=await this.fetcher.fetch(s,{...n,priority:i});if(this.lastDataObtainedTimestampMs=(0,Zt.now)(),(0,Zt.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(),xt(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,Zt.now)(),await this.onSomeDataLoaded({downloadingItems:e,dataView:n,loaded:o,signal:r,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:Zt.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}},signal:r,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}getFetchUrl(e,t){if(!We(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:s}){let n=e[0],{segment:o}=n,u=this.representations.get(i);!this.downloadingBufferItems.length||(0,Zt.isNullable)(u)||(0,Zt.isNullable)(o.feedingBytes)||o.networkStatus!=="downloading"||s.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(!We(e.segmentReference))throw new Error("Representation is not template type");e.segmentReference.baseUrl=t}};var Al=G(Fa(),1),Py=G(ft(),1);var Le=require("@vkontakte/videoplayer-shared/es2018");var Io=class extends Ur{constructor(t,i,r,s){super(t,i,r,s);this.currentLiveSegmentServerLatency$=new Le.ValueSubject(0);this.currentLowLatencySegmentLength$=new Le.ValueSubject(0);this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.isActiveLowLatency=s.isActiveLowLatency}updateManifest(t){var r,s,n;if(!t||[...this.segments.values()].every(o=>!o.length))return;let i=(0,Al.default)(t.streams[this.kind],o=>o.representations);for(let o of i){if((0,Le.isNullable)(o)||!We(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>({...h,networkStatus:"none",bufferStatus:"none",size:void 0})),c=100,d=(r=this.segments.get(o.id))!=null?r:[],l=(n=(s=(0,Py.default)(d,-1))==null?void 0:s.time.to)!=null?n:0,p=u==null?void 0:u.findIndex(h=>l>=h.time.from+c&&l<=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,[...d,...h])}this.representations.set(o.id,o)}}proceedLowLatencyLive(){let t=this.downloadingRepresentationId;(0,Le.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,Al.default)(i,n=>n.representations).find(n=>n.id===this.downloadingRepresentationId);if((0,Le.isNullable)(r))return;let s=this.segments.get(r.id);if(s!=null&&s.length)return{from:s[0].time.from,to:s[s.length-1].time.to}}getRepresentationInitialTime(){var r;if((0,Le.isNullable)(this.playingRepresentationId))return 0;let t=(r=this.representations.get(this.playingRepresentationId))==null?void 0:r.segmentReference;return(0,Le.isNullable)(t)||!We(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,Le.isNullable)(t.segment.data)||!this.isActiveLowLatency())return;let i=t.segment.data,r=this.containerParser,{serverDataReceivedTimestamp:s,serverDataPreparedTime:n}=r.getServerLatencyTimestamps(i);s&&n&&this.currentLiveSegmentServerLatency$.next(n-s),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,Le.isNullable)(t.segment.data)||(0,Le.isNullable)(r)||!We(r))return;let s=this.containerParser;if(t.segment.isCurrentLowLatency){let{timescale:o}=r;t.segment.time.to=s.getChunkEndTime(i,o)}}updateLowLatencyLive(t){var r;let i=0;for(let s of this.representations.values()){let n=s.segmentReference;if(!We(n))return;let o=(r=this.segments.get(s.id))!=null?r:[],u=o.find(d=>Math.floor(d.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(d=>Math.floor(d.time.from)===Math.floor(t.segment.time.to))&&this.isActiveLowLatency()){let d=Math.round(t.segment.time.to*n.timescale/1e3).toString(10),l=Pt(n.segmentTemplateUrl,{segmentTime:d});o.push({networkStatus:"none",bufferStatus:"none",time:{from:t.segment.time.to,to:t.segment.time.to+this.tuning.dash.bufferTolerance},url:l,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 s;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:d}=(s=await o)!=null?s:{};if(this.initDataPromises.delete(t.id),(0,Le.isNullable)(c)||(0,Le.isNullable)(d))return;u&&this.parsedInitData.set(t.id,u);let l=this.getActualLiveStartingSegments(t.segmentReference);this.segments.has(t.id)||this.segments.set(t.id,l);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:Le.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,s=[],n=0,o=i.length-1;do s.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()?[s[0]]:s}};var vs=class{static getBufferManager(e,t,i,r){var s;return(s=r.manifest)!=null&&s.live?new Io(e,t,i,r):We(i[0].segmentReference)?new Ur(e,t,i,r):new To(e,t,i,r)}};var ze=require("@vkontakte/videoplayer-shared/es2018");var Ii=require("@vkontakte/videoplayer-shared/es2018");var q$=18,ky=!1;try{ky=H.browser.isSafari&&!!H.browser.safariVersion&&H.browser.safariVersion<=q$}catch(a){console.error(a)}var Rl=class{constructor(e,t=!1){this.bufferFull$=new Ii.Subject;this.error$=new Ii.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:Ii.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 s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};ky&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!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(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Ii.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),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,Ii.assertNever)(t)}}},Ay=Rl;var Ei=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var Ss=class{constructor(e){this.error$=new ze.Subject;this.subscription=new ze.Subscription;this.mediaSource=e}init(e,t,i=!1){this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e}; codecs="${t}"`),this.sourceBufferTaskQueue=new Ay(this.sourceBuffer,i),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(r=>this.error$.next(r))),this.subscription.add((0,ze.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:ze.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,ze.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,ze.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}getBufferState(){if((0,ze.isNullable)(this.sourceBuffer)||!ge(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,ze.isNullable)(this.sourceBuffer)||!ge(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,ze.isNullable)(e)?0:Ei(this.sourceBuffer.buffered,e)}async abortBuffer(e){return(0,ze.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 Eo=(a,e)=>{a.video.forEach(t=>{let i=t.representations.filter(({fps:r,height:s})=>{var o;let n=(o=e.find(([u])=>u===`${s}p`))==null?void 0:o[1];return n&&Number.isInteger(n)&&r&&Number.isInteger(r)?r<=n:!0});t.representations=i})};var U$=["timeupdate","progress","play","seeked","stalled","waiting"],Ry=["timeupdate","progress","loadeddata","playing","seeked"],wo=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 ve;this.state$=new re("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 s;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,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?(s=this.audioBufferManager)==null?void 0:s.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 lo({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)(...U$.map(r=>(0,I.fromEvent)(this.element,r)),(0,I.fromEvent)((0,I.getWindow)(),"online")).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(),s=>this.error$.next({id:"StallWatchdogCallback",category:I.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:s})),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,s,n,o;(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=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),this.element.currentTime=i/1e3,await this.videoBufferManager.seek(i),await((o=this.audioBufferManager)==null?void 0:o.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(){var e,t;return Math.max(((e=this.videoBufferManager)==null?void 0:e.calculateDurationFromSegments())||0,((t=this.audioBufferManager)==null?void 0:t.calculateDurationFromSegments())||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,s;let t=(s=(r=this.videoNativeBufferManager)==null?void 0:r.getBufferState())!=null?s:[];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))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)(),s=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,d=(0,I.isNonNullable)(this.videoBufferManager)&&u<s&&r-n>i,l=(0,I.isNonNullable)(this.audioBufferManager)&&c<s&&r-o>i;return(d||l)&&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 fo(e!=null?e:"",this.manifestUrlString)}catch(i){let r=(t=no(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 d,l,p,h;return!!((l=(d=this.element)==null?void 0:d.canPlayType)!=null&&l.call(d,u)&&((h=(p=nt())==null?void 0:p.isTypeSupported)!=null&&h.call(p,`${u}; codecs="${c}"`))||o==="text")},r,s;for(let o of["video","audio"]){let c=e.streams[o].filter(({mime:l,codecs:p})=>i(o,l,p));t[o]=c;let d;if(this.tuning.dash.codecsPrioritizeEnabled){let l=c.map(({codecs:p})=>p);o==="audio"&&(s=So(l),d=s[0]),o==="video"&&(r=vo(l),this.forceVideoCodec&&(0,My.default)(r,this.forceVideoCodec)?d=this.forceVideoCodec:d=r[0]),d&&(t[o]=c.filter(({codecs:p})=>Nr(p)===d))}else{let l=new Set(c.map(({codecs:p})=>p));d=go(l),d&&(t[o]=c.filter(({codecs:p})=>p.startsWith(d)))}if(o==="video"){let l=this.tuning.preferHDR,p=t.video.some(b=>b.hdr),h=t.video.some(b=>!b.hdr);H.display.isHDR&&l&&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&&Eo(t,m)}}let n={...e,streams:t};return this.tuning.dash.codecsPrioritizeEnabled&&(n.codecs={video:r,audio:s}),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 s=c=>{this.representationSubscription.add((0,I.fromEvent)(c,"error").pipe((0,I.filter)(d=>{var l;return!!((l=this.element)!=null&&l.played.length)})).subscribe(d=>{this.error$.next({id:"VideoSource",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:d})}))};this.source=dn();let n=(0,I.getWindow)().document,o=n.createElement("source");if(s(o),o.src=URL.createObjectURL(this.source),this.element.appendChild(o),yr())if(r){let c=n.createElement("source");s(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,d)=>[...c,...d.representations],[]);if(this.videoNativeBufferManager=new Ss(this.source),this.videoBufferManager=vs.getBufferManager("video",this.videoNativeBufferManager,u,e),this.bufferManagers=[this.videoBufferManager],this.nativeBufferManagers=[this.videoNativeBufferManager],(0,I.isNonNullable)(i)){this.audioNativeBufferManager=new Ss(this.source);let c=this.manifest.streams.audio.reduce((d,l)=>[...d,...l.representations],[]);this.audioBufferManager=vs.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)(...Ry.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)(...Ry.map(e=>(0,I.fromEvent)(this.element,e))).pipe((0,I.map)(e=>{var t,i,r,s;return Math.max((i=(t=this.videoBufferManager)==null?void 0:t.getForwardPlaybackBufferDuration())!=null?i:0,(s=(r=this.audioBufferManager)==null?void 0:r.getForwardPlaybackBufferDuration())!=null?s: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,s,n;if((0,I.isNullable)(this.element)||(0,I.isNullable)(this.videoBufferManager)||this.isStreamNotOpen)return;let e=this.element.currentTime*1e3,i=((s=(r=this.videoNativeBufferManager)==null?void 0:r.getBufferState())!=null?s:[]).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 he=require("@vkontakte/videoplayer-shared/es2018");var xo=class extends wo{constructor(e){super(e)}prepareManifestUrlString(e,t){return e}initRepresentationSubscriptions(){super.initRepresentationSubscriptions(),this.initDisableStallWatchdogSubscription(),this.initEndOfVideoSubscription()}setSourceDuration(){var t;(0,he.assertNonNullable)(this.manifest),(0,he.assertNonNullable)(this.source);let e=[(t=this.manifest.duration)!=null?t:0,...(0,Ml.default)((0,Ml.default)([...this.manifest.streams.audio,...this.manifest.streams.video],i=>i.representations),i=>{let r=[];return i.duration&&r.push(i.duration),We(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,he.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,he.assertNonNullable)(this.element);let e=(0,he.merge)((0,he.fromEvent)(this.element,"ended"),this.forceEnded$),t=this.nativeBufferLength$.pipe((0,he.filter)(i=>i>this.tuning.dash.bufferEmptinessTolerance));this.representationSubscription.add((0,he.merge)(e,t).subscribe(i=>this.stopStallWatchdogSubscription()))}initEndOfVideoSubscription(){let e=(0,he.merge)(...this.bufferManagers.map(s=>s.fullyBuffered$)).pipe((0,he.map)(()=>this.bufferManagers.every(s=>s.fullyBuffered$.getValue()))),t=(0,he.merge)(...this.bufferManagers.map(s=>s.onLastSegment$)).pipe((0,he.map)(()=>this.bufferManagers.some(s=>s.onLastSegment$.getValue()))),i=(0,he.combine)({allBuffersFull:e,someBufferEnded:t}).pipe((0,he.filterChanged)(),(0,he.map)(({allBuffersFull:s,someBufferEnded:n})=>s&&n),(0,he.filter)(s=>s)),r=()=>{var s;try{(s=this.source)==null||s.endOfStream()}catch(n){this.error$.next({id:"EndOfStream",category:he.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:n})}};this.representationSubscription.add((0,he.merge)(this.forceEnded$,i).pipe((0,he.filter)(s=>(0,he.isNonNullable)(this.source)&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(n=>!n.updating))).subscribe(r))}};var jr=class extends Na{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,$y.filterChanged)()).subscribe(s=>{let n=[...this.videoTracksMap.entries()].find(([,{representation:l}])=>l.id===s);if(!n){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[o,{stream:u}]=n,c=this.params.desiredState.videoStream.getTransition();c&&c.to&&c.to.id===u.id&&this.params.desiredState.videoStream.setState(c.to),e.currentVideoTrack$.next(o),e.currentVideoStream$.next(Jn(u));let d=this.player.calculateDurationFromSegments();d&&this.params.output.duration$.next(d/1e3)},r))}getPlayer(){return new xo({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 Q=require("@vkontakte/videoplayer-shared/es2018");var By=G(Ye(),1),Ll=G(Fa(),1);var wi=(a,e,t=0)=>{for(let i=0;i<a.length;i++)if(a.start(i)*1e3-t<=e&&a.end(i)*1e3+t>e)return!0;return!1};var T=require("@vkontakte/videoplayer-shared/es2018");var Po=G(Ye(),1),er=G(ft(),1),ko=G(Fa(),1);var Ly=G(Fc(),1);var xi=require("@vkontakte/videoplayer-shared/es2018");var j$=18,Cy=!1;try{Cy=H.browser.isSafari&&!!H.browser.safariVersion&&H.browser.safariVersion<=j$}catch(a){console.error(a)}var $l=class{constructor(e,t=!1){this.bufferFull$=new xi.Subject;this.error$=new xi.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:xi.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 s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};Cy&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!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(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:xi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),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,xi.assertNever)(t)}}},Dy=$l;var Cl=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};var P=require("@vkontakte/videoplayer-shared/es2018");var ys=class{constructor(e,t,i,{fetcher:r,tuning:s,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 ve;this.switchAbortController=new ve;this.destroyAbortController=new ve;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 Dy(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||!ge(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Cl(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let c=this.getForwardBufferDuration(o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,c<d).catch(l=>{this.handleAsyncError(l,"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),s=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(s))}.bind(this));this.switchTo=(0,P.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!ge(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),s=this.initData.get(e);if((0,P.isNullable)(s)||(0,P.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,P.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!ge(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,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(!ge(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),s=this.initData.get(e);if((0,P.isNullable)(s)||(0,P.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,P.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!ge(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,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,ko.default)(e,c=>c.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let c of this.representations.keys()){let d=t.find(h=>h.id===c);d&&this.representations.set(c,d);let l=this.representations.get(c);if(!l||!ct(l.segmentReference)){this.isSeekingLive=!1;return}let p=this.getActualLiveStartingSegments(l.segmentReference);this.segments.set(l.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 s=this.segments.get(i);(0,P.assertNonNullable)(s,"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(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var d;this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(c!=null&&c.live),this.baseUrls=(d=c==null?void 0:c.baseUrls)!=null?d:[],this.initData=new Map(i.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(l=>[l.id,l])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!ge(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ve,(0,P.abortable)(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);(0,P.assertNonNullable)(s,`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(s,"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||!ge(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 ve,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)||!ge(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),s=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)(s))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=Ti(i),b=Ti(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(F=>e>=F.time.from&&e<F.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)&&Cl(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 d=[];if(!this.activeSegments.size&&(d=this.selectForwardBufferSegments(r,t.segmentReference.type,o),d.length)){let h="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,Po.default)(d,n))h="high";else{let m=(0,er.default)(d,0);m&&m.time.from-n.time.to>=this.forwardBufferTarget/2&&(h="low")}this.loadSegments(d,t,h).catch(m=>{this.handleAsyncError(m,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!d.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,er.default)(r,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<u),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.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=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.streams[this.kind];if(!t)return;let i=(0,ko.default)(t,s=>s.representations).find(s=>s.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,s;if(!e||[...this.segments.values()].every(n=>!n.length))return;let t=(0,ko.default)(e.streams[this.kind],n=>n.representations);for(let n of t){if(!n||!ct(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:[],d=(s=(r=(0,er.default)(c,-1))==null?void 0:r.time.to)!=null?s:0,l=o==null?void 0:o.findIndex(p=>d>=p.time.from+u&&d<=p.time.to+u);if(l===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(n.segmentReference);this.segments.set(n.id,p)}else{let p=o.slice(l+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,er.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 s=r.segmentReference;if(!ct(s))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*s.timescale/1e3).toString(10),d=Pt(s.segmentTemplateUrl,{segmentTime:c});n.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s: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&&Ki&&Ki(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Ki&&Ki(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),s=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&&ge(this.mediaSource,this.sourceBuffer)&&!(wi(this.sourceBuffer.buffered,h)&&wi(this.sourceBuffer.buffered,m)))&&v&&x});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let n=e,o=0,u=0,c=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let p=s;p<n.length&&(o<=d||u<=l);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"){ct(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:s,url:n,signal:o,onProgress:u,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await(0,P.abortable)(o,async function*(){let d=(0,P.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=(0,P.now)(),!d)return;let l=new DataView(d),p=Zi(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=p.getChunkEndTime(l,b)}u&&r.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(l,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=p.getServerLatencyTimestamps(l);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),xt(d)||(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())ct(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:s,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(s,{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),xt(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(ct(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,er.default)(e,0).byte.from,to:(0,er.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,P.now)(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,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(!ct(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:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(c,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,P.now)();let l=this.onSomeTemplateDataLoaded({dataView:c,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(l)}catch(l){this.error$.next({id:"SegmentFeeding",category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Po.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!ge(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(s.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),d=Zi(n.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!ge(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(s.aborted){await n();continue}let d=c.byte.from-i,l=c.byte.to-i,p=l-d+1,h=d<r,m=l<=r;if(!h)continue;let b=Zi(o.mime);if(c.status==="downloading"&&m){c.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+d,p);await this.sourceBufferTaskQueue.append(S,s)&&!s.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-d),u.loadedBytes>u.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+d+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,s)&&!s.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)||!ge(this.mediaSource,this.sourceBuffer))){!this.isLive&&H.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(wi(this.sourceBuffer.buffered,e.segment.time.from,100)&&wi(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",kl(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let s of(i=this.segments.get(r.id))!=null?i:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.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,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Yi(()=>(0,Ly.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",s=!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,Zi(e.mime),{priority:r,ignoreNetworkErrors:s})).then(async u=>{if(!u)return;let{init:c,dataView:d,segments:l}=u,p=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,p);let h=l;this.isLive&&ct(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=>{s||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||!ge(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,P.isNullable)(e))return!1;let r=[],s=0,n=u=>{u.sort((d,l)=>d.from-l.from);let c=[u[0]];for(let d=1;d<u.length;d++){let{from:l,to:p}=u[d],h=c[c.length-1];h.to>=l?h.to=Math.max(h.to,p):c.push(u[d])}return c},o=u=>{var d;if(s>=t)return r;r.push({...u.time}),r=n(r);let c=kl(u)?(d=u.size)!=null?d:0:u.byte.to-u.byte.from;s+=c};for(let u of this.segments.values())for(let c of u){let d=c.time.to<=e-this.tuning.dash.bufferPruningSafeZone,l=c.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||l)&&c.status==="fed"&&o(c)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let c=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,l=0;for(let p of this.segments.values())for(let h of p)(0,Po.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(d)&&l++;if(l===this.segments.size){let p={time:{from:c,to:d},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 d of c)d.time.from>=e+u&&d.status==="fed"&&o(d)}return r.length?(await Promise.all(r.map(c=>this.sourceBufferTaskQueue.remove(c.from,c.to)))).reduce((c,d)=>c||d,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!ge(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||!ge(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||!ge(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,P.isNullable)(e)?0:Ei(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!ge(this.mediaSource,this.sourceBuffer)))for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to,persistent:!1},{buffered:s}=this.sourceBuffer;for(let n=0;n<s.length;n++){let o=s.start(n)*1e3,u=s.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||!ge(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,{usePersistentGaps:r}=this.tuning.dash;this.gaps=this.gaps.filter(s=>{if(r&&s.persistent)return!0;let n=Math.round(s.from),o=Math.round(s.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=Yi(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:P.ErrorCategory.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if((0,P.isNullable)(this.sourceBuffer)||!ge(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),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(d=>d.from-t<=n&&d.to+t>=o),c=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(c.length===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.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 U=require("@vkontakte/videoplayer-shared/es2018");var Ro=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested$=new U.Subject;this.firstBytesManifest$=new U.Subject;this.firstBytesRequested$=new U.Subject;this.firstBytesReceived$=new U.Subject;this.lastConnectionType$=new U.ValueSubject(void 0);this.lastConnectionReused$=new U.ValueSubject(void 0);this.lastRequestFirstBytes$=new U.ValueSubject(void 0);this.lastConnectionMetrics$=new U.ValueSubject(void 0);this.lastDownloadMetrics$=new U.ValueSubject(void 0);this.recoverableError$=new U.Subject;this.error$=new U.Subject;this.abortAllController=new ve;this.subscription=new U.SubscriptionRemovable;this.performanceObserver=null;this.pendingConnectionMetrics=new Map;this.fetchManifest=(0,U.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Si(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=uo(i)),this.trackRequestStart(i,performance.now());let r=(0,U.now)();this.manifestRequested$.next();let s=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Ao);if(s){let n=(0,U.now)();t.log("success",(0,U.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(s.headers),this.firstBytesManifest$.next();let o=s.headers.get("content-length"),u=0;o&&(u=parseInt(o,10));let c=await s.text();if((!o||isNaN(u)||u<=0)&&(u=new TextEncoder().encode(c).length),u>0){let d=n-r,p=u/(d/1e3)*8/1024,h={bytes:u,speed:p,url:e};this.lastDownloadMetrics$.next(h)}return c}else return t.error("error",(0,U.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null}.bind(this));this.fetch=(0,U.abortable)(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:c=!1,ignoreNetworkErrors:d=!1}={}){var ce,ne,A;let l=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(l,(0,U.getWindow)().location.href);$.searchParams.append("bytes",`${i.from}-${i.to}`),l=$.toString();break}default:(0,U.assertNever)(t)}this.requestQuic&&(l=Si(l));let m=this.abortAllController.signal,b;if(n){let $=new ve;if(b=(0,U.merge)((0,U.fromEvent)(this.abortAllController.signal,"abort"),(0,U.fromEvent)(n,"abort")).subscribe(()=>{try{$.abort()}catch(k){Ao(k)}}),this.subscription.add(b),this.abortAllController.signal.aborted||n.aborted)try{$.abort()}catch(k){Ao(k)}m=$.signal}let S=0,v=(0,U.now)();h.log("startRequest",(0,U.flattenObject)({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:v})),this.trackRequestStart(l,performance.now()),this.firstBytesRequested$.next();let y=yield this.doFetch(l,{priority:s,headers:p,signal:m},{ignoreNetworkErrors:d}),x=(0,U.now)();if(!y)return h.error("error",{message:"No response in request"}),h.end(),this.unsubscribeAbortSubscription(b),null;if((ce=this.throughputEstimator)==null||ce.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,U.now)(),k={requestStartedAt:v,requestEndedAt:$,duration:$-v};return h.log("endRequest",(0,U.flattenObject)(k)),h.end(),y.arrayBuffer()}let w=y.body;if(o){let $;[w,$]=y.body.tee(),(ne=this.throughputEstimator)==null||ne.trackStream($,u)}let M=w.getReader(),_,F=parseInt((A=y.headers.get("content-length"))!=null?A:"",10);Number.isFinite(F)&&(_=F),!_&&i&&(_=i.to-i.from+1);let O=_?new Uint8Array(_):new Uint8Array(0),j=!1,V=$=>{this.unsubscribeAbortSubscription(b),j=!0,Ao($)},W=(0,U.abortable)(m,async function*({done:$,value:k}){if(S===0&&(this.lastRequestFirstBytes$.next((0,U.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(W,V)}}.bind(this));yield M==null?void 0:M.read().then(W,V),this.unsubscribeAbortSubscription(b);let N=(0,U.now)(),te={failed:j,requestStartedAt:v,requestEndedAt:N,duration:N-v};if(j)return h.error("endRequest",(0,U.flattenObject)(te)),h.end(),null;if(S>0){let $=N-v,R=S/($/1e3)*8/1024,X={bytes:S,speed:R,url:e};this.lastDownloadMetrics$.next(X)}return h.log("endRequest",(0,U.flattenObject)(te)),h.end(),O.buffer}.bind(this));this.fetchByteRangeRepresentation=(0,U.abortable)(this.abortAllController.signal,async function*(e,t,i){var v;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,c,d;e.indexRange&&(c=e.indexRange.from,d=e.indexRange.to,u=s+1===c,u&&(n=Math.min(c,r),o=Math.max(d,s))),n=Math.min(n,0);let l=yield this.fetch(e.url,{range:{from:n,to:o},measureThroughput:!1,...i});if(!l)return null;let p=new DataView(l,r-n,s-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(l,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(l),segments:S}}.bind(this));this.fetchTemplateRepresentation=(0,U.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=s,(0,U.getWindow)().PerformanceObserver&&this.setupPerformanceObserver()}onHeadersReceived(e){let{type:t,reused:i}=oo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}setupPerformanceObserver(){this.performanceObserver=new((0,U.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,U.getWindow)().navigator))return"unknown";let e=(0,U.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,s=0;return e.domainLookupStart>0&&e.domainLookupEnd>0&&(t=e.domainLookupEnd-e.domainLookupStart),e.connectStart>0&&e.connectEnd>0&&(s=e.connectEnd-e.connectStart,e.secureConnectionStart>0?(r=e.connectEnd-e.secureConnectionStart,i=e.secureConnectionStart-e.connectStart):i=s),{dnsResolveTime:Math.max(0,t),tcpHandshakeTime:Math.max(0,i),tlsHandshakeTime:Math.max(0,r),totalConnectTime:Math.max(0,s),networkType:this.estimateNetworkType(),url:e.name}}findMatchingRequest(e){try{for(let[t,i]of this.pendingConnectionMetrics.entries()){let r=new URL(e.name),s=r.origin+r.pathname,n=new URL(i.url),o=n.origin+n.pathname;if(s===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:U.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 s,n;let{type:r}=e;switch(r){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:(0,U.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 bt(e,t);if(r.ok)return r;if(i!=null&&i.ignoreNetworkErrors)return;let s=await r.text(),n=parseInt(s);if(!isNaN(n))switch(n){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:U.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:U.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:U.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:U.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${n})`,category:U.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:s})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Ao=a=>{if(!xt(a))throw a};var Ts=require("@vkontakte/videoplayer-shared/es2018"),Pi=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 Ts.ValueSubject(e.initial),this.debounced$=new Ts.ValueSubject(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new He(`raw_${t}`),this.smoothedSeries$=new He(`smoothed_${t}`),this.reportedSeries$=new He(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,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),s=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>s||this.smoothed<n)&&((0,Ts.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 Pi{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Kt(this.slow,e,this.params.emaAlphaSlow),this.fast=Kt(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 Pi{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=al(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Kt(this.emaSmoothed,e,this.params.emaAlpha);let i=Pv(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Co=class extends Pi{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?Kt(this.smoothed,t,this.params.emaAlpha):t}};var tr=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 Co({initial:e,label:"liveEdgeDelay",...t})}};var Dl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var Do=require("@vkontakte/videoplayer-shared/es2018");var Is=class a{constructor(e,t){this.currentRepresentation$=new Do.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,Do.isNullable)(e))for(let i of this.representations)for(let r of i){let s=r.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let c=s.segments.find(d=>d.time.from<=e&&d.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,s.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=a.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=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&ct(t.segmentReference))}};var W$=["timeupdate","progress","play","seeked","stalled","waiting"],z$=["timeupdate","progress","loadeddata","playing","seeked"];var Lo=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 re("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 ve;this.initManifest=(0,T.abortable)(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Fe(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(d=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:T.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:d})});if(!e)return null;let t=null;try{t=fo(e!=null?e:"",this.manifestUrlString),this.manifestReceived$.next()}catch(d){let l=(u=no(e))!=null?u:{id:"ManifestParsing",category:T.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:d};this.error$.next(l)}if(!t)return null;let i=(d,l,p)=>{var h,m,b,S;return!!((m=(h=this.element)==null?void 0:h.canPlayType)!=null&&m.call(h,l)&&((S=(b=nt())==null?void 0:b.isTypeSupported)!=null&&S.call(b,`${l}; codecs="${p}"`))||d==="text")};if(t.live){this.isLive$.next(!0);let{availabilityStartTime:d,latestSegmentPublishTime:l,streamIsUnpublished:p,streamIsAlive:h}=t.live,m=((c=t.duration)!=null?c:0)/1e3;this.liveSeekableDuration$.next(-1*m),this.liveDuration$.next((l-d)/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:[]},s,n;for(let d of["video","audio"]){let p=t.streams[d].filter(({mime:m,codecs:b})=>i(d,m,b));r[d]=p;let h;if(this.tuning.dash.codecsPrioritizeEnabled){let m=p.map(({codecs:b})=>b);d==="audio"&&(n=So(m),h=n[0]),d==="video"&&(s=vo(m),this.forceVideoCodec&&(0,By.default)(s,this.forceVideoCodec)?h=this.forceVideoCodec:h=s[0]),h&&(r[d]=p.filter(({codecs:b})=>Nr(b)===h))}else{let m=new Set(p.map(({codecs:b})=>b));h=go(m),h&&(r[d]=p.filter(({codecs:b})=>b.startsWith(h)))}if(d==="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&&Eo(r,v)}}let o={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:s,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 l;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=dn();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),yr())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 ys("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 ys("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}if(Is.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Is(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,T.merge)(...z$.map(p=>(0,T.fromEvent)(this.element,p))).pipe((0,T.map)(p=>this.element?Ei(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=an(this.manifestUrlString,2);this.manifestUrlString=Fe(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()||Dl(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=an(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),Dl(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=an(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(),F=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(F);let O="none";if(_?O="active_low_latency":this.isLowLatency$.getValue()&&F?(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)),W=Math.abs(V-S),N=0;!h||W<=this.tuning.dashCmafLive.offsetCalculationError?N=S:V>0&&W>this.tuning.dashCmafLive.offsetCalculationError&&(N=V),this.manifestUrlString=Fe(this.manifestUrlString,N,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()))),d=(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$,d).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=[(l=this.manifest.duration)!=null?l:0,...(0,Ll.default)((0,Ll.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),ct(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,s;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||(s=this.audioBufferManager)!=null&&s.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 Ro({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=tr.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=Fe(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)(...W$.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&&wi(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var w,M,_,F,O,j,V,W,N,te,ce;let{keepSilentStallWatchdogWhenNotActive:t}=this.tuning.dashCmafLive,{crashOnStallTimeout:i,crashOnStallTWithoutDataTimeout:r,liveStallReinitInterval:s,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 d=this.currentStallDuration$.getValue();d+=n,this.currentStallDuration$.next(d);let l={timeInWaiting:d},p=(0,T.now)(),h=100,m=(_=(M=this.videoBufferManager)==null?void 0:M.lastDataObtainedTimestamp)!=null?_:0;this.videoLastDataObtainedTimestamp$.next(m);let b=(O=(F=this.audioBufferManager)==null?void 0:F.lastDataObtainedTimestamp)!=null?O:0,S=(V=(j=this.videoBufferManager)==null?void 0:j.getForwardBufferDuration())!=null?V:0,v=(N=(W=this.audioBufferManager)==null?void 0:W.getForwardBufferDuration())!=null?N:0,y=S<h&&p-m>r,x=this.audioBufferManager&&v<h&&p-b>r;if((!t||c)&&((y||x)&&d>r||d>=i))throw new Error(`Stall timeout exceeded: ${d} ms`);if(o&&d%s===0){let ne=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);!c&&t?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(ne),this.updateManifest()):this.seekLive(ne).catch(A=>{this.error$.next({id:"stallIntervalCallback",category:T.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:A})}),l.liveLastOffset=ne}else{let ne=this.element.currentTime*1e3;(te=this.videoBufferManager)==null||te.maintain(ne),(ce=this.audioBufferManager)==null||ce.maintain(ne),l.position=ne}this.tracer.log("stallIntervalCallback",(0,T.flattenObject)(l))};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,s,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=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),wi(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 s=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<=s&&c.to+o>s&&(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 it=require("@vkontakte/videoplayer-shared/es2018"),Bo=class{constructor(){this.subscription=new it.Subscription;this.pipSize$=new it.ValueSubject(void 0);this.videoSize$=new it.ValueSubject(void 0);this.elementSize$=new it.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=it.noop}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add((0,it.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,it.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,it.map)(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var ir=class{constructor(e){this.subscription=new Q.Subscription;this.videoState=new re("stopped");this.observableVideo=null;this.droppedFramesManager=new Dr;this.stallsManager=new io;this.elementSizeManager=new Bo;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new bi;this.audioTrackSwitchHistory=new bi;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,Q.assertNever)(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new Lr(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:((s=e.projectionData)==null?void 0:s.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 ht(e.source.url),this.params=e,this.video=Ke(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ue(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Lo({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,Q.isNullable)(this.observableVideo)&&(this.observableVideo=Ze(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:Q.ErrorCategory.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,Q.filter)(l=>!!l.length),(0,Q.once)()).subscribe(l=>{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:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,Q.map)(l=>l.to.state!=="none"),(0,Q.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}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.currentBuffer$,e.currentNativeBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.manifestRequested$,e.manifestRequested$),s(this.player.firstBytesManifest$,e.firstBytesManifest$),s(this.player.manifestReceived$,e.manifestReceived$),s(this.player.firstBytesRequested$,e.firstBytesRequested$),s(this.player.firstBytesReceived$,e.firstBytesReceived$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.lastConnectionMetrics$,e.httpConnectionMetrics$),s(this.player.lastDownloadMetrics$,e.httpDownloadMetrics$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe((0,Q.filter)(Q.isNonNullable),(0,Q.once)()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe((0,Q.map)(l=>l.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(_t(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),vi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(Je(this.video,t.volume,i.volumeState$,r)),this.subscription.add(pt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(mt(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:l})=>{if(l==="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,Q.assertNonNullable)(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let b=[];for(let S of p.audio){b.push(xl(S));let v=[];for(let y of S.representations){let x=gs(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(Pl(b));let S=[];for(let v of b.representations){let y=Ti({...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=Ey(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 l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let o=(0,Q.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,Q.fromEvent)(this.video,"progress")).pipe((0,Q.filter)(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe((0,Q.throttle)(u))),this.subscription.add(o.subscribe(async()=>{let l=this.player.state$.getState(),p=this.player.state$.getTransition();if(l!=="manifest_ready"&&l!=="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,Q.isNonNullable)(S)&&(this.stallsManager.lastVideoTrackSelected=S);let v=this.params.desiredState.autoVideoTrackLimits.getTransition();if(v&&this.params.output.autoVideoTrackLimits$.next(v.to),l==="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,Q.combine)({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:(0,Q.merge)((0,Q.observableFrom)([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,Q.map)(l=>l.to)))}).pipe((0,Q.map)(({videoState:l,autoVideoTrackState:p})=>l.to!=="stopped"&&p),(0,Q.filterChanged)()).subscribe(l=>this.player.setSmartRepresentationSwitch(l))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,Q.filterChanged)()).subscribe(l=>{let p=[...this.videoTracksMap.entries()].find(([,{representation:v}])=>v.id===l);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(Pl(m));let S=this.player.calculateDurationFromSegments();S&&this.params.output.duration$.next(S/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,Q.filterChanged)()).subscribe(l=>{let p=[...this.audioTracksMap.entries()].find(([,{representation:S}])=>S.id===l);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(xl(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var p,h;if(l!=null&&l.is3dVideo&&((p=this.params.tuning.spherical)!=null&&p.enabled))try{this.init3DScene(l),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,Q.map)(({to:l})=>l==="ready"),(0,Q.filterChanged)());this.subscription.add((0,Q.merge)(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,Q.observableFrom)(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add((0,Q.merge)(c,this.player.state$.stateChangeEnded$,(0,Q.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=(0,Q.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,Q.observableFrom)(["init"])).pipe((0,Q.debounce)(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var O,j,V,W,N,te,ce,ne,A,$,k,R,X;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Ca:$a,t=this.params.tuning.useNewAutoSelectVideoTrack?Yn:Gn,i=this.params.tuning.useNewAutoSelectVideoTrack?Ot:zn,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(O=r.videoTrack.getState())==null?void 0:O.id,u=[...this.videoTracksMap.keys()].find(({id:Y})=>Y===o),c=s.currentVideoTrack$.getValue(),d=((W=(V=r.videoStream.getState())!=null?V:u&&((j=this.videoTracksMap.get(u))==null?void 0:j.stream))!=null?W:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let l=[...this.videoStreamsMap.keys()].find(({id:Y})=>Y===d.id),p=l&&this.videoStreamsMap.get(l);if(!p)return;let h=Ei(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=(N=r.audioStream.getState())!=null?N:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,y=(te=[...this.audioStreamsMap.keys()].find(({id:Y})=>Y===(v==null?void 0:v.id)))!=null?te:this.audioStreamsMap.keys().next().value,x=0;if(y){if(u&&!n){let Y=e(u,p,(ce=this.audioStreamsMap.get(y))!=null?ce:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,(ne=Y==null?void 0:Y.bitrate)!=null?ne:-1/0)}if(c){let Y=e(c,p,(A=this.audioStreamsMap.get(y))!=null?A:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,($=Y==null?void 0:Y.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,F=M&&((X=this.audioTracksMap.get(M))==null?void 0:X.representation);if(_&&F)return[_,F];if(_&&!F&&this.audioTracksMap.size===0)return[_,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){et(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:Q.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),Xe(this.video),this.tracer.end()}};var Es=class extends ir{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var me=require("@vkontakte/videoplayer-shared/es2018");var ws=class extends ir{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,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 me.ValueSubject(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe((0,me.filterChanged)()).subscribe(u=>{let c=i.position$.getValue(),d=i.volume$.getValue(),l=!d.volume||d.muted;!u&&!c&&l?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe((0,me.map)(u=>u.to)).subscribe(this.player.isLowLatency$)).add((0,me.combine)({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,me.map)(({liveBufferTime:u,liveAvailabilityStartTime:c})=>u&&c?u*1e3+c+t:void 0)).subscribe(i.liveTime$)).add((0,me.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,me.merge)(r.playbackRateState$,new me.ValueSubject(1))}).pipe((0,me.filter)(({liveStreamStatus:u,liveDuration:c})=>u==="active"&&!!c)).subscribe(({liveDuration:u,playbackRate:c})=>{let d=i.liveBufferTime$.getValue(),l=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;l||c<1-p||this.video.paused||(0,me.isNullable)(d)||(t=u-d)})).add((0,me.combine)({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,me.merge)(r.playbackRateState$,new me.ValueSubject(1))}).pipe((0,me.filterChanged)((u,c)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===c.liveDuration:u.time===c.time)).subscribe(({time:u,liveDuration:c,playbackRate:d})=>{let l=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;if(!l&&!this.video.paused&&d>=1-p||(0,me.isNullable)(u)||(0,me.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=wy(u);this.params.output.availableTextTracks$.next([c])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe((0,me.filter)(u=>(0,me.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 Vy="X-Playback-Duration",Bl=async a=>{var r;let e=await bt(a),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(Vy)?parseInt(e.headers.get(Vy),10):void 0};var se=require("@vkontakte/videoplayer-shared/es2018");var _l=G(ec(),1);var Vo=require("@vkontakte/videoplayer-shared/es2018");var Y$=a=>{let e=null;if(a.QUALITY&&(e=mi(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=(0,Vo.videoSizeToQuality)({width:t,height:i})}return e!=null?e:null},K$=(a,e)=>{var s,n;let t=a.split(`
178
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var sy=a=>{if(!(a!=null&&a.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(a),r=(i==null?void 0:i[1])==="-"?-1:1,s={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 s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},Pt=(a,e)=>{let t=a;t=(0,yl.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,ny.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,yl.default)(t,n,(o,u)=>(0,ja.isNullable)(s)?o:(0,ja.isNullable)(u)?s:(0,oy.default)(s,parseInt(u,10),"0"))}return t},fo=(a,e)=>{var j,V,W,N,te,ce,ne,A,$,k,R,X,Y,At,Rt,de,Be,Ve,_e,rt,Ut,jt,ki,ar,sr,Wl,zl,Gl,Yl,Kl,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;let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(vt=>{var be,Ai;return(Ai=(be=vt.textContent)==null?void 0:be.trim())!=null?Ai:""}),o=(j=(0,uy.default)(n,0))!=null?j:"",u=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),d=s.getAttribute("publishTime"),l=s.getElementsByTagName("vk:Attrs")[0],p=l==null?void 0:l.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=l==null?void 0:l.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=l==null?void 0:l.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=l==null?void 0:l.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,S;u&&(S={availabilityStartTime:c?new Date(c).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:p?new Date(p).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:m==="yes"});let v,y=s.getAttribute("mediaPresentationDuration"),x=[...s.getElementsByTagName("Period")],w=x.reduce((vt,be)=>({...vt,[be.id]:be.children}),{}),M=x.reduce((vt,be)=>({...vt,[be.id]:be.getAttribute("duration")}),{});y?v=sy(y):(0,Tl.default)(M).filter(vt=>vt).length&&!u?v=(0,Tl.default)(M).reduce((vt,be)=>{var Ai;return vt+((Ai=sy(be))!=null?Ai:0)},0):b&&(v=parseInt(b,10));let _=0,F=(W=(V=s.getAttribute("profiles"))==null?void 0:V.split(","))!=null?W:[];for(let vt of x.map(be=>be.id))for(let be of w[vt]){let Ai=(N=be.getAttribute("id"))!=null?N:"id"+(_++).toString(10),zr=(te=be.getAttribute("mimeType"))!=null?te:"",qo=(ce=be.getAttribute("codecs"))!=null?ce:"",Uo=(ne=be.getAttribute("contentType"))!=null?ne:zr==null?void 0:zr.split("/")[0],aT=($=(A=be.getAttribute("profiles"))==null?void 0:A.split(","))!=null?$:[],Ad=(R=ay((k=be.getAttribute("lang"))!=null?k:""))!=null?R:{},Cs=(At=(Y=(X=be.querySelector("Label"))==null?void 0:X.textContent)==null?void 0:Y.trim())!=null?At:void 0,sT=be.querySelectorAll("Representation"),nT=be.querySelector("SegmentTemplate"),oT=(de=(Rt=be.querySelector("Role"))==null?void 0:Rt.getAttribute("value"))!=null?de:void 0,nr=Uo,Pe={id:Ai,language:Ad.language,isDefault:oT==="main",label:Cs,codecs:qo,hdr:nr==="video"&&Sl(qo),mime:zr,representations:[]};for(let fe of sT){let ii=(Be=fe.getAttribute("lang"))!=null?Be:void 0,Ds=(_e=(Ve=Cs!=null?Cs:be.getAttribute("label"))!=null?Ve:fe.getAttribute("label"))!=null?_e:void 0,Ls=(jt=(Ut=(rt=fe.querySelector("BaseURL"))==null?void 0:rt.textContent)==null?void 0:Ut.trim())!=null?jt:"",Ri=new URL(Ls||o,e).toString(),ri=(ki=fe.getAttribute("mimeType"))!=null?ki:zr,Bs=(sr=(ar=fe.getAttribute("codecs"))!=null?ar:qo)!=null?sr:"",Vs;if(Uo==="text"){let ai=fe.getAttribute("id")||"",_s=((Wl=Ad.privateuse)==null?void 0:Wl.includes("x-auto"))||ai.includes("_auto"),Mi=fe.querySelector("SegmentTemplate");if(Mi){let Gr={representationId:(zl=fe.getAttribute("id"))!=null?zl:void 0,bandwidth:(Gl=fe.getAttribute("bandwidth"))!=null?Gl:void 0},Os=parseInt((Yl=fe.getAttribute("bandwidth"))!=null?Yl:"",10)/1e3,Ns=(Xl=parseInt((Kl=Mi.getAttribute("startNumber"))!=null?Kl:"",10))!=null?Xl:1,or=parseInt((Jl=Mi.getAttribute("timescale"))!=null?Jl:"",10),jo=(Zl=Mi.querySelectorAll("SegmentTimeline S"))!=null?Zl:[],ur=Mi.getAttribute("media");if(!ur)continue;let Fs=[],qs=0,Us="",cr=0,Yr=Ns,je=0;for(let St of jo){let $i=parseInt((ed=St.getAttribute("d"))!=null?ed:"",10),dt=parseInt((td=St.getAttribute("r"))!=null?td:"",10)||0,si=parseInt((id=St.getAttribute("t"))!=null?id:"",10);je=Number.isFinite(si)?si:je;let Ci=$i/or*1e3,ni=je/or*1e3;for(let Mt=0;Mt<dt+1;Mt++){let oi=Pt(ur,{...Gr,segmentNumber:Yr.toString(10),segmentTime:(je+Mt*$i).toString(10)}),lr=(ni!=null?ni:0)+Mt*Ci,Xr=lr+Ci;Yr++,Fs.push({time:{from:lr,to:Xr},url:oi})}je+=(dt+1)*$i,qs+=(dt+1)*Ci}cr=je/or*1e3,Us=Pt(ur,{...Gr,segmentNumber:Yr.toString(10),segmentTime:je.toString(10)});let Kr={time:{from:cr,to:1/0},url:Us},Ht={type:"template",baseUrl:Ri,segmentTemplateUrl:ur,initUrl:"",totalSegmentsDurationMs:qs,segments:Fs,nextSegmentBeyondManifest:Kr,timescale:or};Vs={id:ai,kind:"text",segmentReference:Ht,profiles:[],duration:v,bitrate:Os,mime:"",codecs:"",width:0,height:0,isAuto:_s}}else Vs={id:ai,isAuto:_s,kind:"text",url:Ri}}else{let ai=(ad=(rd=fe.getAttribute("contentType"))!=null?rd:ri==null?void 0:ri.split("/")[0])!=null?ad:Uo,_s=(nd=(sd=be.getAttribute("profiles"))==null?void 0:sd.split(","))!=null?nd:[],Mi=parseInt((od=fe.getAttribute("width"))!=null?od:"",10),Gr=parseInt((ud=fe.getAttribute("height"))!=null?ud:"",10),Os=parseInt((cd=fe.getAttribute("bandwidth"))!=null?cd:"",10)/1e3,Ns=(ld=fe.getAttribute("frameRate"))!=null?ld:"",or=(dd=fe.getAttribute("quality"))!=null?dd:void 0,jo=Ns?ry(Ns):void 0,ur=(pd=fe.getAttribute("id"))!=null?pd:"id"+(_++).toString(10),Fs=ai==="video"?`${Gr}p`:ai==="audio"?`${Os}Kbps`:Bs,qs=`${ur}@${Fs}`,Us=[...F,...aT,..._s],cr,Yr=fe.querySelector("SegmentBase"),je=(hd=fe.querySelector("SegmentTemplate"))!=null?hd:nT;if(Yr){let Ht=(md=(fd=fe.querySelector("SegmentBase Initialization"))==null?void 0:fd.getAttribute("range"))!=null?md:"",[St,$i]=Ht.split("-").map(oi=>parseInt(oi,10)),dt={from:St,to:$i},si=(bd=fe.querySelector("SegmentBase"))==null?void 0:bd.getAttribute("indexRange"),[Ci,ni]=si?si.split("-").map(oi=>parseInt(oi,10)):[],Mt=si?{from:Ci,to:ni}:void 0;cr={type:"byteRange",url:Ri,initRange:dt,indexRange:Mt}}else if(je){let Ht={representationId:(gd=fe.getAttribute("id"))!=null?gd:void 0,bandwidth:(vd=fe.getAttribute("bandwidth"))!=null?vd:void 0},St=parseInt((Sd=je.getAttribute("timescale"))!=null?Sd:"",10),$i=(yd=je.getAttribute("initialization"))!=null?yd:"",dt=je.getAttribute("media"),si=(Id=parseInt((Td=je.getAttribute("startNumber"))!=null?Td:"",10))!=null?Id:1,Ci=Pt($i,Ht);if(!dt)throw new ReferenceError("No media attribute in SegmentTemplate");let ni=(Ed=je.querySelectorAll("SegmentTimeline S"))!=null?Ed:[],Mt=[],oi=0,lr="",Xr=0;if(ni.length){let js=si,yt=0;for(let dr of ni){let $t=parseInt((wd=dr.getAttribute("d"))!=null?wd:"",10),Di=parseInt((xd=dr.getAttribute("r"))!=null?xd:"",10)||0,Hs=parseInt((Pd=dr.getAttribute("t"))!=null?Pd:"",10);yt=Number.isFinite(Hs)?Hs:yt;let Ho=$t/St*1e3,Qo=yt/St*1e3;for(let Qs=0;Qs<Di+1;Qs++){let cT=Pt(dt,{...Ht,segmentNumber:js.toString(10),segmentTime:(yt+Qs*$t).toString(10)}),Rd=(Qo!=null?Qo:0)+Qs*Ho,lT=Rd+Ho;js++,Mt.push({time:{from:Rd,to:lT},url:cT})}yt+=(Di+1)*$t,oi+=(Di+1)*Ho}Xr=yt/St*1e3,lr=Pt(dt,{...Ht,segmentNumber:js.toString(10),segmentTime:yt.toString(10)})}else if((0,ja.isNonNullable)(v)){let yt=parseInt((kd=je.getAttribute("duration"))!=null?kd:"",10)/St*1e3,dr=Math.ceil(v/yt),$t=0;for(let Di=1;Di<dr;Di++){let Hs=Pt(dt,{...Ht,segmentNumber:Di.toString(10),segmentTime:$t.toString(10)});Mt.push({time:{from:$t,to:$t+yt},url:Hs}),$t+=yt}Xr=$t,lr=Pt(dt,{...Ht,segmentNumber:dr.toString(10),segmentTime:$t.toString(10)})}let uT={time:{from:Xr,to:1/0},url:lr};cr={type:"template",baseUrl:Ri,segmentTemplateUrl:dt,initUrl:Ci,totalSegmentsDurationMs:oi,segments:Mt,nextSegmentBeyondManifest:uT,timescale:St}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ai||!ri)continue;let Kr={video:"video",audio:"audio",text:"text"}[ai];if(!Kr)continue;nr||(nr=Kr),Vs={id:qs,kind:Kr,segmentReference:cr,profiles:Us,duration:v,bitrate:Os,mime:ri,codecs:Bs,width:Mi,height:Gr,fps:jo,quality:or}}Pe.language||(Pe.language=ii),Pe.label||(Pe.label=Ds),Pe.mime||(Pe.mime=ri),Pe.codecs||(Pe.codecs=Bs),Pe.hdr||(Pe.hdr=nr==="video"&&Sl(Bs)),Pe.representations.push(Vs)}if(nr){let fe=r[nr].find(ii=>ii.id===Pe.id);if(fe&&Pe.representations.every(ii=>ii.segmentReference.type==="template"))for(let ii of fe.representations){let Ds=Pe.representations.find(ri=>ri.id===ii.id);if(!Ds)continue;let Ls=Ds.segmentReference,Ri=ii.segmentReference;Ri.segments.push(...Ls.segments),Ri.nextSegmentBeyondManifest=Ls.nextSegmentBeyondManifest}else r[nr].push(Pe)}}return{duration:v,streams:r,baseUrls:n,live:S}};var bo=G(ft(),1),Il=G(Ye(),1),Qa=require("@vkontakte/videoplayer-shared/es2018");var Ha=(s=>(s.VP9="vp9",s.AV1="av1",s.NONE="none",s.SMOOTH="smooth",s.POWER_EFFICIENT="power_efficient",s))(Ha||{});var mo=a=>{let{webmDecodingInfo:e}=H.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(a){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,Qa.assertNever)(a)}},cy=({webmCodec:a,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...mo(a),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],s=[...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[...s,"MPEG",...mo(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...mo(a),"MPEG",...s,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...mo(a),...s,"HLS","HLS_ONDEMAND"];default:(0,Qa.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,Qa.assertNever)(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},ly=({androidPreferredFormat:a,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"],s=[...i,...r],n=[...r,...i],o,u=H.device.isMac&&H.browser.isSafari;if(H.device.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:(0,Qa.assertNever)(a)}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=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},El=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],go=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,bo.default)(t.value.split("."),0)}for(let t of a){let i=(0,bo.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,bo.default)(e.value.split("."),0)},vo=a=>{let e=a.map(i=>Nr(i)),{codecs:t}=H.video;return T$().filter(i=>{if((0,Il.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})},So=a=>{let e=a.map(i=>Nr(i)),{codecs:t}=H.video;return I$().filter(i=>{if((0,Il.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},Nr=a=>a.split(".")[0].replace("0",""),T$=()=>["av1","vp9","hev1","avc1"],I$=()=>["opus","mp4a"];var xy=G(ft(),1);var E$=(a,e={})=>{let i=e.timeout||1,r=performance.now();return Re.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},w$=a=>Re.clearTimeout(a),dy=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),py=!dy(Re.requestIdleCallback)||!dy(Re.cancelIdleCallback),Yi=py?E$:Re.requestIdleCallback,Ki=py?w$:Re.cancelIdleCallback;var D=require("@vkontakte/videoplayer-shared/es2018");var fy=G(ft(),1);var yo=a=>a.valid,ue=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,s;i===0?(this.size=void 0,this.valid=!1,s=void 0):i===1?(this.size=void 0,this.valid=!1,s=void 0):i>e.byteLength?(this.size=i,this.valid=!1,s=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,s=i-this.cursor),this.content=new DataView(e.buffer,r,s)}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 Fr=class extends ue{};var hy=require("@vkontakte/videoplayer-shared/es2018");var Wa=class extends ue{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,hy.assertNever)(e)}}};var za=class extends ue{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 s=this.readString(4);this.compatibleBrands.push(s)}}};var Ga=class extends ue{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ye=class extends ue{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 Ya=class extends ye{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 Ka=class extends ue{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Xa=class extends ue{constructor(e,t){super(e,t),this.data=this.content}};var Xi=class extends ye{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(),s=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,c=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:c})}}}};var Ja=class extends ue{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Za=class extends ue{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var es=class extends ye{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 ts=class extends ye{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var is=class extends ye{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 rs=class extends ue{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var as=class extends ye{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 ss=class extends ue{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ns=class extends ue{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var os=class extends ye{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var us=class extends ue{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var cs=class extends ye{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 ls=class extends ye{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 ds=class extends ye{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 ps=class extends ue{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var hs=class extends ye{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 fs=class extends ue{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 P$={ftyp:za,moov:Ga,mvhd:Ya,moof:Ka,mdat:Xa,sidx:Xi,trak:Ja,mdia:rs,mfhd:os,tkhd:as,traf:us,tfhd:cs,tfdt:ls,trun:ds,minf:ss,sv3d:Za,st3d:es,prhd:ts,proj:ns,equi:is,uuid:Wa,stbl:ps,stsd:hs,avc1:fs,unknown:Fr},Xt=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n;try{n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(o){if(!(o instanceof RangeError))throw o}if(!n||!yo(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=P$[e];return i?new i(t,new a):new Fr(t,new a)}};var yi=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,s;yo(t)&&((s=(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 A$=new TextDecoder("ascii"),R$=a=>A$.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",M$=a=>{let e=new Xi(a,new Xt),t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},$$=(a,e)=>{let i=new Xt().parse(a),r=new yi(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],c=o.source.byteOffset,l=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,c,l)},C$=a=>{let t=new Xt().parse(a),i=new yi(t),r={},s=i.findAll("uuid"),n=(0,fy.default)(s,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},D$=a=>{var r;let t=new Xt().parse(a);return(r=new yi(t).find("sidx"))==null?void 0:r.timescale},L$=(a,e)=>{let i=new Xt().parse(a),s=new yi(i).findAll("traf"),n=s[s.length-1].children.find(l=>l.type==="tfhd"),o=s[s.length-1].children.find(l=>l.type==="tfdt"),u=s[s.length-1].children.find(l=>l.type==="trun"),c=0;return u.sampleDuration.length?c=u.sampleDuration.reduce((l,p)=>l+p,0):c=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+c)/e*1e3},B$=a=>{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 Xt().parse(a),r=new yi(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},my={validateData:R$,parseInit:B$,getIndexRange:()=>{},parseSegments:M$,parseFeedableSegmentChunk:$$,getChunkEndTime:L$,getServerLatencyTimestamps:C$,getTimescaleFromIndex:D$};var bs=G(Ye(),1),Jt=require("@vkontakte/videoplayer-shared/es2018");var gy=require("@vkontakte/videoplayer-shared/es2018");var by={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"}},vy=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=ms(a,t),r=i in by,s=r?by[i].type:"binary",n=a.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(a.buffer,a.byteOffset+t+1,o-1),c=n&255>>o,d=ms(u),l=c*2**((o-1)*8)+d,p=t+o,h;return p+l>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,l),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+l,value:h,valueSize:l}},ms=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},kt=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return ms(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:(0,gy.assertNever)(e)}},Ji=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=vy(i);if(!e(r))return;r.type==="master"&&Ji(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},Sy=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=vy(a);return Ji(r.value,({tag:s,type:n,value:o})=>(s===17143?e=kt(o,n):s===17026?t=kt(o,n):s===17029&&(i=kt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var yy=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],V$=[231,22612,22743,167,171,163,160,175],_$=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,c,d=!1,l=0;return Ji(a,({tag:p,type:h,value:m,valueSize:b})=>{if(p===21419){let S=kt(m,h);c=ms(S)}else p!==21420&&(c=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?i=kt(m,h):p===17545?r=kt(m,h):p===21420&&c===475249515?u=kt(m,h):p===374648427?Ji(m,({tag:S,type:v,value:y})=>S===30321?(d=kt(y,v)===1,!1):!0):s&&n&&(0,bs.default)(yy,p)&&(o=!0),!o}),(0,Jt.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,Jt.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,Jt.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:d,stereoMode:l,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},O$=a=>{if((0,Jt.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},N$=(a,e)=>{let t=!1,i=!1,r=o=>(0,Jt.isNonNullable)(o.time)&&(0,Jt.isNonNullable)(o.position),s=[],n;return Ji(a,({tag:o,type:u,value:c})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=kt(c,u));break;case 183:break;case 241:n&&(n.position=kt(c,u));break;default:t&&(0,bs.default)(yy,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((o,u)=>{let{time:c,position:d}=o,l=s[u+1];return{status:"none",time:{from:c,to:l?l.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:l?e.segmentStart+l.position-1:e.segmentEnd-1}}})},F$=a=>{let e=0,t=!1;try{Ji(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,bs.default)(V$,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||(t=(0,bs.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},Ty={validateData:Sy,parseInit:_$,getIndexRange:O$,parseSegments:N$,parseFeedableSegmentChunk:F$};var Zi=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Ty;case"mp4":return my}}throw new ReferenceError(`Unsupported mime type ${a}`)};var wl=G(ft(),1);var Iy=require("@vkontakte/videoplayer-shared/es2018"),Ti=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?mi(s):void 0)!=null?u:(0,Iy.videoSizeToQuality)({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},gs=({id:a,bitrate:e})=>({id:a,bitrate:e}),Ey=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),wy=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),xl=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,wl.default)(i.split("."),0),isDefault:r}),Pl=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,wl.default)(r.split("."),0)}),kl=a=>"url"in a,ct=a=>a.type==="template";var qr=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,manifest:o}){this.error$=new D.Subject;this.playingRepresentation$=new D.ValueSubject(void 0);this.playingRepresentationInit$=new D.ValueSubject(void 0);this.currentSegmentLength$=new D.ValueSubject(0);this.onLastSegment$=new D.ValueSubject(!1);this.fullyBuffered$=new D.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 ve;this.downloadAbortController=new ve;this.subscription=new D.Subscription;this.startWith=(0,D.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,D.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.containerParser=Zi(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),s=this.parsedInitData.get(t.id);(0,D.assertNonNullable)(i,"No init buffer for starting representation"),(0,D.assertNonNullable)(r,"No segments for starting representation"),await this.nativeBufferManager.addInitSegment(i),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s)}.bind(this));this.switchTo=(0,D.abortable)(this.destroyAbortController.signal,async function*(e,t=!0){var l;if((0,D.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,D.assertNonNullable)(r,`No such representation ${e}`),(0,D.assertNonNullable)(i,`No such representation ${this.downloadingRepresentationId}`),yield this.loadInitIfNeeded(r,"high");let s=this.initData.get(r.id),n=this.segments.get(r.id);(0,D.assertNonNullable)(s,"No init buffer for switching representation"),(0,D.assertNonNullable)(n,"No segments for switching representation");let o=(l=this.getCurrentPosition())!=null?l:0,u=p=>p.segment.networkStatus!=="downloaded"||p.segment.time.to-o>this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment,c=p=>{let h=this.representations.get(p.representationId);return(0,D.assertNonNullable)(h,"No itemRepresentation for previous track before switch"),p.segment.networkStatus!=="downloaded"||this.forceSwitchCondition(h,r)},d=p=>t?u(p)&&c(p):u(p);this.bufferPlaybackQueue.filter(d).forEach(p=>p.segment.bufferStatus="none"),this.bufferPlaybackQueue=this.bufferPlaybackQueue.filter(p=>!d(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,D.abortable)(this.downloadAbortController.signal,async function*(){let e=(0,D.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(t=>{let i=(0,D.getWindow)();this.loadByteRangeSegmentsTimeoutId=i.setTimeout(t,e),this.subscription.add((0,D.fromEvent)(i,"online").pipe((0,D.once)()).subscribe(()=>{t(),i.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}))})}.bind(this));var u;this.kind=e,this.nativeBufferManager=t,this.fetcher=r,this.tuning=s,this.getCurrentPosition=n,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.baseUrls=(u=o==null?void 0:o.baseUrls)!=null?u:[],this.representations=new Map(i.map(c=>[c.id,c]))}async seek(e){await this.abort(),await this.clearBuffer(),await this.maintain(e)}async maintain(e=this.getCurrentPosition()){(0,D.isNullable)(e)||(await this.maintainPlaybackBuffer(e),await this.maintainNativeBuffer(),this.actualizeLastSegmentInfo(e))}getForwardPlaybackBufferDuration(e=this.getCurrentPosition()){let t=this.getPlaybackBufferState();return(0,D.isNonNullable)(t)&&(0,D.isNonNullable)(e)?t.to-e:0}getPlaybackBufferState(){if(!this.bufferPlaybackQueue.length)return null;let t=this.bufferPlaybackQueue[0].segment.time.from,i=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segment.time.to;return{from:t,to:i}}async abort(){this.abortDownload(),await this.abortNativeBuffer()}findSegmentStartTime(e){var s,n;let t=(n=(s=this.downloadingRepresentationId)!=null?s: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,D.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(){var t;if((0,D.isNullable)(this.playingRepresentationId))return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(t=(0,xy.default)(e,-1))==null?void 0:t.time.to:0)||0}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){let e=(0,D.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_10c8n03b79nlf)for(let t of this.idleCallbacks.values())e.__polyfill_cancelIdleCallback_10c8n03b79nlf(t);this.idleCallbacks.clear(),e.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}forceSwitchCondition(e,t){let i=!0;if(this.kind==="video"){let r=Ti(e),s=Ti(t);i=(0,D.isNonNullable)(r)&&(0,D.isNonNullable)(s)&&(0,D.isHigher)(s.quality,r.quality)}else if(this.kind==="audio"){let r=gs(e),s=gs(t);i=(0,D.isNonNullable)(r==null?void 0:r.bitrate)&&(0,D.isNonNullable)(s==null?void 0:s.bitrate)&&s.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 ve,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,Yi(async r=>await this.loadInitIfNeeded(i,"low",!1)))}async loadInitIfNeeded(e,t="auto",i=!1){let r=this.initDataPromises.get(e.id),s;this.initData.has(e.id)&&this.segments.has(e.id)?s=Promise.resolve():(0,D.isNonNullable)(r)?s=r:s=this.loadInit(e,t,i),await s}async loadInit(e,t="auto",i=!1){var r;try{let s=this.tuning.dash.useFetchPriorityHints?t:"auto",n=this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,s);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,D.isNullable)(u)||(0,D.isNullable)(c))return;o&&this.parsedInitData.set(e.id,o);let d=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,d),this.segments.set(e.id,c),this.failedDownloads=0}catch(s){i&&this.error$.next({id:"LoadInits",category:D.ErrorCategory.WTF,message:"loadInit threw",thrown:s})}}async maintainNativeBuffer(){var o;let e=this.getCurrentPosition();if((0,D.isNullable)(e)||this.maintainNativeBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex||this.preloadOnly)return;this.maintainNativeBufferMutex=!0;let t=this.bufferPlaybackQueue.find(u=>this.withinInterval(e,u.segment.time)),i=this.bufferPlaybackQueue.find(u=>u.segment.bufferStatus!=="fed"),r=this.initData.get((o=i==null?void 0:i.representationId)!=null?o:""),s=this.bufferPlaybackQueue[0],n=this.downloadAbortController.signal;(0,D.isNonNullable)(r)&&(0,D.isNonNullable)(i)&&(0,D.isNonNullable)(t)&&this.playingRepresentationId!==i.representationId&&this.withinAppendInterval(e,i.segment.time)&&(i===t||t.segment.bufferStatus==="fed")&&(await this.abortNativeBuffer(),await this.nativeBufferManager.addInitSegment(r,this.downloadAbortController.signal),this.playingRepresentationId=i.representationId,this.playingRepresentation$.next(this.playingRepresentationId)),(0,D.isNonNullable)(i)&&this.withinAppendInterval(e,i.segment.time)&&(i.segment.loadedBytes===i.segment.size&&i.segment.bufferStatus==="none"?await this.appendSegmentFully(i,n):await this.appendSegmentPartially(i,n)),(0,D.isNonNullable)(s)&&this.withinRemoveInterval(e,s.segment.time)&&await this.removeSegment(s,n),this.pruneVirtualBuffer(e),this.maintainNativeBufferMutex=!1}async maintainPlaybackBuffer(e){(0,D.assertNonNullable)(this.downloadingRepresentationId);let t=this.segments.get(this.downloadingRepresentationId),i=this.representations.get(this.downloadingRepresentationId);if((0,D.isNullable)(t)||(0,D.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,D.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 s=this.selectItemsToLoad();await this.loadItems(s,i),this.maintainPlaybackBufferMutex=!1}actualizeLastSegmentInfo(e){var r;let t=this.segments.get((r=this.downloadingRepresentationId)!=null?r:"");if((0,D.isNullable)(t)||t.length===0)return;let i=t[(t==null?void 0:t.length)-1];(0,D.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,D.assertNonNullable)(this.downloadingRepresentationId);let i=this.getPlaybackBufferState(),r,s;(0,D.isNonNullable)(i)&&this.withinInterval(e,i)?(s=this.forwardBufferTarget-this.getForwardPlaybackBufferDuration(e),r=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segmentIndex+1):(s=this.forwardBufferTarget,r=t.findIndex(o=>this.withinInterval(e,o.time))),r=r===-1?0:r;let n=[];for(;r<t.length&&s>0;){n.push({representationId:this.downloadingRepresentationId,segmentIndex:r,segment:t[r]});let{from:o,to:u}=t[r].time;s-=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,D.isNonNullable)(e)?e+r>=t&&e<i:!1}withinAppendInterval(e,{from:t,to:i}){let{actionTimeShiftFromSegment:r}=this.tuning.dash;return(0,D.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,D.isNonNullable)(e)?e-i>t:!1}async appendSegmentFully(e,t){if((0,D.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,D.isNullable)(e.segment.data)||(0,D.isNullable)(e.segment.loadedBytes)||(0,D.isNullable)(e.segment.feedingBytes)||(0,D.isNullable)(e.segment.fedBytes)||(0,D.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),s=e.segment.loadedBytes!==e.segment.size?this.parseFeedableSegmentChunk(r):r;s!=null&&s.byteLength&&(e.segment.bufferStatus="partially_fed",e.segment.feedingBytes+=s.byteLength,await this.nativeBufferManager.append(s,t)&&(e.segment.fedBytes+=s.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,s=(r-i)/4;await this.nativeBufferManager.remove(0,r-s,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,D.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 s=this.currentVirtualBufferSize-t+i;for(let n of this.segments.values())for(let o of n)(0,D.isNonNullable)(o.size)&&s>0&&o.time.to<=e-r&&o.bufferStatus==="none"&&o.networkStatus==="downloaded"&&(o.data=null,o.networkStatus="none",this.currentVirtualBufferSize-=o.size,s-=o.size);for(let n of this.segments.values())for(let o of[...n].reverse())(0,D.isNonNullable)(o.size)&&s>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,s-=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 Ft=require("@vkontakte/videoplayer-shared/es2018");var To=class extends qr{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:s,...n}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),!r.aborted)try{await this.fetcher.fetch(s,{...n,priority:i}),this.lastDataObtainedTimestampMs=(0,Ft.now)(),this.failedDownloads=0}catch(o){this.abortDownloadingItems(),xt(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=0,t=0,i=[],r=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,s=this.preloadOnly?this.forwardBufferTarget:0,n=0;for(;n<this.downloadingBufferItems.length&&this.downloadingBufferItems[n].segment.networkStatus==="none"&&(e<=r||t<=s);){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(We(t.segmentReference))throw new Error("Representation is not byte range type");let{signal:i}=this.downloadAbortController,r=t.segmentReference.url,s={from:e[0].segment.byte.from,to:e[e.length-1].segment.byte.to};return{url:r,range:s,onProgress:async(o,u)=>{if(!i.aborted)try{this.lastDataObtainedTimestampMs=(0,Ft.now)(),await this.onSomeDataLoaded({downloadingItems:e,dataView:o,loaded:u,signal:i,globalFrom:s?s.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:Ft.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:s,signal:n}){let o=this.representations.get(i);if(!(!this.downloadingBufferItems.length||(0,Ft.isNullable)(o)||(0,Ft.isNullable)(r)||n.aborted))for(let u of e){let{segment:c}=u,d=c.byte.from-r,l=c.byte.to-r,p=l-d+1,h=d<s,m=l<=s;c.size=p,h&&(c.networkStatus==="downloading"&&c.bufferStatus==="none"&&m?(c.data=new DataView(t.buffer,t.byteOffset+d,p),this.currentVirtualBufferSize+=c.size,this.onItemFullyDownloaded(u),c.loadedBytes=Math.min(p,s-d),await this.onDownloadItem(u)):(0,Ft.isNonNullable)(c.feedingBytes)&&this.tuning.dash.enableSubSegmentBufferFeeding&&c.networkStatus==="downloading"&&(c.loadedBytes=Math.min(p,s-d),m&&(this.currentVirtualBufferSize+=c.size,this.onItemFullyDownloaded(u)),c.loadedBytes>c.feedingBytes&&(c.data=new DataView(t.buffer,t.byteOffset+d,c.loadedBytes),await this.onDownloadItem(u))))}}updateRepresentationBaseUrl(e,t){if(We(e.segmentReference))throw new Error("Representation is not byte range type");e.segmentReference.url=t}};var Zt=require("@vkontakte/videoplayer-shared/es2018");var Ur=class extends qr{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:s,...n}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),!r.aborted)try{let o=await this.fetcher.fetch(s,{...n,priority:i});if(this.lastDataObtainedTimestampMs=(0,Zt.now)(),(0,Zt.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(),xt(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,Zt.now)(),await this.onSomeDataLoaded({downloadingItems:e,dataView:n,loaded:o,signal:r,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:Zt.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}},signal:r,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}getFetchUrl(e,t){if(!We(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:s}){let n=e[0],{segment:o}=n,u=this.representations.get(i);!this.downloadingBufferItems.length||(0,Zt.isNullable)(u)||(0,Zt.isNullable)(o.feedingBytes)||o.networkStatus!=="downloading"||s.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(!We(e.segmentReference))throw new Error("Representation is not template type");e.segmentReference.baseUrl=t}};var Al=G(Fa(),1),Py=G(ft(),1);var Le=require("@vkontakte/videoplayer-shared/es2018");var Io=class extends Ur{constructor(t,i,r,s){super(t,i,r,s);this.currentLiveSegmentServerLatency$=new Le.ValueSubject(0);this.currentLowLatencySegmentLength$=new Le.ValueSubject(0);this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.isActiveLowLatency=s.isActiveLowLatency}updateManifest(t){var r,s,n;if(!t||[...this.segments.values()].every(o=>!o.length))return;let i=(0,Al.default)(t.streams[this.kind],o=>o.representations);for(let o of i){if((0,Le.isNullable)(o)||!We(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>({...h,networkStatus:"none",bufferStatus:"none",size:void 0})),c=100,d=(r=this.segments.get(o.id))!=null?r:[],l=(n=(s=(0,Py.default)(d,-1))==null?void 0:s.time.to)!=null?n:0,p=u==null?void 0:u.findIndex(h=>l>=h.time.from+c&&l<=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,[...d,...h])}this.representations.set(o.id,o)}}proceedLowLatencyLive(){let t=this.downloadingRepresentationId;(0,Le.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,Al.default)(i,n=>n.representations).find(n=>n.id===this.downloadingRepresentationId);if((0,Le.isNullable)(r))return;let s=this.segments.get(r.id);if(s!=null&&s.length)return{from:s[0].time.from,to:s[s.length-1].time.to}}getRepresentationInitialTime(){var r;if((0,Le.isNullable)(this.playingRepresentationId))return 0;let t=(r=this.representations.get(this.playingRepresentationId))==null?void 0:r.segmentReference;return(0,Le.isNullable)(t)||!We(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,Le.isNullable)(t.segment.data)||!this.isActiveLowLatency())return;let i=t.segment.data,r=this.containerParser,{serverDataReceivedTimestamp:s,serverDataPreparedTime:n}=r.getServerLatencyTimestamps(i);s&&n&&this.currentLiveSegmentServerLatency$.next(n-s),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,Le.isNullable)(t.segment.data)||(0,Le.isNullable)(r)||!We(r))return;let s=this.containerParser;if(t.segment.isCurrentLowLatency){let{timescale:o}=r;t.segment.time.to=s.getChunkEndTime(i,o)}}updateLowLatencyLive(t){var r;let i=0;for(let s of this.representations.values()){let n=s.segmentReference;if(!We(n))return;let o=(r=this.segments.get(s.id))!=null?r:[],u=o.find(d=>Math.floor(d.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(d=>Math.floor(d.time.from)===Math.floor(t.segment.time.to))&&this.isActiveLowLatency()){let d=Math.round(t.segment.time.to*n.timescale/1e3).toString(10),l=Pt(n.segmentTemplateUrl,{segmentTime:d});o.push({networkStatus:"none",bufferStatus:"none",time:{from:t.segment.time.to,to:t.segment.time.to+this.tuning.dash.bufferTolerance},url:l,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 s;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:d}=(s=await o)!=null?s:{};if(this.initDataPromises.delete(t.id),(0,Le.isNullable)(c)||(0,Le.isNullable)(d))return;u&&this.parsedInitData.set(t.id,u);let l=this.getActualLiveStartingSegments(t.segmentReference);this.segments.has(t.id)||this.segments.set(t.id,l);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:Le.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,s=[],n=0,o=i.length-1;do s.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()?[s[0]]:s}};var vs=class{static getBufferManager(e,t,i,r){var s;return(s=r.manifest)!=null&&s.live?new Io(e,t,i,r):We(i[0].segmentReference)?new Ur(e,t,i,r):new To(e,t,i,r)}};var ze=require("@vkontakte/videoplayer-shared/es2018");var Ii=require("@vkontakte/videoplayer-shared/es2018");var q$=18,ky=!1;try{ky=H.browser.isSafari&&!!H.browser.safariVersion&&H.browser.safariVersion<=q$}catch(a){console.error(a)}var Rl=class{constructor(e,t=!1){this.bufferFull$=new Ii.Subject;this.error$=new Ii.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:Ii.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 s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};ky&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!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(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Ii.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),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,Ii.assertNever)(t)}}},Ay=Rl;var Ei=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var Ss=class{constructor(e){this.error$=new ze.Subject;this.subscription=new ze.Subscription;this.mediaSource=e}init(e,t,i=!1){this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e}; codecs="${t}"`),this.sourceBufferTaskQueue=new Ay(this.sourceBuffer,i),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(r=>this.error$.next(r))),this.subscription.add((0,ze.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:ze.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,ze.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,ze.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}getBufferState(){if((0,ze.isNullable)(this.sourceBuffer)||!ge(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,ze.isNullable)(this.sourceBuffer)||!ge(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,ze.isNullable)(e)?0:Ei(this.sourceBuffer.buffered,e)}async abortBuffer(e){return(0,ze.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 Eo=(a,e)=>{a.video.forEach(t=>{let i=t.representations.filter(({fps:r,height:s})=>{var o;let n=(o=e.find(([u])=>u===`${s}p`))==null?void 0:o[1];return n&&Number.isInteger(n)&&r&&Number.isInteger(r)?r<=n:!0});t.representations=i})};var U$=["timeupdate","progress","play","seeked","stalled","waiting"],Ry=["timeupdate","progress","loadeddata","playing","seeked"],wo=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 ve;this.state$=new re("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 s;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,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?(s=this.audioBufferManager)==null?void 0:s.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 lo({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)(...U$.map(r=>(0,I.fromEvent)(this.element,r)),(0,I.fromEvent)((0,I.getWindow)(),"online")).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(),s=>this.error$.next({id:"StallWatchdogCallback",category:I.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:s})),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,s,n,o;(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=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),this.element.currentTime=i/1e3,await this.videoBufferManager.seek(i),await((o=this.audioBufferManager)==null?void 0:o.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(){var e,t;return Math.max(((e=this.videoBufferManager)==null?void 0:e.calculateDurationFromSegments())||0,((t=this.audioBufferManager)==null?void 0:t.calculateDurationFromSegments())||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,s;let t=(s=(r=this.videoNativeBufferManager)==null?void 0:r.getBufferState())!=null?s:[];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))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)(),s=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,d=(0,I.isNonNullable)(this.videoBufferManager)&&u<s&&r-n>i,l=(0,I.isNonNullable)(this.audioBufferManager)&&c<s&&r-o>i;return(d||l)&&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 fo(e!=null?e:"",this.manifestUrlString)}catch(i){let r=(t=no(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 d,l,p,h;return!!((l=(d=this.element)==null?void 0:d.canPlayType)!=null&&l.call(d,u)&&((h=(p=nt())==null?void 0:p.isTypeSupported)!=null&&h.call(p,`${u}; codecs="${c}"`))||o==="text")},r,s;for(let o of["video","audio"]){let c=e.streams[o].filter(({mime:l,codecs:p})=>i(o,l,p));t[o]=c;let d;if(this.tuning.dash.codecsPrioritizeEnabled){let l=c.map(({codecs:p})=>p);o==="audio"&&(s=So(l),d=s[0]),o==="video"&&(r=vo(l),this.forceVideoCodec&&(0,My.default)(r,this.forceVideoCodec)?d=this.forceVideoCodec:d=r[0]),d&&(t[o]=c.filter(({codecs:p})=>Nr(p)===d))}else{let l=new Set(c.map(({codecs:p})=>p));d=go(l),d&&(t[o]=c.filter(({codecs:p})=>p.startsWith(d)))}if(o==="video"){let l=this.tuning.preferHDR,p=t.video.some(b=>b.hdr),h=t.video.some(b=>!b.hdr);H.display.isHDR&&l&&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&&Eo(t,m)}}let n={...e,streams:t};return this.tuning.dash.codecsPrioritizeEnabled&&(n.codecs={video:r,audio:s}),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 s=c=>{this.representationSubscription.add((0,I.fromEvent)(c,"error").pipe((0,I.filter)(d=>{var l;return!!((l=this.element)!=null&&l.played.length)})).subscribe(d=>{this.error$.next({id:"VideoSource",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:d})}))};this.source=dn();let n=(0,I.getWindow)().document,o=n.createElement("source");if(s(o),o.src=URL.createObjectURL(this.source),this.element.appendChild(o),yr())if(r){let c=n.createElement("source");s(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,d)=>[...c,...d.representations],[]);if(this.videoNativeBufferManager=new Ss(this.source),this.videoBufferManager=vs.getBufferManager("video",this.videoNativeBufferManager,u,e),this.bufferManagers=[this.videoBufferManager],this.nativeBufferManagers=[this.videoNativeBufferManager],(0,I.isNonNullable)(i)){this.audioNativeBufferManager=new Ss(this.source);let c=this.manifest.streams.audio.reduce((d,l)=>[...d,...l.representations],[]);this.audioBufferManager=vs.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)(...Ry.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)(...Ry.map(e=>(0,I.fromEvent)(this.element,e))).pipe((0,I.map)(e=>{var t,i,r,s;return Math.max((i=(t=this.videoBufferManager)==null?void 0:t.getForwardPlaybackBufferDuration())!=null?i:0,(s=(r=this.audioBufferManager)==null?void 0:r.getForwardPlaybackBufferDuration())!=null?s: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,s,n;if((0,I.isNullable)(this.element)||(0,I.isNullable)(this.videoBufferManager)||this.isStreamNotOpen)return;let e=this.element.currentTime*1e3,i=((s=(r=this.videoNativeBufferManager)==null?void 0:r.getBufferState())!=null?s:[]).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 he=require("@vkontakte/videoplayer-shared/es2018");var xo=class extends wo{constructor(e){super(e)}prepareManifestUrlString(e,t){return e}initRepresentationSubscriptions(){super.initRepresentationSubscriptions(),this.initDisableStallWatchdogSubscription(),this.initEndOfVideoSubscription()}setSourceDuration(){var t;(0,he.assertNonNullable)(this.manifest),(0,he.assertNonNullable)(this.source);let e=[(t=this.manifest.duration)!=null?t:0,...(0,Ml.default)((0,Ml.default)([...this.manifest.streams.audio,...this.manifest.streams.video],i=>i.representations),i=>{let r=[];return i.duration&&r.push(i.duration),We(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,he.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,he.assertNonNullable)(this.element);let e=(0,he.merge)((0,he.fromEvent)(this.element,"ended"),this.forceEnded$),t=this.nativeBufferLength$.pipe((0,he.filter)(i=>i>this.tuning.dash.bufferEmptinessTolerance));this.representationSubscription.add((0,he.merge)(e,t).subscribe(i=>this.stopStallWatchdogSubscription()))}initEndOfVideoSubscription(){let e=(0,he.merge)(...this.bufferManagers.map(s=>s.fullyBuffered$)).pipe((0,he.map)(()=>this.bufferManagers.every(s=>s.fullyBuffered$.getValue()))),t=(0,he.merge)(...this.bufferManagers.map(s=>s.onLastSegment$)).pipe((0,he.map)(()=>this.bufferManagers.some(s=>s.onLastSegment$.getValue()))),i=(0,he.combine)({allBuffersFull:e,someBufferEnded:t}).pipe((0,he.filterChanged)(),(0,he.map)(({allBuffersFull:s,someBufferEnded:n})=>s&&n),(0,he.filter)(s=>s)),r=()=>{var s;try{(s=this.source)==null||s.endOfStream()}catch(n){this.error$.next({id:"EndOfStream",category:he.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:n})}};this.representationSubscription.add((0,he.merge)(this.forceEnded$,i).pipe((0,he.filter)(s=>(0,he.isNonNullable)(this.source)&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(n=>!n.updating))).subscribe(r))}};var jr=class extends Na{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,$y.filterChanged)()).subscribe(s=>{let n=[...this.videoTracksMap.entries()].find(([,{representation:l}])=>l.id===s);if(!n){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[o,{stream:u}]=n,c=this.params.desiredState.videoStream.getTransition();c&&c.to&&c.to.id===u.id&&this.params.desiredState.videoStream.setState(c.to),e.currentVideoTrack$.next(o),e.currentVideoStream$.next(Jn(u));let d=this.player.calculateDurationFromSegments();d&&this.params.output.duration$.next(d/1e3)},r))}getPlayer(){return new xo({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 Q=require("@vkontakte/videoplayer-shared/es2018");var By=G(Ye(),1),Ll=G(Fa(),1);var wi=(a,e,t=0)=>{for(let i=0;i<a.length;i++)if(a.start(i)*1e3-t<=e&&a.end(i)*1e3+t>e)return!0;return!1};var T=require("@vkontakte/videoplayer-shared/es2018");var Po=G(Ye(),1),er=G(ft(),1),ko=G(Fa(),1);var Ly=G(Fc(),1);var xi=require("@vkontakte/videoplayer-shared/es2018");var j$=18,Cy=!1;try{Cy=H.browser.isSafari&&!!H.browser.safariVersion&&H.browser.safariVersion<=j$}catch(a){console.error(a)}var $l=class{constructor(e,t=!1){this.bufferFull$=new xi.Subject;this.error$=new xi.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:xi.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 s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};Cy&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!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(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:xi.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),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,xi.assertNever)(t)}}},Dy=$l;var Cl=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};var P=require("@vkontakte/videoplayer-shared/es2018");var ys=class{constructor(e,t,i,{fetcher:r,tuning:s,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 ve;this.switchAbortController=new ve;this.destroyAbortController=new ve;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 Dy(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||!ge(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Cl(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let c=this.getForwardBufferDuration(o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,c<d).catch(l=>{this.handleAsyncError(l,"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),s=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(s))}.bind(this));this.switchTo=(0,P.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!ge(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),s=this.initData.get(e);if((0,P.isNullable)(s)||(0,P.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,P.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!ge(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,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(!ge(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),s=this.initData.get(e);if((0,P.isNullable)(s)||(0,P.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,P.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!ge(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,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,ko.default)(e,c=>c.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let c of this.representations.keys()){let d=t.find(h=>h.id===c);d&&this.representations.set(c,d);let l=this.representations.get(c);if(!l||!ct(l.segmentReference)){this.isSeekingLive=!1;return}let p=this.getActualLiveStartingSegments(l.segmentReference);this.segments.set(l.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 s=this.segments.get(i);(0,P.assertNonNullable)(s,"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(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var d;this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(c!=null&&c.live),this.baseUrls=(d=c==null?void 0:c.baseUrls)!=null?d:[],this.initData=new Map(i.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(l=>[l.id,l])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!ge(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ve,(0,P.abortable)(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);(0,P.assertNonNullable)(s,`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(s,"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||!ge(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 ve,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)||!ge(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),s=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)(s))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=Ti(i),b=Ti(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(F=>e>=F.time.from&&e<F.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)&&Cl(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 d=[];if(!this.activeSegments.size&&(d=this.selectForwardBufferSegments(r,t.segmentReference.type,o),d.length)){let h="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,Po.default)(d,n))h="high";else{let m=(0,er.default)(d,0);m&&m.time.from-n.time.to>=this.forwardBufferTarget/2&&(h="low")}this.loadSegments(d,t,h).catch(m=>{this.handleAsyncError(m,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!d.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,er.default)(r,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<u),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.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=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.streams[this.kind];if(!t)return;let i=(0,ko.default)(t,s=>s.representations).find(s=>s.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,s;if(!e||[...this.segments.values()].every(n=>!n.length))return;let t=(0,ko.default)(e.streams[this.kind],n=>n.representations);for(let n of t){if(!n||!ct(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:[],d=(s=(r=(0,er.default)(c,-1))==null?void 0:r.time.to)!=null?s:0,l=o==null?void 0:o.findIndex(p=>d>=p.time.from+u&&d<=p.time.to+u);if(l===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(n.segmentReference);this.segments.set(n.id,p)}else{let p=o.slice(l+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,er.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 s=r.segmentReference;if(!ct(s))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*s.timescale/1e3).toString(10),d=Pt(s.segmentTemplateUrl,{segmentTime:c});n.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s: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&&Ki&&Ki(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Ki&&Ki(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),s=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&&ge(this.mediaSource,this.sourceBuffer)&&!(wi(this.sourceBuffer.buffered,h)&&wi(this.sourceBuffer.buffered,m)))&&v&&x});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let n=e,o=0,u=0,c=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let p=s;p<n.length&&(o<=d||u<=l);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"){ct(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:s,url:n,signal:o,onProgress:u,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await(0,P.abortable)(o,async function*(){let d=(0,P.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=(0,P.now)(),!d)return;let l=new DataView(d),p=Zi(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=p.getChunkEndTime(l,b)}u&&r.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(l,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=p.getServerLatencyTimestamps(l);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),xt(d)||(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())ct(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:s,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(s,{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),xt(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(ct(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,er.default)(e,0).byte.from,to:(0,er.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,P.now)(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,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(!ct(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:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(c,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,P.now)();let l=this.onSomeTemplateDataLoaded({dataView:c,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(l)}catch(l){this.error$.next({id:"SegmentFeeding",category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Po.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!ge(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(s.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),d=Zi(n.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!ge(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(s.aborted){await n();continue}let d=c.byte.from-i,l=c.byte.to-i,p=l-d+1,h=d<r,m=l<=r;if(!h)continue;let b=Zi(o.mime);if(c.status==="downloading"&&m){c.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+d,p);await this.sourceBufferTaskQueue.append(S,s)&&!s.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-d),u.loadedBytes>u.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+d+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,s)&&!s.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)||!ge(this.mediaSource,this.sourceBuffer))){!this.isLive&&H.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(wi(this.sourceBuffer.buffered,e.segment.time.from,100)&&wi(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",kl(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let s of(i=this.segments.get(r.id))!=null?i:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.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,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Yi(()=>(0,Ly.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",s=!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,Zi(e.mime),{priority:r,ignoreNetworkErrors:s})).then(async u=>{if(!u)return;let{init:c,dataView:d,segments:l}=u,p=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,p);let h=l;this.isLive&&ct(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=>{s||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||!ge(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,P.isNullable)(e))return!1;let r=[],s=0,n=u=>{u.sort((d,l)=>d.from-l.from);let c=[u[0]];for(let d=1;d<u.length;d++){let{from:l,to:p}=u[d],h=c[c.length-1];h.to>=l?h.to=Math.max(h.to,p):c.push(u[d])}return c},o=u=>{var d;if(s>=t)return r;r.push({...u.time}),r=n(r);let c=kl(u)?(d=u.size)!=null?d:0:u.byte.to-u.byte.from;s+=c};for(let u of this.segments.values())for(let c of u){let d=c.time.to<=e-this.tuning.dash.bufferPruningSafeZone,l=c.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||l)&&c.status==="fed"&&o(c)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let c=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,l=0;for(let p of this.segments.values())for(let h of p)(0,Po.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(d)&&l++;if(l===this.segments.size){let p={time:{from:c,to:d},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 d of c)d.time.from>=e+u&&d.status==="fed"&&o(d)}return r.length?(await Promise.all(r.map(c=>this.sourceBufferTaskQueue.remove(c.from,c.to)))).reduce((c,d)=>c||d,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!ge(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||!ge(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||!ge(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,P.isNullable)(e)?0:Ei(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!ge(this.mediaSource,this.sourceBuffer)))for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to,persistent:!1},{buffered:s}=this.sourceBuffer;for(let n=0;n<s.length;n++){let o=s.start(n)*1e3,u=s.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||!ge(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,{usePersistentGaps:r}=this.tuning.dash;this.gaps=this.gaps.filter(s=>{if(r&&s.persistent)return!0;let n=Math.round(s.from),o=Math.round(s.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=Yi(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:P.ErrorCategory.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if((0,P.isNullable)(this.sourceBuffer)||!ge(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),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(d=>d.from-t<=n&&d.to+t>=o),c=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(c.length===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.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 U=require("@vkontakte/videoplayer-shared/es2018");var Ro=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested$=new U.Subject;this.firstBytesManifest$=new U.Subject;this.firstBytesRequested$=new U.Subject;this.firstBytesReceived$=new U.Subject;this.lastConnectionType$=new U.ValueSubject(void 0);this.lastConnectionReused$=new U.ValueSubject(void 0);this.lastRequestFirstBytes$=new U.ValueSubject(void 0);this.lastConnectionMetrics$=new U.ValueSubject(void 0);this.lastDownloadMetrics$=new U.ValueSubject(void 0);this.recoverableError$=new U.Subject;this.error$=new U.Subject;this.abortAllController=new ve;this.subscription=new U.SubscriptionRemovable;this.performanceObserver=null;this.pendingConnectionMetrics=new Map;this.fetchManifest=(0,U.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Si(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=uo(i)),this.trackRequestStart(i,performance.now());let r=(0,U.now)();this.manifestRequested$.next();let s=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Ao);if(s){let n=(0,U.now)();t.log("success",(0,U.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(s.headers),this.firstBytesManifest$.next();let o=s.headers.get("content-length"),u=0;o&&(u=parseInt(o,10));let c=await s.text();if((!o||isNaN(u)||u<=0)&&(u=new TextEncoder().encode(c).length),u>0){let d=n-r,p=u/(d/1e3)*8/1024,h={bytes:u,speed:p,url:e};this.lastDownloadMetrics$.next(h)}return c}else return t.error("error",(0,U.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null}.bind(this));this.fetch=(0,U.abortable)(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:c=!1,ignoreNetworkErrors:d=!1}={}){var ce,ne,A;let l=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(l,(0,U.getWindow)().location.href);$.searchParams.append("bytes",`${i.from}-${i.to}`),l=$.toString();break}default:(0,U.assertNever)(t)}this.requestQuic&&(l=Si(l));let m=this.abortAllController.signal,b;if(n){let $=new ve;if(b=(0,U.merge)((0,U.fromEvent)(this.abortAllController.signal,"abort"),(0,U.fromEvent)(n,"abort")).subscribe(()=>{try{$.abort()}catch(k){Ao(k)}}),this.subscription.add(b),this.abortAllController.signal.aborted||n.aborted)try{$.abort()}catch(k){Ao(k)}m=$.signal}let S=0,v=(0,U.now)();h.log("startRequest",(0,U.flattenObject)({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:v})),this.trackRequestStart(l,performance.now()),this.firstBytesRequested$.next();let y=yield this.doFetch(l,{priority:s,headers:p,signal:m},{ignoreNetworkErrors:d}),x=(0,U.now)();if(!y)return h.error("error",{message:"No response in request"}),h.end(),this.unsubscribeAbortSubscription(b),null;if((ce=this.throughputEstimator)==null||ce.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,U.now)(),k={requestStartedAt:v,requestEndedAt:$,duration:$-v};return h.log("endRequest",(0,U.flattenObject)(k)),h.end(),y.arrayBuffer()}let w=y.body;if(o){let $;[w,$]=y.body.tee(),(ne=this.throughputEstimator)==null||ne.trackStream($,u)}let M=w.getReader(),_,F=parseInt((A=y.headers.get("content-length"))!=null?A:"",10);Number.isFinite(F)&&(_=F),!_&&i&&(_=i.to-i.from+1);let O=_?new Uint8Array(_):new Uint8Array(0),j=!1,V=$=>{this.unsubscribeAbortSubscription(b),j=!0,Ao($)},W=(0,U.abortable)(m,async function*({done:$,value:k}){if(S===0&&(this.lastRequestFirstBytes$.next((0,U.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(W,V)}}.bind(this));yield M==null?void 0:M.read().then(W,V),this.unsubscribeAbortSubscription(b);let N=(0,U.now)(),te={failed:j,requestStartedAt:v,requestEndedAt:N,duration:N-v};if(j)return h.error("endRequest",(0,U.flattenObject)(te)),h.end(),null;if(S>0){let $=N-v,R=S/($/1e3)*8/1024,X={bytes:S,speed:R,url:e};this.lastDownloadMetrics$.next(X)}return h.log("endRequest",(0,U.flattenObject)(te)),h.end(),O.buffer}.bind(this));this.fetchByteRangeRepresentation=(0,U.abortable)(this.abortAllController.signal,async function*(e,t,i){var v;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,c,d;e.indexRange&&(c=e.indexRange.from,d=e.indexRange.to,u=s+1===c,u&&(n=Math.min(c,r),o=Math.max(d,s))),n=Math.min(n,0);let l=yield this.fetch(e.url,{range:{from:n,to:o},measureThroughput:!1,...i});if(!l)return null;let p=new DataView(l,r-n,s-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(l,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(l),segments:S}}.bind(this));this.fetchTemplateRepresentation=(0,U.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=s,(0,U.getWindow)().PerformanceObserver&&this.setupPerformanceObserver()}onHeadersReceived(e){let{type:t,reused:i}=oo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}setupPerformanceObserver(){this.performanceObserver=new((0,U.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,U.getWindow)().navigator))return"unknown";let e=(0,U.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,s=0;return e.domainLookupStart>0&&e.domainLookupEnd>0&&(t=e.domainLookupEnd-e.domainLookupStart),e.connectStart>0&&e.connectEnd>0&&(s=e.connectEnd-e.connectStart,e.secureConnectionStart>0?(r=e.connectEnd-e.secureConnectionStart,i=e.secureConnectionStart-e.connectStart):i=s),{dnsResolveTime:Math.max(0,t),tcpHandshakeTime:Math.max(0,i),tlsHandshakeTime:Math.max(0,r),totalConnectTime:Math.max(0,s),networkType:this.estimateNetworkType(),url:e.name}}findMatchingRequest(e){try{for(let[t,i]of this.pendingConnectionMetrics.entries()){let r=new URL(e.name),s=r.origin+r.pathname,n=new URL(i.url),o=n.origin+n.pathname;if(s===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:U.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 s,n;let{type:r}=e;switch(r){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:(0,U.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 bt(e,t);if(r.ok)return r;if(i!=null&&i.ignoreNetworkErrors)return;let s=await r.text(),n=parseInt(s);if(!isNaN(n))switch(n){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:U.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:U.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:U.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:U.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${n})`,category:U.ErrorCategory.FATAL,httpCode:r.status,UVBackendErrorCode:s})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Ao=a=>{if(!xt(a))throw a};var Ts=require("@vkontakte/videoplayer-shared/es2018"),Pi=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 Ts.ValueSubject(e.initial),this.debounced$=new Ts.ValueSubject(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new He(`raw_${t}`),this.smoothedSeries$=new He(`smoothed_${t}`),this.reportedSeries$=new He(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,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),s=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>s||this.smoothed<n)&&((0,Ts.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 Pi{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Kt(this.slow,e,this.params.emaAlphaSlow),this.fast=Kt(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 Pi{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=al(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Kt(this.emaSmoothed,e,this.params.emaAlpha);let i=Pv(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Co=class extends Pi{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?Kt(this.smoothed,t,this.params.emaAlpha):t}};var tr=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 Co({initial:e,label:"liveEdgeDelay",...t})}};var Dl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var Do=require("@vkontakte/videoplayer-shared/es2018");var Is=class a{constructor(e,t){this.currentRepresentation$=new Do.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,Do.isNullable)(e))for(let i of this.representations)for(let r of i){let s=r.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let c=s.segments.find(d=>d.time.from<=e&&d.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,s.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=a.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=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&ct(t.segmentReference))}};var W$=["timeupdate","progress","play","seeked","stalled","waiting"],z$=["timeupdate","progress","loadeddata","playing","seeked"];var Lo=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 re("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 ve;this.initManifest=(0,T.abortable)(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Fe(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(d=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:T.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:d})});if(!e)return null;let t=null;try{t=fo(e!=null?e:"",this.manifestUrlString),this.manifestReceived$.next()}catch(d){let l=(u=no(e))!=null?u:{id:"ManifestParsing",category:T.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:d};this.error$.next(l)}if(!t)return null;let i=(d,l,p)=>{var h,m,b,S;return!!((m=(h=this.element)==null?void 0:h.canPlayType)!=null&&m.call(h,l)&&((S=(b=nt())==null?void 0:b.isTypeSupported)!=null&&S.call(b,`${l}; codecs="${p}"`))||d==="text")};if(t.live){this.isLive$.next(!0);let{availabilityStartTime:d,latestSegmentPublishTime:l,streamIsUnpublished:p,streamIsAlive:h}=t.live,m=((c=t.duration)!=null?c:0)/1e3;this.liveSeekableDuration$.next(-1*m),this.liveDuration$.next((l-d)/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:[]},s,n;for(let d of["video","audio"]){let p=t.streams[d].filter(({mime:m,codecs:b})=>i(d,m,b));r[d]=p;let h;if(this.tuning.dash.codecsPrioritizeEnabled){let m=p.map(({codecs:b})=>b);d==="audio"&&(n=So(m),h=n[0]),d==="video"&&(s=vo(m),this.forceVideoCodec&&(0,By.default)(s,this.forceVideoCodec)?h=this.forceVideoCodec:h=s[0]),h&&(r[d]=p.filter(({codecs:b})=>Nr(b)===h))}else{let m=new Set(p.map(({codecs:b})=>b));h=go(m),h&&(r[d]=p.filter(({codecs:b})=>b.startsWith(h)))}if(d==="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&&Eo(r,v)}}let o={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:s,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 l;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=dn();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),yr())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 ys("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 ys("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}if(Is.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Is(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,T.merge)(...z$.map(p=>(0,T.fromEvent)(this.element,p))).pipe((0,T.map)(p=>this.element?Ei(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=an(this.manifestUrlString,2);this.manifestUrlString=Fe(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()||Dl(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=an(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),Dl(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=an(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(),F=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(F);let O="none";if(_?O="active_low_latency":this.isLowLatency$.getValue()&&F?(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)),W=Math.abs(V-S),N=0;!h||W<=this.tuning.dashCmafLive.offsetCalculationError?N=S:V>0&&W>this.tuning.dashCmafLive.offsetCalculationError&&(N=V),this.manifestUrlString=Fe(this.manifestUrlString,N,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()))),d=(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$,d).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=[(l=this.manifest.duration)!=null?l:0,...(0,Ll.default)((0,Ll.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),ct(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,s;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||(s=this.audioBufferManager)!=null&&s.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 Ro({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=tr.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=Fe(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)(...W$.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&&wi(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var w,M,_,F,O,j,V,W,N,te,ce;let{keepSilentStallWatchdogWhenNotActive:t}=this.tuning.dashCmafLive,{crashOnStallTimeout:i,crashOnStallTWithoutDataTimeout:r,liveStallReinitInterval:s,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 d=this.currentStallDuration$.getValue();d+=n,this.currentStallDuration$.next(d);let l={timeInWaiting:d},p=(0,T.now)(),h=100,m=(_=(M=this.videoBufferManager)==null?void 0:M.lastDataObtainedTimestamp)!=null?_:0;this.videoLastDataObtainedTimestamp$.next(m);let b=(O=(F=this.audioBufferManager)==null?void 0:F.lastDataObtainedTimestamp)!=null?O:0,S=(V=(j=this.videoBufferManager)==null?void 0:j.getForwardBufferDuration())!=null?V:0,v=(N=(W=this.audioBufferManager)==null?void 0:W.getForwardBufferDuration())!=null?N:0,y=S<h&&p-m>r,x=this.audioBufferManager&&v<h&&p-b>r;if((!t||c)&&((y||x)&&d>r||d>=i))throw new Error(`Stall timeout exceeded: ${d} ms`);if(o&&d%s===0){let ne=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);!c&&t?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(ne),this.updateManifest()):this.seekLive(ne).catch(A=>{this.error$.next({id:"stallIntervalCallback",category:T.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:A})}),l.liveLastOffset=ne}else{let ne=this.element.currentTime*1e3;(te=this.videoBufferManager)==null||te.maintain(ne),(ce=this.audioBufferManager)==null||ce.maintain(ne),l.position=ne}this.tracer.log("stallIntervalCallback",(0,T.flattenObject)(l))};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,s,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=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),wi(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 s=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<=s&&c.to+o>s&&(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 it=require("@vkontakte/videoplayer-shared/es2018"),Bo=class{constructor(){this.subscription=new it.Subscription;this.pipSize$=new it.ValueSubject(void 0);this.videoSize$=new it.ValueSubject(void 0);this.elementSize$=new it.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=it.noop}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add((0,it.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,it.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,it.map)(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var ir=class{constructor(e){this.subscription=new Q.Subscription;this.videoState=new re("stopped");this.observableVideo=null;this.droppedFramesManager=new Dr;this.stallsManager=new io;this.elementSizeManager=new Bo;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new bi;this.audioTrackSwitchHistory=new bi;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,Q.assertNever)(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new Lr(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:((s=e.projectionData)==null?void 0:s.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 ht(e.source.url),this.params=e,this.video=Ke(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ue(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Lo({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,Q.isNullable)(this.observableVideo)&&(this.observableVideo=Ze(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:Q.ErrorCategory.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,Q.filter)(l=>!!l.length),(0,Q.once)()).subscribe(l=>{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:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,Q.map)(l=>l.to.state!=="none"),(0,Q.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}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.currentBuffer$,e.currentNativeBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.manifestRequested$,e.manifestRequested$),s(this.player.firstBytesManifest$,e.firstBytesManifest$),s(this.player.manifestReceived$,e.manifestReceived$),s(this.player.firstBytesRequested$,e.firstBytesRequested$),s(this.player.firstBytesReceived$,e.firstBytesReceived$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.lastConnectionMetrics$,e.httpConnectionMetrics$),s(this.player.lastDownloadMetrics$,e.httpDownloadMetrics$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe((0,Q.filter)(Q.isNonNullable),(0,Q.once)()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe((0,Q.map)(l=>l.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(_t(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),vi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(Je(this.video,t.volume,i.volumeState$,r)),this.subscription.add(pt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(mt(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:l})=>{if(l==="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,Q.assertNonNullable)(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let b=[];for(let S of p.audio){b.push(xl(S));let v=[];for(let y of S.representations){let x=gs(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(Pl(b));let S=[];for(let v of b.representations){let y=Ti({...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=Ey(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 l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let o=(0,Q.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,Q.fromEvent)(this.video,"progress")).pipe((0,Q.filter)(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe((0,Q.throttle)(u))),this.subscription.add(o.subscribe(async()=>{let l=this.player.state$.getState(),p=this.player.state$.getTransition();if(l!=="manifest_ready"&&l!=="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,Q.isNonNullable)(S)&&(this.stallsManager.lastVideoTrackSelected=S);let v=this.params.desiredState.autoVideoTrackLimits.getTransition();if(v&&this.params.output.autoVideoTrackLimits$.next(v.to),l==="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,Q.combine)({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:(0,Q.merge)((0,Q.observableFrom)([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,Q.map)(l=>l.to)))}).pipe((0,Q.map)(({videoState:l,autoVideoTrackState:p})=>l.to!=="stopped"&&p),(0,Q.filterChanged)()).subscribe(l=>this.player.setSmartRepresentationSwitch(l))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,Q.filterChanged)()).subscribe(l=>{let p=[...this.videoTracksMap.entries()].find(([,{representation:v}])=>v.id===l);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(Pl(m));let S=this.player.calculateDurationFromSegments();S&&this.params.output.duration$.next(S/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,Q.filterChanged)()).subscribe(l=>{let p=[...this.audioTracksMap.entries()].find(([,{representation:S}])=>S.id===l);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(xl(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var p,h;if(l!=null&&l.is3dVideo&&((p=this.params.tuning.spherical)!=null&&p.enabled))try{this.init3DScene(l),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,Q.map)(({to:l})=>l==="ready"),(0,Q.filterChanged)());this.subscription.add((0,Q.merge)(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,Q.observableFrom)(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add((0,Q.merge)(c,this.player.state$.stateChangeEnded$,(0,Q.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=(0,Q.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,Q.observableFrom)(["init"])).pipe((0,Q.debounce)(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var O,j,V,W,N,te,ce,ne,A,$,k,R,X;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Ca:$a,t=this.params.tuning.useNewAutoSelectVideoTrack?Yn:Gn,i=this.params.tuning.useNewAutoSelectVideoTrack?Ot:zn,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(O=r.videoTrack.getState())==null?void 0:O.id,u=[...this.videoTracksMap.keys()].find(({id:Y})=>Y===o),c=s.currentVideoTrack$.getValue(),d=((W=(V=r.videoStream.getState())!=null?V:u&&((j=this.videoTracksMap.get(u))==null?void 0:j.stream))!=null?W:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let l=[...this.videoStreamsMap.keys()].find(({id:Y})=>Y===d.id),p=l&&this.videoStreamsMap.get(l);if(!p)return;let h=Ei(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=(N=r.audioStream.getState())!=null?N:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,y=(te=[...this.audioStreamsMap.keys()].find(({id:Y})=>Y===(v==null?void 0:v.id)))!=null?te:this.audioStreamsMap.keys().next().value,x=0;if(y){if(u&&!n){let Y=e(u,p,(ce=this.audioStreamsMap.get(y))!=null?ce:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,(ne=Y==null?void 0:Y.bitrate)!=null?ne:-1/0)}if(c){let Y=e(c,p,(A=this.audioStreamsMap.get(y))!=null?A:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,($=Y==null?void 0:Y.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,F=M&&((X=this.audioTracksMap.get(M))==null?void 0:X.representation);if(_&&F)return[_,F];if(_&&!F&&this.audioTracksMap.size===0)return[_,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){et(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:Q.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),Xe(this.video),this.tracer.end()}};var Es=class extends ir{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var me=require("@vkontakte/videoplayer-shared/es2018");var ws=class extends ir{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,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 me.ValueSubject(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe((0,me.filterChanged)()).subscribe(u=>{let c=i.position$.getValue(),d=i.volume$.getValue(),l=!d.volume||d.muted;!u&&!c&&l?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe((0,me.map)(u=>u.to)).subscribe(this.player.isLowLatency$)).add((0,me.combine)({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,me.map)(({liveBufferTime:u,liveAvailabilityStartTime:c})=>u&&c?u*1e3+c+t:void 0)).subscribe(i.liveTime$)).add((0,me.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,me.merge)(r.playbackRateState$,new me.ValueSubject(1))}).pipe((0,me.filter)(({liveStreamStatus:u,liveDuration:c})=>u==="active"&&!!c)).subscribe(({liveDuration:u,playbackRate:c})=>{let d=i.liveBufferTime$.getValue(),l=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;l||c<1-p||this.video.paused||(0,me.isNullable)(d)||(t=u-d)})).add((0,me.combine)({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,me.merge)(r.playbackRateState$,new me.ValueSubject(1))}).pipe((0,me.filterChanged)((u,c)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===c.liveDuration:u.time===c.time)).subscribe(({time:u,liveDuration:c,playbackRate:d})=>{let l=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;if(!l&&!this.video.paused&&d>=1-p||(0,me.isNullable)(u)||(0,me.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=wy(u);this.params.output.availableTextTracks$.next([c])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe((0,me.filter)(u=>(0,me.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 Vy="X-Playback-Duration",Bl=async a=>{var r;let e=await bt(a),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(Vy)?parseInt(e.headers.get(Vy),10):void 0};var se=require("@vkontakte/videoplayer-shared/es2018");var _l=G(ec(),1);var Vo=require("@vkontakte/videoplayer-shared/es2018");var Y$=a=>{let e=null;if(a.QUALITY&&(e=mi(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=(0,Vo.videoSizeToQuality)({width:t,height:i})}return e!=null?e:null},K$=(a,e)=>{var s,n;let t=a.split(`
179
179
  `),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],c=u.match(/^#EXT-X-STREAM-INF:(.+)/),d=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!c&&!d)){if(c){let l=(0,_l.default)(c[1].split(",").map(y=>y.split("="))),p=(s=l.QUALITY)!=null?s:`stream-${l.BANDWIDTH}`,h=Y$(l),m;l.BANDWIDTH&&(m=parseInt(l.BANDWIDTH,10)/1e3||void 0),!m&&l["AVERAGE-BANDWIDTH"]&&(m=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,S;if(l.RESOLUTION){let[y,x]=l.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(d){let l=(0,_l.default)(d[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=l.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=l.LANGUAGE,m=l.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}},X$=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),Vl=0,_y=async(a,e=a,t,i)=>{let s=await(await bt(a,i)).text();Vl+=1;try{let{qualityManifests:n,textTracks:o}=K$(s,e);return{qualityManifests:n,textTracks:o}}catch(n){if(Vl<=t.manifestRetryMaxCount)return await X$((0,Vo.getExponentialDelay)(Vl-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),_y(a,e,t)}return{qualityManifests:[],textTracks:[]}},_o=_y;var lt=require("@vkontakte/videoplayer-shared/es2018");var Oo=class{constructor(e,t,i,r,s){this.subscription=new lt.Subscription;this.abortControllers={destroy:new ve,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new lt.ValueSubject(null);this.getCurrentTime$=new lt.ValueSubject(null);this.error$=new lt.Subject;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe((0,lt.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 bt(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
  `),s=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(),d=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:s,to:s+d},url:c}),s=s+d,!i.segmentStartTime){let l=new Date(i.vkStartTime).valueOf(),p=new Date(i.programDateTime).valueOf();i.segmentStartTime=p-l}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),s=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,lt.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 ve;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:lt.ErrorCategory.WTF,thrown:t,message:e})}};var xs=class{constructor(e){this.subscription=new se.Subscription;this.videoState=new re("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new se.ValueSubject([]);this.liveOffset=new Wi;this.manifestStartTime$=new se.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(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.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(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),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 d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&(B(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,se.assertNever)(t)}};var i;this.params=e,this.video=Ke(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:se.VideoQuality.INVARIANT,url:this.params.source.url};let t=(r,s)=>_o(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},s);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new Oo(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new ht(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:s})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:se.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(s,this.params.source.url),this.manifests$.next([this.masterManifest,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:se.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(Ue(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new se.ValueSubject((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,c,d,l;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(l=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(c=t.getState())==null?void 0:c.id)!=null?l:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;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:se.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Ze(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.currentBuffer$,e.currentNativeBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Je(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(pt(this.video,t.playbackRate,r.playbackRateState$,i)),s(mt(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(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,se.filterChanged)(),(0,se.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(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&(0,se.isNonNullable)(c.to)){let l=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let p=this.manifests$.getValue().find(h=>h.id===l);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Ue(p.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.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,d;let o=(d=(c=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:c.call(u))==null?void 0:d.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add((0,se.combine)({startTime:this.manifestStartTime$.pipe((0,se.filter)(se.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,se.map)(o=>o.map(({id:u,quality:c,size:d,bandwidth:l,fps:p})=>({id:u,quality:c,size:d,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i));let n=(0,se.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,se.observableFrom)(["init"])).pipe((0,se.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),Xe(this.video)}prepare(){var o,u,c;let e=this.selectManifest();if((0,se.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:d,min:l}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[p,h]of[[d,"mq"],[l,"lq"]]){let m=String(parseFloat(p||""));h&&p&&r.searchParams.set(h,m)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=Fe(r.toString(),this.liveOffset.getTotalOffset(),s);(c=this.liveTextManager)==null||c.prepare(n),this.video.setAttribute("src",n),this.video.load(),Bl(n).then(d=>{var l;if(!(0,se.isNullable)(d))this.maxSeekBackTime$.next(d);else{let p=(l=this.params.source.maxSeekBackTime)!=null?l:this.maxSeekBackTime$.getValue();((0,se.isNullable)(p)||!isFinite(p))&&bt(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();Bl(S).then(v=>{(0,se.isNullable)(v)||this.maxSeekBackTime$.next(v)})}}).catch(()=>{})}})}playIfAllowed(){et(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:se.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=Fe(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 le=require("@vkontakte/videoplayer-shared/es2018");var Ps=class{constructor(e){this.subscription=new le.Subscription;this.videoState=new re("stopped");this.manifests$=new le.ValueSubject([]);this.unmuteAfterBrowserResetsHappened=new le.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(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.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(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:l}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:l*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,le.assertNever)(t)}};this.textTracksManager=new ht(e.source.url),this.params=e,this.video=Ke(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:le.VideoQuality.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ue(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),_o(Fe(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:le.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,c,d,l;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(l=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(c=t.getState())==null?void 0:c.id)!=null?l:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;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:le.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Ze(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.currentBuffer$,e.currentNativeBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,le.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(_t(this.video,t.isLooped,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(pt(this.video,t.playbackRate,r.playbackRateState$,i)),vi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(Je(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(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&(0,le.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(Ue(b.url)))}let l=this.params.desiredState.playbackRate.getState(),p=(h=this.params.output.element$.getValue())==null?void 0:h.playbackRate;if(l!==p){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(l),m.playbackRate=l)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.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,le.map)(o=>o.map(({id:u,quality:c,size:d,bandwidth:l,fps:p})=>({id:u,quality:c,size:d,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i)),!H.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,le.merge)((0,le.fromEvent)(o,"addtrack"),(0,le.fromEvent)(o,"removetrack"),(0,le.fromEvent)(o,"change"),(0,le.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=(0,le.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,le.observableFrom)(["init"])).pipe((0,le.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Xe(this.video)}prepare(){var s,n;let e=this.selectManifest();if((0,le.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=(s=t==null?void 0:t.to)!=null?s:i)!=null?n:{};for(let[c,d]of[[o,"mq"],[u,"lq"]]){let l=String(parseFloat(c||""));d&&c&&r.searchParams.set(d,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){et(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:le.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var Oy=G(pi(),1),Ol=G(Ni(),1),Ny=G(ft(),1);var Te=require("@vkontakte/videoplayer-shared/es2018");var ks=class{constructor(e){this.subscription=new Te.Subscription;this.videoState=new re("stopped");this.trackUrls={};this.textTracksManager=new ht;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 s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to);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,Te.assertNever)(e)}};this.params=e,this.video=Ke(e.container,e.tuning),this.params.output.element$.next(this.video),(0,Oy.default)(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Ol.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:Te.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Ze(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentNativeBuffer$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,Te.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(_t(this.video,t.isLooped,i)),vi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(Je(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(pt(this.video,t.playbackRate,r.playbackRateState$,i)),s(mt(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,Te.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let d=this.params.desiredState.playbackRate.getState(),l=(c=this.params.output.element$.getValue())==null?void 0:c.playbackRate;if(d!==l){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(d),p.playbackRate=d)}}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,Te.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,Te.observableFrom)(["init"])).pipe((0,Te.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),Xe(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;(0,Te.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,Te.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Si(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Ue(t))}playIfAllowed(){et(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:Te.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var c,d;this.params.output.autoVideoTrackLimits$.next(e);let t=l=>{this.params.output.currentVideoTrack$.next(l),this.params.desiredState.videoTrack.startTransitionTo(l)},i=l=>{let p=Ot(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:l,abrLogger:this.params.dependencies.abrLogger});t(p)},r=(c=this.params.output.currentVideoTrack$.getValue())==null?void 0:c.quality,s=!!(e.max||e.min),n=(0,Ol.default)(this.trackUrls).map(l=>l.track);if(!r||!s||Mr(e,n[0].quality,(d=(0,Ny.default)(n,-1))==null?void 0:d.quality)){i();return}let o=e.max?(0,Te.isLowerOrEqual)(r,e.max):!0,u=e.min?(0,Te.isHigherOrEqual)(r,e.min):!0;o&&u||i(e)}};var Ie=require("@vkontakte/videoplayer-shared/es2018");var qy=require("@vkontakte/videoplayer-shared/es2018"),Fy=["stun:videostun.mycdn.me:80"],J$=1e3,Z$=3,Nl=()=>null,No=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=Nl;this.externalStopCallback=Nl;this.externalErrorCallback=Nl;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:Fy}]};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:qy.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),J$)}normalizeOptions(e={}){let t={stunServerList:Fy,maxRetryNumber:Z$,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var As=class{constructor(e){this.videoState=new re("stopped");this.maxSeekBackTime$=new Ie.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 s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),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,Ie.assertNever)(e)}};this.subscription=new Ie.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ke(e.container,e.tuning),this.liveStreamClient=new No(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),Xe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Ie.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add((0,Ie.merge)(this.videoState.stateChangeStarted$.pipe((0,Ie.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,Ie.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=Ze(this.video);this.subscription.add(()=>r.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(r.timeUpdate$,e.liveTime$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.currentBuffer$,e.currentNativeBuffer$),s(mt(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(Je(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,Ie.assertNever)(n.to)}},i)).add((0,Ie.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,Ie.observableFrom)(["init"])).pipe((0,Ie.debounce)(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Ue(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:Ie.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:Ie.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){et(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:Ie.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Hr=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 ei=require("@vkontakte/videoplayer-shared/es2018");var Uy=a=>new ei.Observable(e=>{let t=new ei.Subscription,i=a.desiredPlaybackState$.stateChangeStarted$.pipe((0,ei.map)(({from:c,to:d})=>`${c}-${d}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe((0,ei.map)(({type:c})=>c!==void 0)),n=new ei.Subject,o=0,u="unknown";return t.add(i.subscribe(c=>{o&&window.clearTimeout(o),u=c,o=window.setTimeout(()=>n.next(c),a.maxTransitionInterval),J({m:"hangup.set",l:c,id:o})})),t.add(r.subscribe(()=>{J({m:"hangup.cl",id:o}),window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(c=>{o&&(J({m:"hangup.rs.0",id:o}),window.clearTimeout(o),o=0,c&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval),J({m:"hangup.rs.1",id:o})))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var gt=require("@vkontakte/videoplayer-shared/es2018");function jy(){return new(window.AudioContext||window.webkitAudioContext)}var Rs=class Rs{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new ve;this.subscriptions=new gt.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,gt.filter)(s=>!!s.type),(0,gt.once)()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){H.browser.isSafari&&e!=="MPEG"||this.subscriptions.add((0,gt.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,gt.filter)(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),(0,gt.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=jy();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 s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.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:Rs.errorId,category:gt.ErrorCategory.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Rs.errorId} exception`,thrown:e})}};Rs.errorId="VolumeMultiplierManager";var Qr=Rs;var eC={chunkDuration:5e3,maxParallelRequests:5},Ms=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=Cu([...ly(this.params.tuning),...cy(this.params.tuning)]).filter(c=>(0,E.isNonNullable)(e.sources[c])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(c=>!(0,Fl.default)(r,c)),...t.filter(c=>(0,Fl.default)(r,c))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,E.flattenObject)(s)),this.screenFormatsIterator=new Hr(s);let n=[...El(!0),...El(!1)];this.chromecastFormatsIterator=new Hr(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&&Qr.isSupported()&&(this.volumeMultiplierManager=new Qr(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){J.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 Hr(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 s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return(0,E.assertNever)(e)}}createScreenProvider(e){var u,c,d;let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let l=this.applyFailoverHost(t[e]),p=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,E.assertNonNullable)(l),this.params.tuning.useDashProviderVirtual&&!H.device.isMobile?new jr({...o,source:l,sourceHls:p,forceVideoCodec:(u=this.videoCodecsIterator)==null?void 0:u.getValue()}):this.params.tuning.useDashProviderVirtualMobile&&H.device.isMobile?new jr({...o,source:l,sourceHls:p,forceVideoCodec:(c=this.videoCodecsIterator)==null?void 0:c.getValue()}):new Es({...o,source:l,sourceHls:p,forceVideoCodec:(d=this.videoCodecsIterator)==null?void 0:d.getValue()})}case"DASH_LIVE_CMAF":{let l=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(l),new ws({...o,source:l})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let l=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(l),new Ps({...o,source:l})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(l),new xs({...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 ks({...o,source:l})}case"DASH_LIVE":{let l=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(l),new Sv({...o,source:l,config:{...eC,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let l=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(l),new As({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:s}=this.params,n=this.providerOutput,o={meta:s,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 Wt){let{chromecastConnector:c}=this.params.dependencies.chromecastInitializer;return(0,E.assertNonNullable)(c),new ha({...o,chromecastConnector:c})}let u=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,E.assertNonNullable)(u),new ka({...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 s=new URL(r);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,Hy.default)((0,ql.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new E.Subscription,t=!1,i=0;e.add((0,E.merge)(this.providerOutput.error$.pipe((0,E.filter)(s=>!this.params.tuning.ignoreAudioRendererError||!s.message||!/AUDIO_RENDERER_ERROR/ig.test(s.message))),Uy({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,E.map)(s=>({id:`ProviderHangup:${s}`,category:E.ErrorCategory.WTF,message:`A ${s} 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 s=this.params.desiredState.playbackState.transitionEnded$.pipe((0,E.filter)(({to:n})=>n==="playing"),(0,E.once)()).subscribe(()=>t=!0);e.add(s)}));let r=()=>{let s=J.drain(),{logDashLiveDebug:n,sendDashLiveDebug:o}=this.params.tuning;if(n&&(0,E.getWindow)().console.log(`===== DASH_LIVE DEBUG START ====
181
181
  `,s.map(({time:u,data:c,stack:d})=>`${u}: ${JSON.stringify(c)}${d?`