@vkontakte/videoplayer-core 2.0.126-dev.3f94cfc5.0 → 2.0.126-dev.4eb5c2dc.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +16 -16
- package/es2015.esm.js +16 -16
- package/es2018.cjs.js +17 -17
- package/es2018.esm.js +17 -17
- package/esnext.cjs.js +22 -22
- package/esnext.esm.js +22 -22
- package/evergreen.esm.js +20 -20
- package/package.json +2 -2
- package/types/player/Player.d.ts +1 -0
- package/types/player/types.d.ts +4 -0
- package/types/providers/DashProvider/baseDashProvider.d.ts +0 -2
- package/types/providers/DashProvider/consts.d.ts +1 -1
- package/types/providers/DashProvider/lib/player.d.ts +7 -4
- package/types/providers/DashProvider/lib/types.d.ts +13 -2
- package/types/providers/types.d.ts +1 -0
package/es2018.cjs.js
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.126-dev.
|
|
3
|
-
* Wed,
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.126-dev.4eb5c2dc.0
|
|
3
|
+
* Wed, 19 Feb 2025 12:26:44 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-126/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var CS=Object.create;var us=Object.defineProperty;var VS=Object.getOwnPropertyDescriptor;var BS=Object.getOwnPropertyNames;var OS=Object.getPrototypeOf,_S=Object.prototype.hasOwnProperty;var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),NS=(a,e)=>{for(var t in e)us(a,t,{get:e[t],enumerable:!0})},sc=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of BS(e))!_S.call(a,i)&&i!==t&&us(a,i,{get:()=>e[i],enumerable:!(r=VS(e,i))||r.enumerable});return a};var U=(a,e,t)=>(t=a!=null?CS(OS(a)):{},sc(e||!a||!a.__esModule?us(t,"default",{value:a,enumerable:!0}):t,a)),FS=a=>sc(us({},"__esModule",{value:!0}),a);var pe=b((Dn,nc)=>{"use strict";var Ti=function(a){return a&&a.Math===Math&&a};nc.exports=Ti(typeof globalThis=="object"&&globalThis)||Ti(typeof window=="object"&&window)||Ti(typeof self=="object"&&self)||Ti(typeof global=="object"&&global)||Ti(typeof Dn=="object"&&Dn)||function(){return this}()||Function("return this")()});var Te=b((vR,oc)=>{"use strict";oc.exports=function(a){try{return!!a()}catch(e){return!0}}});var Ii=b((SR,uc)=>{"use strict";var qS=Te();uc.exports=!qS(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Cn=b((yR,pc)=>{"use strict";var US=Ii(),dc=Function.prototype,lc=dc.apply,cc=dc.call;pc.exports=typeof Reflect=="object"&&Reflect.apply||(US?cc.bind(lc):function(){return cc.apply(lc,arguments)})});var ge=b((TR,fc)=>{"use strict";var hc=Ii(),mc=Function.prototype,Vn=mc.call,HS=hc&&mc.bind.bind(Vn,Vn);fc.exports=hc?HS:function(a){return function(){return Vn.apply(a,arguments)}}});var cr=b((IR,gc)=>{"use strict";var bc=ge(),jS=bc({}.toString),QS=bc("".slice);gc.exports=function(a){return QS(jS(a),8,-1)}});var Bn=b((ER,vc)=>{"use strict";var GS=cr(),WS=ge();vc.exports=function(a){if(GS(a)==="Function")return WS(a)}});var ce=b((xR,Sc)=>{"use strict";var On=typeof document=="object"&&document.all;Sc.exports=typeof On=="undefined"&&On!==void 0?function(a){return typeof a=="function"||a===On}:function(a){return typeof a=="function"}});var qe=b((PR,yc)=>{"use strict";var YS=Te();yc.exports=!YS(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ue=b((wR,Tc)=>{"use strict";var zS=Ii(),ds=Function.prototype.call;Tc.exports=zS?ds.bind(ds):function(){return ds.apply(ds,arguments)}});var _n=b(xc=>{"use strict";var Ic={}.propertyIsEnumerable,Ec=Object.getOwnPropertyDescriptor,KS=Ec&&!Ic.call({1:2},1);xc.f=KS?function(e){var t=Ec(this,e);return!!t&&t.enumerable}:Ic});var Ei=b((kR,Pc)=>{"use strict";Pc.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Ac=b((LR,wc)=>{"use strict";var XS=ge(),JS=Te(),ZS=cr(),Nn=Object,ey=XS("".split);wc.exports=JS(function(){return!Nn("z").propertyIsEnumerable(0)})?function(a){return ZS(a)==="String"?ey(a,""):Nn(a)}:Nn});var Vr=b((RR,kc)=>{"use strict";kc.exports=function(a){return a==null}});var jt=b(($R,Lc)=>{"use strict";var ty=Vr(),ry=TypeError;Lc.exports=function(a){if(ty(a))throw new ry("Can't call method on "+a);return a}});var dr=b((MR,Rc)=>{"use strict";var iy=Ac(),ay=jt();Rc.exports=function(a){return iy(ay(a))}});var He=b((DR,$c)=>{"use strict";var sy=ce();$c.exports=function(a){return typeof a=="object"?a!==null:sy(a)}});var Br=b((CR,Mc)=>{"use strict";Mc.exports={}});var Et=b((VR,Cc)=>{"use strict";var Fn=Br(),qn=pe(),ny=ce(),Dc=function(a){return ny(a)?a:void 0};Cc.exports=function(a,e){return arguments.length<2?Dc(Fn[a])||Dc(qn[a]):Fn[a]&&Fn[a][e]||qn[a]&&qn[a][e]}});var xi=b((BR,Vc)=>{"use strict";var oy=ge();Vc.exports=oy({}.isPrototypeOf)});var pr=b((OR,_c)=>{"use strict";var uy=pe(),Bc=uy.navigator,Oc=Bc&&Bc.userAgent;_c.exports=Oc?String(Oc):""});var Hn=b((_R,jc)=>{"use strict";var Hc=pe(),Un=pr(),Nc=Hc.process,Fc=Hc.Deno,qc=Nc&&Nc.versions||Fc&&Fc.version,Uc=qc&&qc.v8,it,ps;Uc&&(it=Uc.split("."),ps=it[0]>0&&it[0]<4?1:+(it[0]+it[1]));!ps&&Un&&(it=Un.match(/Edge\/(\d+)/),(!it||it[1]>=74)&&(it=Un.match(/Chrome\/(\d+)/),it&&(ps=+it[1])));jc.exports=ps});var jn=b((NR,Gc)=>{"use strict";var Qc=Hn(),ly=Te(),cy=pe(),dy=cy.String;Gc.exports=!!Object.getOwnPropertySymbols&&!ly(function(){var a=Symbol("symbol detection");return!dy(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Qc&&Qc<41})});var Qn=b((FR,Wc)=>{"use strict";var py=jn();Wc.exports=py&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Gn=b((qR,Yc)=>{"use strict";var hy=Et(),my=ce(),fy=xi(),by=Qn(),gy=Object;Yc.exports=by?function(a){return typeof a=="symbol"}:function(a){var e=hy("Symbol");return my(e)&&fy(e.prototype,gy(a))}});var Pi=b((UR,zc)=>{"use strict";var vy=String;zc.exports=function(a){try{return vy(a)}catch(e){return"Object"}}});var ht=b((HR,Kc)=>{"use strict";var Sy=ce(),yy=Pi(),Ty=TypeError;Kc.exports=function(a){if(Sy(a))return a;throw new Ty(yy(a)+" is not a function")}});var wi=b((jR,Xc)=>{"use strict";var Iy=ht(),Ey=Vr();Xc.exports=function(a,e){var t=a[e];return Ey(t)?void 0:Iy(t)}});var Zc=b((QR,Jc)=>{"use strict";var Wn=Ue(),Yn=ce(),zn=He(),xy=TypeError;Jc.exports=function(a,e){var t,r;if(e==="string"&&Yn(t=a.toString)&&!zn(r=Wn(t,a))||Yn(t=a.valueOf)&&!zn(r=Wn(t,a))||e!=="string"&&Yn(t=a.toString)&&!zn(r=Wn(t,a)))return r;throw new xy("Can't convert object to primitive value")}});var at=b((GR,ed)=>{"use strict";ed.exports=!0});var id=b((WR,rd)=>{"use strict";var td=pe(),Py=Object.defineProperty;rd.exports=function(a,e){try{Py(td,a,{value:e,configurable:!0,writable:!0})}catch(t){td[a]=e}return e}});var Ai=b((YR,nd)=>{"use strict";var wy=at(),Ay=pe(),ky=id(),ad="__core-js_shared__",sd=nd.exports=Ay[ad]||ky(ad,{});(sd.versions||(sd.versions=[])).push({version:"3.38.0",mode:wy?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Kn=b((zR,ud)=>{"use strict";var od=Ai();ud.exports=function(a,e){return od[a]||(od[a]=e||{})}});var Or=b((KR,ld)=>{"use strict";var Ly=jt(),Ry=Object;ld.exports=function(a){return Ry(Ly(a))}});var st=b((XR,cd)=>{"use strict";var $y=ge(),My=Or(),Dy=$y({}.hasOwnProperty);cd.exports=Object.hasOwn||function(e,t){return Dy(My(e),t)}});var Xn=b((JR,dd)=>{"use strict";var Cy=ge(),Vy=0,By=Math.random(),Oy=Cy(1 .toString);dd.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+Oy(++Vy+By,36)}});var Ie=b((ZR,hd)=>{"use strict";var _y=pe(),Ny=Kn(),pd=st(),Fy=Xn(),qy=jn(),Uy=Qn(),_r=_y.Symbol,Jn=Ny("wks"),Hy=Uy?_r.for||_r:_r&&_r.withoutSetter||Fy;hd.exports=function(a){return pd(Jn,a)||(Jn[a]=qy&&pd(_r,a)?_r[a]:Hy("Symbol."+a)),Jn[a]}});var gd=b((e$,bd)=>{"use strict";var jy=Ue(),md=He(),fd=Gn(),Qy=wi(),Gy=Zc(),Wy=Ie(),Yy=TypeError,zy=Wy("toPrimitive");bd.exports=function(a,e){if(!md(a)||fd(a))return a;var t=Qy(a,zy),r;if(t){if(e===void 0&&(e="default"),r=jy(t,a,e),!md(r)||fd(r))return r;throw new Yy("Can't convert object to primitive value")}return e===void 0&&(e="number"),Gy(a,e)}});var Zn=b((t$,vd)=>{"use strict";var Ky=gd(),Xy=Gn();vd.exports=function(a){var e=Ky(a,"string");return Xy(e)?e:e+""}});var hs=b((r$,yd)=>{"use strict";var Jy=pe(),Sd=He(),eo=Jy.document,Zy=Sd(eo)&&Sd(eo.createElement);yd.exports=function(a){return Zy?eo.createElement(a):{}}});var to=b((i$,Td)=>{"use strict";var eT=qe(),tT=Te(),rT=hs();Td.exports=!eT&&!tT(function(){return Object.defineProperty(rT("div"),"a",{get:function(){return 7}}).a!==7})});var xd=b(Ed=>{"use strict";var iT=qe(),aT=Ue(),sT=_n(),nT=Ei(),oT=dr(),uT=Zn(),lT=st(),cT=to(),Id=Object.getOwnPropertyDescriptor;Ed.f=iT?Id:function(e,t){if(e=oT(e),t=uT(t),cT)try{return Id(e,t)}catch(r){}if(lT(e,t))return nT(!aT(sT.f,e,t),e[t])}});var ro=b((s$,Pd)=>{"use strict";var dT=Te(),pT=ce(),hT=/#|\.prototype\./,ki=function(a,e){var t=fT[mT(a)];return t===gT?!0:t===bT?!1:pT(e)?dT(e):!!e},mT=ki.normalize=function(a){return String(a).replace(hT,".").toLowerCase()},fT=ki.data={},bT=ki.NATIVE="N",gT=ki.POLYFILL="P";Pd.exports=ki});var Nr=b((n$,Ad)=>{"use strict";var wd=Bn(),vT=ht(),ST=Ii(),yT=wd(wd.bind);Ad.exports=function(a,e){return vT(a),e===void 0?a:ST?yT(a,e):function(){return a.apply(e,arguments)}}});var io=b((o$,kd)=>{"use strict";var TT=qe(),IT=Te();kd.exports=TT&&IT(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var mt=b((u$,Ld)=>{"use strict";var ET=He(),xT=String,PT=TypeError;Ld.exports=function(a){if(ET(a))return a;throw new PT(xT(a)+" is not an object")}});var hr=b($d=>{"use strict";var wT=qe(),AT=to(),kT=io(),ms=mt(),Rd=Zn(),LT=TypeError,ao=Object.defineProperty,RT=Object.getOwnPropertyDescriptor,so="enumerable",no="configurable",oo="writable";$d.f=wT?kT?function(e,t,r){if(ms(e),t=Rd(t),ms(r),typeof e=="function"&&t==="prototype"&&"value"in r&&oo in r&&!r[oo]){var i=RT(e,t);i&&i[oo]&&(e[t]=r.value,r={configurable:no in r?r[no]:i[no],enumerable:so in r?r[so]:i[so],writable:!1})}return ao(e,t,r)}:ao:function(e,t,r){if(ms(e),t=Rd(t),ms(r),AT)try{return ao(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new LT("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Fr=b((c$,Md)=>{"use strict";var $T=qe(),MT=hr(),DT=Ei();Md.exports=$T?function(a,e,t){return MT.f(a,e,DT(1,t))}:function(a,e,t){return a[e]=t,a}});var me=b((d$,Cd)=>{"use strict";var Li=pe(),CT=Cn(),VT=Bn(),BT=ce(),OT=xd().f,_T=ro(),qr=Br(),NT=Nr(),Ur=Fr(),Dd=st();Ai();var FT=function(a){var e=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,r)}return new a(t,r,i)}return CT(a,this,arguments)};return e.prototype=a.prototype,e};Cd.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?Li:i?Li[t]:Li[t]&&Li[t].prototype,o=r?qr:qr[t]||Ur(qr,t,{})[t],u=o.prototype,l,c,d,p,h,f,g,S,I;for(p in e)l=_T(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&Dd(n,p),f=o[p],c&&(a.dontCallGetSet?(I=OT(n,p),g=I&&I.value):g=n[p]),h=c&&g?g:e[p],!(!l&&!s&&typeof f==typeof h)&&(a.bind&&c?S=NT(h,Li):a.wrap&&c?S=FT(h):s&&BT(h)?S=VT(h):S=h,(a.sham||h&&h.sham||f&&f.sham)&&Ur(S,"sham",!0),Ur(o,p,S),s&&(d=t+"Prototype",Dd(qr,d)||Ur(qr,d,{}),Ur(qr[d],p,h),a.real&&u&&(l||!u[p])&&Ur(u,p,h)))}});var Bd=b((p$,Vd)=>{"use strict";var qT=Math.ceil,UT=Math.floor;Vd.exports=Math.trunc||function(e){var t=+e;return(t>0?UT:qT)(t)}});var Ri=b((h$,Od)=>{"use strict";var HT=Bd();Od.exports=function(a){var e=+a;return e!==e||e===0?0:HT(e)}});var Nd=b((m$,_d)=>{"use strict";var jT=Ri(),QT=Math.max,GT=Math.min;_d.exports=function(a,e){var t=jT(a);return t<0?QT(t+e,0):GT(t,e)}});var uo=b((f$,Fd)=>{"use strict";var WT=Ri(),YT=Math.min;Fd.exports=function(a){var e=WT(a);return e>0?YT(e,9007199254740991):0}});var Hr=b((b$,qd)=>{"use strict";var zT=uo();qd.exports=function(a){return zT(a.length)}});var lo=b((g$,Hd)=>{"use strict";var KT=dr(),XT=Nd(),JT=Hr(),Ud=function(a){return function(e,t,r){var i=KT(e),s=JT(i);if(s===0)return!a&&-1;var n=XT(r,s),o;if(a&&t!==t){for(;s>n;)if(o=i[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in i)&&i[n]===t)return a||n||0;return!a&&-1}};Hd.exports={includes:Ud(!0),indexOf:Ud(!1)}});var $i=b((v$,jd)=>{"use strict";jd.exports=function(){}});var Qd=b(()=>{"use strict";var ZT=me(),eI=lo().includes,tI=Te(),rI=$i(),iI=tI(function(){return!Array(1).includes()});ZT({target:"Array",proto:!0,forced:iI},{includes:function(e){return eI(this,e,arguments.length>1?arguments[1]:void 0)}});rI("includes")});var Qt=b((T$,Gd)=>{"use strict";var aI=Et();Gd.exports=aI});var Yd=b((I$,Wd)=>{"use strict";Qd();var sI=Qt();Wd.exports=sI("Array","includes")});var Kd=b((E$,zd)=>{"use strict";var nI=Yd();zd.exports=nI});var nt=b((x$,Xd)=>{"use strict";var oI=Kd();Xd.exports=oI});var bs=b((V$,ep)=>{"use strict";var lI=Kn(),cI=Xn(),Zd=lI("keys");ep.exports=function(a){return Zd[a]||(Zd[a]=cI(a))}});var rp=b((B$,tp)=>{"use strict";var dI=Te();tp.exports=!dI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var gs=b((O$,ap)=>{"use strict";var pI=st(),hI=ce(),mI=Or(),fI=bs(),bI=rp(),ip=fI("IE_PROTO"),co=Object,gI=co.prototype;ap.exports=bI?co.getPrototypeOf:function(a){var e=mI(a);if(pI(e,ip))return e[ip];var t=e.constructor;return hI(t)&&e instanceof t?t.prototype:e instanceof co?gI:null}});var vs=b((_$,sp)=>{"use strict";sp.exports={}});var up=b((N$,op)=>{"use strict";var vI=ge(),po=st(),SI=dr(),yI=lo().indexOf,TI=vs(),np=vI([].push);op.exports=function(a,e){var t=SI(a),r=0,i=[],s;for(s in t)!po(TI,s)&&po(t,s)&&np(i,s);for(;e.length>r;)po(t,s=e[r++])&&(~yI(i,s)||np(i,s));return i}});var ho=b((F$,lp)=>{"use strict";lp.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var mo=b((q$,cp)=>{"use strict";var II=up(),EI=ho();cp.exports=Object.keys||function(e){return II(e,EI)}});var fo=b((U$,fp)=>{"use strict";var pp=qe(),xI=Te(),hp=ge(),PI=gs(),wI=mo(),AI=dr(),kI=_n().f,mp=hp(kI),LI=hp([].push),RI=pp&&xI(function(){var a=Object.create(null);return a[2]=2,!mp(a,2)}),dp=function(a){return function(e){for(var t=AI(e),r=wI(t),i=RI&&PI(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!pp||(i?u in t:mp(t,u)))&&LI(o,a?[u,t[u]]:t[u]);return o}};fp.exports={entries:dp(!0),values:dp(!1)}});var bp=b(()=>{"use strict";var $I=me(),MI=fo().entries;$I({target:"Object",stat:!0},{entries:function(e){return MI(e)}})});var vp=b((Q$,gp)=>{"use strict";bp();var DI=Br();gp.exports=DI.Object.entries});var yp=b((G$,Sp)=>{"use strict";var CI=vp();Sp.exports=CI});var jr=b((W$,Tp)=>{"use strict";var VI=yp();Tp.exports=VI});var mr=b((Y$,Ip)=>{"use strict";Ip.exports={}});var Pp=b((z$,xp)=>{"use strict";var BI=pe(),OI=ce(),Ep=BI.WeakMap;xp.exports=OI(Ep)&&/native code/.test(String(Ep))});var So=b((K$,kp)=>{"use strict";var _I=Pp(),Ap=pe(),NI=He(),FI=Fr(),bo=st(),go=Ai(),qI=bs(),UI=vs(),wp="Object already initialized",vo=Ap.TypeError,HI=Ap.WeakMap,Ss,Mi,ys,jI=function(a){return ys(a)?Mi(a):Ss(a,{})},QI=function(a){return function(e){var t;if(!NI(e)||(t=Mi(e)).type!==a)throw new vo("Incompatible receiver, "+a+" required");return t}};_I||go.state?(ot=go.state||(go.state=new HI),ot.get=ot.get,ot.has=ot.has,ot.set=ot.set,Ss=function(a,e){if(ot.has(a))throw new vo(wp);return e.facade=a,ot.set(a,e),e},Mi=function(a){return ot.get(a)||{}},ys=function(a){return ot.has(a)}):(fr=qI("state"),UI[fr]=!0,Ss=function(a,e){if(bo(a,fr))throw new vo(wp);return e.facade=a,FI(a,fr,e),e},Mi=function(a){return bo(a,fr)?a[fr]:{}},ys=function(a){return bo(a,fr)});var ot,fr;kp.exports={set:Ss,get:Mi,has:ys,enforce:jI,getterFor:QI}});var Io=b((X$,Rp)=>{"use strict";var yo=qe(),GI=st(),Lp=Function.prototype,WI=yo&&Object.getOwnPropertyDescriptor,To=GI(Lp,"name"),YI=To&&function(){}.name==="something",zI=To&&(!yo||yo&&WI(Lp,"name").configurable);Rp.exports={EXISTS:To,PROPER:YI,CONFIGURABLE:zI}});var Mp=b($p=>{"use strict";var KI=qe(),XI=io(),JI=hr(),ZI=mt(),eE=dr(),tE=mo();$p.f=KI&&!XI?Object.defineProperties:function(e,t){ZI(e);for(var r=eE(t),i=tE(t),s=i.length,n=0,o;s>n;)JI.f(e,o=i[n++],r[o]);return e}});var Eo=b((Z$,Dp)=>{"use strict";var rE=Et();Dp.exports=rE("document","documentElement")});var Ao=b((eM,Fp)=>{"use strict";var iE=mt(),aE=Mp(),Cp=ho(),sE=vs(),nE=Eo(),oE=hs(),uE=bs(),Vp=">",Bp="<",Po="prototype",wo="script",_p=uE("IE_PROTO"),xo=function(){},Np=function(a){return Bp+wo+Vp+a+Bp+"/"+wo+Vp},Op=function(a){a.write(Np("")),a.close();var e=a.parentWindow.Object;return a=null,e},lE=function(){var a=oE("iframe"),e="java"+wo+":",t;return a.style.display="none",nE.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Np("document.F=Object")),t.close(),t.F},Ts,Is=function(){try{Ts=new ActiveXObject("htmlfile")}catch(e){}Is=typeof document!="undefined"?document.domain&&Ts?Op(Ts):lE():Op(Ts);for(var a=Cp.length;a--;)delete Is[Po][Cp[a]];return Is()};sE[_p]=!0;Fp.exports=Object.create||function(e,t){var r;return e!==null?(xo[Po]=iE(e),r=new xo,xo[Po]=null,r[_p]=e):r=Is(),t===void 0?r:aE.f(r,t)}});var Qr=b((tM,qp)=>{"use strict";var cE=Fr();qp.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:cE(a,e,t),a}});var $o=b((rM,jp)=>{"use strict";var dE=Te(),pE=ce(),hE=He(),mE=Ao(),Up=gs(),fE=Qr(),bE=Ie(),gE=at(),Ro=bE("iterator"),Hp=!1,xt,ko,Lo;[].keys&&(Lo=[].keys(),"next"in Lo?(ko=Up(Up(Lo)),ko!==Object.prototype&&(xt=ko)):Hp=!0);var vE=!hE(xt)||dE(function(){var a={};return xt[Ro].call(a)!==a});vE?xt={}:gE&&(xt=mE(xt));pE(xt[Ro])||fE(xt,Ro,function(){return this});jp.exports={IteratorPrototype:xt,BUGGY_SAFARI_ITERATORS:Hp}});var Es=b((iM,Gp)=>{"use strict";var SE=Ie(),yE=SE("toStringTag"),Qp={};Qp[yE]="z";Gp.exports=String(Qp)==="[object z]"});var Di=b((aM,Wp)=>{"use strict";var TE=Es(),IE=ce(),xs=cr(),EE=Ie(),xE=EE("toStringTag"),PE=Object,wE=xs(function(){return arguments}())==="Arguments",AE=function(a,e){try{return a[e]}catch(t){}};Wp.exports=TE?xs:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=AE(e=PE(a),xE))=="string"?t:wE?xs(e):(r=xs(e))==="Object"&&IE(e.callee)?"Arguments":r}});var zp=b((sM,Yp)=>{"use strict";var kE=Es(),LE=Di();Yp.exports=kE?{}.toString:function(){return"[object "+LE(this)+"]"}});var Ci=b((nM,Xp)=>{"use strict";var RE=Es(),$E=hr().f,ME=Fr(),DE=st(),CE=zp(),VE=Ie(),Kp=VE("toStringTag");Xp.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(DE(i,Kp)||$E(i,Kp,{configurable:!0,value:e}),r&&!RE&&ME(i,"toString",CE))}});var Zp=b((oM,Jp)=>{"use strict";var BE=$o().IteratorPrototype,OE=Ao(),_E=Ei(),NE=Ci(),FE=mr(),qE=function(){return this};Jp.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=OE(BE,{next:_E(+!r,t)}),NE(a,i,!1,!0),FE[i]=qE,a}});var th=b((uM,eh)=>{"use strict";var UE=ge(),HE=ht();eh.exports=function(a,e,t){try{return UE(HE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var ih=b((lM,rh)=>{"use strict";var jE=He();rh.exports=function(a){return jE(a)||a===null}});var sh=b((cM,ah)=>{"use strict";var QE=ih(),GE=String,WE=TypeError;ah.exports=function(a){if(QE(a))return a;throw new WE("Can't set "+GE(a)+" as a prototype")}});var Mo=b((dM,nh)=>{"use strict";var YE=th(),zE=He(),KE=jt(),XE=sh();nh.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=YE(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return KE(i),XE(s),zE(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var gh=b((pM,bh)=>{"use strict";var JE=me(),ZE=Ue(),Ps=at(),mh=Io(),ex=ce(),tx=Zp(),oh=gs(),uh=Mo(),rx=Ci(),ix=Fr(),Do=Qr(),ax=Ie(),lh=mr(),fh=$o(),sx=mh.PROPER,nx=mh.CONFIGURABLE,ch=fh.IteratorPrototype,ws=fh.BUGGY_SAFARI_ITERATORS,Vi=ax("iterator"),dh="keys",Bi="values",ph="entries",hh=function(){return this};bh.exports=function(a,e,t,r,i,s,n){tx(t,e,r);var o=function(I){if(I===i&&p)return p;if(!ws&&I&&I in c)return c[I];switch(I){case dh:return function(){return new t(this,I)};case Bi:return function(){return new t(this,I)};case ph:return function(){return new t(this,I)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[Vi]||c["@@iterator"]||i&&c[i],p=!ws&&d||o(i),h=e==="Array"&&c.entries||d,f,g,S;if(h&&(f=oh(h.call(new a)),f!==Object.prototype&&f.next&&(!Ps&&oh(f)!==ch&&(uh?uh(f,ch):ex(f[Vi])||Do(f,Vi,hh)),rx(f,u,!0,!0),Ps&&(lh[u]=hh))),sx&&i===Bi&&d&&d.name!==Bi&&(!Ps&&nx?ix(c,"name",Bi):(l=!0,p=function(){return ZE(d,this)})),i)if(g={values:o(Bi),keys:s?p:o(dh),entries:o(ph)},n)for(S in g)(ws||l||!(S in c))&&Do(c,S,g[S]);else JE({target:e,proto:!0,forced:ws||l},g);return(!Ps||n)&&c[Vi]!==p&&Do(c,Vi,p,{name:i}),lh[e]=p,g}});var Sh=b((hM,vh)=>{"use strict";vh.exports=function(a,e){return{value:a,done:e}}});var Vo=b((mM,xh)=>{"use strict";var ox=dr(),Co=$i(),yh=mr(),Ih=So(),ux=hr().f,lx=gh(),As=Sh(),cx=at(),dx=qe(),Eh="Array Iterator",px=Ih.set,hx=Ih.getterFor(Eh);xh.exports=lx(Array,"Array",function(a,e){px(this,{type:Eh,target:ox(a),index:0,kind:e})},function(){var a=hx(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,As(void 0,!0);switch(a.kind){case"keys":return As(t,!1);case"values":return As(e[t],!1)}return As([t,e[t]],!1)},"values");var Th=yh.Arguments=yh.Array;Co("keys");Co("values");Co("entries");if(!cx&&dx&&Th.name!=="values")try{ux(Th,"name",{value:"values"})}catch(a){}});var wh=b((fM,Ph)=>{"use strict";var mx=Ie(),fx=mr(),bx=mx("iterator"),gx=Array.prototype;Ph.exports=function(a){return a!==void 0&&(fx.Array===a||gx[bx]===a)}});var Bo=b((bM,kh)=>{"use strict";var vx=Di(),Ah=wi(),Sx=Vr(),yx=mr(),Tx=Ie(),Ix=Tx("iterator");kh.exports=function(a){if(!Sx(a))return Ah(a,Ix)||Ah(a,"@@iterator")||yx[vx(a)]}});var Rh=b((gM,Lh)=>{"use strict";var Ex=Ue(),xx=ht(),Px=mt(),wx=Pi(),Ax=Bo(),kx=TypeError;Lh.exports=function(a,e){var t=arguments.length<2?Ax(a):e;if(xx(t))return Px(Ex(t,a));throw new kx(wx(a)+" is not iterable")}});var Dh=b((vM,Mh)=>{"use strict";var Lx=Ue(),$h=mt(),Rx=wi();Mh.exports=function(a,e,t){var r,i;$h(a);try{if(r=Rx(a,"return"),!r){if(e==="throw")throw t;return t}r=Lx(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return $h(r),t}});var Ls=b((SM,Oh)=>{"use strict";var $x=Nr(),Mx=Ue(),Dx=mt(),Cx=Pi(),Vx=wh(),Bx=Hr(),Ch=xi(),Ox=Rh(),_x=Bo(),Vh=Dh(),Nx=TypeError,ks=function(a,e){this.stopped=a,this.result=e},Bh=ks.prototype;Oh.exports=function(a,e,t){var r=t&&t.that,i=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=$x(e,r),l,c,d,p,h,f,g,S=function(E){return l&&Vh(l,"normal",E),new ks(!0,E)},I=function(E){return i?(Dx(E),o?u(E[0],E[1],S):u(E[0],E[1])):o?u(E,S):u(E)};if(s)l=a.iterator;else if(n)l=a;else{if(c=_x(a),!c)throw new Nx(Cx(a)+" is not iterable");if(Vx(c)){for(d=0,p=Bx(a);p>d;d++)if(h=I(a[d]),h&&Ch(Bh,h))return h;return new ks(!1)}l=Ox(a,c)}for(f=s?a.next:l.next;!(g=Mx(f,l)).done;){try{h=I(g.value)}catch(E){Vh(l,"throw",E)}if(typeof h=="object"&&h&&Ch(Bh,h))return h}return new ks(!1)}});var Nh=b((yM,_h)=>{"use strict";var Fx=qe(),qx=hr(),Ux=Ei();_h.exports=function(a,e,t){Fx?qx.f(a,e,Ux(0,t)):a[e]=t}});var Fh=b(()=>{"use strict";var Hx=me(),jx=Ls(),Qx=Nh();Hx({target:"Object",stat:!0},{fromEntries:function(e){var t={};return jx(e,function(r,i){Qx(t,r,i)},{AS_ENTRIES:!0}),t}})});var Uh=b((EM,qh)=>{"use strict";Vo();Fh();var Gx=Br();qh.exports=Gx.Object.fromEntries});var jh=b((xM,Hh)=>{"use strict";Hh.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 Gh=b(()=>{"use strict";Vo();var Wx=jh(),Yx=pe(),zx=Ci(),Qh=mr();for(Rs in Wx)zx(Yx[Rs],Rs),Qh[Rs]=Qh.Array;var Rs});var Yh=b((AM,Wh)=>{"use strict";var Kx=Uh();Gh();Wh.exports=Kx});var Oo=b((kM,zh)=>{"use strict";var Xx=Yh();zh.exports=Xx});var Kh=b(()=>{"use strict"});var _o=b(($M,Xh)=>{"use strict";var Oi=pe(),Jx=pr(),Zx=cr(),$s=function(a){return Jx.slice(0,a.length)===a};Xh.exports=function(){return $s("Bun/")?"BUN":$s("Cloudflare-Workers")?"CLOUDFLARE":$s("Deno/")?"DENO":$s("Node.js/")?"NODE":Oi.Bun&&typeof Bun.version=="string"?"BUN":Oi.Deno&&typeof Deno.version=="object"?"DENO":Zx(Oi.process)==="process"?"NODE":Oi.window&&Oi.document?"BROWSER":"REST"}()});var Ms=b((MM,Jh)=>{"use strict";var eP=_o();Jh.exports=eP==="NODE"});var em=b((DM,Zh)=>{"use strict";var tP=hr();Zh.exports=function(a,e,t){return tP.f(a,e,t)}});var im=b((CM,rm)=>{"use strict";var rP=Et(),iP=em(),aP=Ie(),sP=qe(),tm=aP("species");rm.exports=function(a){var e=rP(a);sP&&e&&!e[tm]&&iP(e,tm,{configurable:!0,get:function(){return this}})}});var sm=b((VM,am)=>{"use strict";var nP=xi(),oP=TypeError;am.exports=function(a,e){if(nP(e,a))return a;throw new oP("Incorrect invocation")}});var Fo=b((BM,nm)=>{"use strict";var uP=ge(),lP=ce(),No=Ai(),cP=uP(Function.toString);lP(No.inspectSource)||(No.inspectSource=function(a){return cP(a)});nm.exports=No.inspectSource});var Uo=b((OM,dm)=>{"use strict";var dP=ge(),pP=Te(),om=ce(),hP=Di(),mP=Et(),fP=Fo(),um=function(){},lm=mP("Reflect","construct"),qo=/^\s*(?:class|function)\b/,bP=dP(qo.exec),gP=!qo.test(um),_i=function(e){if(!om(e))return!1;try{return lm(um,[],e),!0}catch(t){return!1}},cm=function(e){if(!om(e))return!1;switch(hP(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return gP||!!bP(qo,fP(e))}catch(t){return!0}};cm.sham=!0;dm.exports=!lm||pP(function(){var a;return _i(_i.call)||!_i(Object)||!_i(function(){a=!0})||a})?cm:_i});var hm=b((_M,pm)=>{"use strict";var vP=Uo(),SP=Pi(),yP=TypeError;pm.exports=function(a){if(vP(a))return a;throw new yP(SP(a)+" is not a constructor")}});var Ho=b((NM,fm)=>{"use strict";var mm=mt(),TP=hm(),IP=Vr(),EP=Ie(),xP=EP("species");fm.exports=function(a,e){var t=mm(a).constructor,r;return t===void 0||IP(r=mm(t)[xP])?e:TP(r)}});var gm=b((FM,bm)=>{"use strict";var PP=ge();bm.exports=PP([].slice)});var Sm=b((qM,vm)=>{"use strict";var wP=TypeError;vm.exports=function(a,e){if(a<e)throw new wP("Not enough arguments");return a}});var jo=b((UM,ym)=>{"use strict";var AP=pr();ym.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(AP)});var Zo=b((HM,Lm)=>{"use strict";var je=pe(),kP=Cn(),LP=Nr(),Tm=ce(),RP=st(),km=Te(),Im=Eo(),$P=gm(),Em=hs(),MP=Sm(),DP=jo(),CP=Ms(),Ko=je.setImmediate,Xo=je.clearImmediate,VP=je.process,Qo=je.Dispatch,BP=je.Function,xm=je.MessageChannel,OP=je.String,Go=0,Ni={},Pm="onreadystatechange",Fi,br,Wo,Yo;km(function(){Fi=je.location});var Jo=function(a){if(RP(Ni,a)){var e=Ni[a];delete Ni[a],e()}},zo=function(a){return function(){Jo(a)}},wm=function(a){Jo(a.data)},Am=function(a){je.postMessage(OP(a),Fi.protocol+"//"+Fi.host)};(!Ko||!Xo)&&(Ko=function(e){MP(arguments.length,1);var t=Tm(e)?e:BP(e),r=$P(arguments,1);return Ni[++Go]=function(){kP(t,void 0,r)},br(Go),Go},Xo=function(e){delete Ni[e]},CP?br=function(a){VP.nextTick(zo(a))}:Qo&&Qo.now?br=function(a){Qo.now(zo(a))}:xm&&!DP?(Wo=new xm,Yo=Wo.port2,Wo.port1.onmessage=wm,br=LP(Yo.postMessage,Yo)):je.addEventListener&&Tm(je.postMessage)&&!je.importScripts&&Fi&&Fi.protocol!=="file:"&&!km(Am)?(br=Am,je.addEventListener("message",wm,!1)):Pm in Em("script")?br=function(a){Im.appendChild(Em("script"))[Pm]=function(){Im.removeChild(this),Jo(a)}}:br=function(a){setTimeout(zo(a),0)});Lm.exports={set:Ko,clear:Xo}});var Mm=b((jM,$m)=>{"use strict";var Rm=pe(),_P=qe(),NP=Object.getOwnPropertyDescriptor;$m.exports=function(a){if(!_P)return Rm[a];var e=NP(Rm,a);return e&&e.value}});var eu=b((QM,Cm)=>{"use strict";var Dm=function(){this.head=null,this.tail=null};Dm.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}}};Cm.exports=Dm});var Bm=b((GM,Vm)=>{"use strict";var FP=pr();Vm.exports=/ipad|iphone|ipod/i.test(FP)&&typeof Pebble!="undefined"});var _m=b((WM,Om)=>{"use strict";var qP=pr();Om.exports=/web0s(?!.*chrome)/i.test(qP)});var Qm=b((YM,jm)=>{"use strict";var Wr=pe(),UP=Mm(),Nm=Nr(),tu=Zo().set,HP=eu(),jP=jo(),QP=Bm(),GP=_m(),ru=Ms(),Fm=Wr.MutationObserver||Wr.WebKitMutationObserver,qm=Wr.document,Um=Wr.process,Ds=Wr.Promise,su=UP("queueMicrotask"),Gr,iu,au,Cs,Hm;su||(qi=new HP,Ui=function(){var a,e;for(ru&&(a=Um.domain)&&a.exit();e=qi.get();)try{e()}catch(t){throw qi.head&&Gr(),t}a&&a.enter()},!jP&&!ru&&!GP&&Fm&&qm?(iu=!0,au=qm.createTextNode(""),new Fm(Ui).observe(au,{characterData:!0}),Gr=function(){au.data=iu=!iu}):!QP&&Ds&&Ds.resolve?(Cs=Ds.resolve(void 0),Cs.constructor=Ds,Hm=Nm(Cs.then,Cs),Gr=function(){Hm(Ui)}):ru?Gr=function(){Um.nextTick(Ui)}:(tu=Nm(tu,Wr),Gr=function(){tu(Ui)}),su=function(a){qi.head||Gr(),qi.add(a)});var qi,Ui;jm.exports=su});var Wm=b((zM,Gm)=>{"use strict";Gm.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Vs=b((KM,Ym)=>{"use strict";Ym.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var gr=b((XM,zm)=>{"use strict";var WP=pe();zm.exports=WP.Promise});var Yr=b((JM,Zm)=>{"use strict";var YP=pe(),Hi=gr(),zP=ce(),KP=ro(),XP=Fo(),JP=Ie(),Km=_o(),ZP=at(),nu=Hn(),Xm=Hi&&Hi.prototype,ew=JP("species"),ou=!1,Jm=zP(YP.PromiseRejectionEvent),tw=KP("Promise",function(){var a=XP(Hi),e=a!==String(Hi);if(!e&&nu===66||ZP&&!(Xm.catch&&Xm.finally))return!0;if(!nu||nu<51||!/native code/.test(a)){var t=new Hi(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[ew]=r,ou=t.then(function(){})instanceof r,!ou)return!0}return!e&&(Km==="BROWSER"||Km==="DENO")&&!Jm});Zm.exports={CONSTRUCTOR:tw,REJECTION_EVENT:Jm,SUBCLASSING:ou}});var zr=b((ZM,tf)=>{"use strict";var ef=ht(),rw=TypeError,iw=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new rw("Bad Promise constructor");e=r,t=i}),this.resolve=ef(e),this.reject=ef(t)};tf.exports.f=function(a){return new iw(a)}});var Tf=b(()=>{"use strict";var aw=me(),sw=at(),Ns=Ms(),Gt=pe(),Zr=Ue(),rf=Qr(),af=Mo(),nw=Ci(),ow=im(),uw=ht(),_s=ce(),lw=He(),cw=sm(),dw=Ho(),lf=Zo().set,pu=Qm(),pw=Wm(),hw=Vs(),mw=eu(),cf=So(),Fs=gr(),hu=Yr(),df=zr(),qs="Promise",pf=hu.CONSTRUCTOR,fw=hu.REJECTION_EVENT,bw=hu.SUBCLASSING,uu=cf.getterFor(qs),gw=cf.set,Kr=Fs&&Fs.prototype,vr=Fs,Bs=Kr,hf=Gt.TypeError,lu=Gt.document,mu=Gt.process,cu=df.f,vw=cu,Sw=!!(lu&&lu.createEvent&&Gt.dispatchEvent),mf="unhandledrejection",yw="rejectionhandled",sf=0,ff=1,Tw=2,fu=1,bf=2,Os,nf,Iw,of,gf=function(a){var e;return lw(a)&&_s(e=a.then)?e:!1},vf=function(a,e){var t=e.value,r=e.state===ff,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===bf&&xw(e),e.rejection=fu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new hf("Promise-chain cycle")):(l=gf(u))?Zr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Sf=function(a,e){a.notified||(a.notified=!0,pu(function(){for(var t=a.reactions,r;r=t.get();)vf(r,a);a.notified=!1,e&&!a.rejection&&Ew(a)}))},yf=function(a,e,t){var r,i;Sw?(r=lu.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Gt.dispatchEvent(r)):r={promise:e,reason:t},!fw&&(i=Gt["on"+a])?i(r):a===mf&&pw("Unhandled promise rejection",t)},Ew=function(a){Zr(lf,Gt,function(){var e=a.facade,t=a.value,r=uf(a),i;if(r&&(i=hw(function(){Ns?mu.emit("unhandledRejection",t,e):yf(mf,e,t)}),a.rejection=Ns||uf(a)?bf:fu,i.error))throw i.value})},uf=function(a){return a.rejection!==fu&&!a.parent},xw=function(a){Zr(lf,Gt,function(){var e=a.facade;Ns?mu.emit("rejectionHandled",e):yf(yw,e,a.value)})},Xr=function(a,e,t){return function(r){a(e,r,t)}},Jr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=Tw,Sf(a,!0))},du=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new hf("Promise can't be resolved itself");var r=gf(e);r?pu(function(){var i={done:!1};try{Zr(r,e,Xr(du,i,a),Xr(Jr,i,a))}catch(s){Jr(i,s,a)}}):(a.value=e,a.state=ff,Sf(a,!1))}catch(i){Jr({done:!1},i,a)}}};if(pf&&(vr=function(e){cw(this,Bs),uw(e),Zr(Os,this);var t=uu(this);try{e(Xr(du,t),Xr(Jr,t))}catch(r){Jr(t,r)}},Bs=vr.prototype,Os=function(e){gw(this,{type:qs,done:!1,notified:!1,parent:!1,reactions:new mw,rejection:!1,state:sf,value:void 0})},Os.prototype=rf(Bs,"then",function(e,t){var r=uu(this),i=cu(dw(this,vr));return r.parent=!0,i.ok=_s(e)?e:!0,i.fail=_s(t)&&t,i.domain=Ns?mu.domain:void 0,r.state===sf?r.reactions.add(i):pu(function(){vf(i,r)}),i.promise}),nf=function(){var a=new Os,e=uu(a);this.promise=a,this.resolve=Xr(du,e),this.reject=Xr(Jr,e)},df.f=cu=function(a){return a===vr||a===Iw?new nf(a):vw(a)},!sw&&_s(Fs)&&Kr!==Object.prototype)){of=Kr.then,bw||rf(Kr,"then",function(e,t){var r=this;return new vr(function(i,s){Zr(of,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Kr.constructor}catch(a){}af&&af(Kr,Bs)}aw({global:!0,constructor:!0,wrap:!0,forced:pf},{Promise:vr});nw(vr,qs,!1,!0);ow(qs)});var wf=b((rD,Pf)=>{"use strict";var Pw=Ie(),Ef=Pw("iterator"),xf=!1;try{If=0,bu={next:function(){return{done:!!If++}},return:function(){xf=!0}},bu[Ef]=function(){return this},Array.from(bu,function(){throw 2})}catch(a){}var If,bu;Pf.exports=function(a,e){try{if(!e&&!xf)return!1}catch(i){return!1}var t=!1;try{var r={};r[Ef]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var gu=b((iD,Af)=>{"use strict";var ww=gr(),Aw=wf(),kw=Yr().CONSTRUCTOR;Af.exports=kw||!Aw(function(a){ww.all(a).then(void 0,function(){})})});var kf=b(()=>{"use strict";var Lw=me(),Rw=Ue(),$w=ht(),Mw=zr(),Dw=Vs(),Cw=Ls(),Vw=gu();Lw({target:"Promise",stat:!0,forced:Vw},{all:function(e){var t=this,r=Mw.f(t),i=r.resolve,s=r.reject,n=Dw(function(){var o=$w(t.resolve),u=[],l=0,c=1;Cw(e,function(d){var p=l++,h=!1;c++,Rw(o,t,d).then(function(f){h||(h=!0,u[p]=f,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var Rf=b(()=>{"use strict";var Bw=me(),Ow=at(),_w=Yr().CONSTRUCTOR,Su=gr(),Nw=Et(),Fw=ce(),qw=Qr(),Lf=Su&&Su.prototype;Bw({target:"Promise",proto:!0,forced:_w,real:!0},{catch:function(a){return this.then(void 0,a)}});!Ow&&Fw(Su)&&(vu=Nw("Promise").prototype.catch,Lf.catch!==vu&&qw(Lf,"catch",vu,{unsafe:!0}));var vu});var $f=b(()=>{"use strict";var Uw=me(),Hw=Ue(),jw=ht(),Qw=zr(),Gw=Vs(),Ww=Ls(),Yw=gu();Uw({target:"Promise",stat:!0,forced:Yw},{race:function(e){var t=this,r=Qw.f(t),i=r.reject,s=Gw(function(){var n=jw(t.resolve);Ww(e,function(o){Hw(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var Mf=b(()=>{"use strict";var zw=me(),Kw=zr(),Xw=Yr().CONSTRUCTOR;zw({target:"Promise",stat:!0,forced:Xw},{reject:function(e){var t=Kw.f(this),r=t.reject;return r(e),t.promise}})});var yu=b((pD,Df)=>{"use strict";var Jw=mt(),Zw=He(),eA=zr();Df.exports=function(a,e){if(Jw(a),Zw(e)&&e.constructor===a)return e;var t=eA.f(a),r=t.resolve;return r(e),t.promise}});var Bf=b(()=>{"use strict";var tA=me(),rA=Et(),Cf=at(),iA=gr(),Vf=Yr().CONSTRUCTOR,aA=yu(),sA=rA("Promise"),nA=Cf&&!Vf;tA({target:"Promise",stat:!0,forced:Cf||Vf},{resolve:function(e){return aA(nA&&this===sA?iA:this,e)}})});var Of=b(()=>{"use strict";Tf();kf();Rf();$f();Mf();Bf()});var qf=b(()=>{"use strict";var oA=me(),uA=at(),Us=gr(),lA=Te(),Nf=Et(),Ff=ce(),cA=Ho(),_f=yu(),dA=Qr(),Iu=Us&&Us.prototype,pA=!!Us&&lA(function(){Iu.finally.call({then:function(){}},function(){})});oA({target:"Promise",proto:!0,real:!0,forced:pA},{finally:function(a){var e=cA(this,Nf("Promise")),t=Ff(a);return this.then(t?function(r){return _f(e,a()).then(function(){return r})}:a,t?function(r){return _f(e,a()).then(function(){throw r})}:a)}});!uA&&Ff(Us)&&(Tu=Nf("Promise").prototype.finally,Iu.finally!==Tu&&dA(Iu,"finally",Tu,{unsafe:!0}));var Tu});var Hf=b((SD,Uf)=>{"use strict";Kh();Of();qf();var hA=Qt();Uf.exports=hA("Promise","finally")});var Qf=b((yD,jf)=>{"use strict";var mA=Hf();jf.exports=mA});var Hs=b((TD,Gf)=>{"use strict";var fA=Qf();Gf.exports=fA});var Zf=b(()=>{"use strict";var yA=me(),TA=fo().values;yA({target:"Object",stat:!0},{values:function(e){return TA(e)}})});var tb=b((JD,eb)=>{"use strict";Zf();var IA=Br();eb.exports=IA.Object.values});var ib=b((ZD,rb)=>{"use strict";var EA=tb();rb.exports=EA});var ei=b((e0,ab)=>{"use strict";var xA=ib();ab.exports=xA});var ub=b(()=>{"use strict";var kA=me(),LA=Or(),RA=Hr(),$A=Ri(),MA=$i();kA({target:"Array",proto:!0},{at:function(e){var t=LA(this),r=RA(t),i=$A(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});MA("at")});var cb=b((x0,lb)=>{"use strict";ub();var DA=Qt();lb.exports=DA("Array","at")});var pb=b((P0,db)=>{"use strict";var CA=cb();db.exports=CA});var Kt=b((w0,hb)=>{"use strict";var VA=pb();hb.exports=VA});var qu=b((JC,Vb)=>{"use strict";var WA=cr();Vb.exports=Array.isArray||function(e){return WA(e)==="Array"}});var Ob=b((ZC,Bb)=>{"use strict";var YA=TypeError,zA=9007199254740991;Bb.exports=function(a){if(a>zA)throw YA("Maximum allowed index exceeded");return a}});var Fb=b((eV,Nb)=>{"use strict";var KA=qu(),XA=Hr(),JA=Ob(),ZA=Nr(),_b=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,c=n?ZA(n,o):!1,d,p;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&KA(d)?(p=XA(d),u=_b(a,e,d,p,u,s-1)-1):(JA(u+1),a[u]=d),u++),l++;return u};Nb.exports=_b});var jb=b((tV,Hb)=>{"use strict";var qb=qu(),ek=Uo(),tk=He(),rk=Ie(),ik=rk("species"),Ub=Array;Hb.exports=function(a){var e;return qb(a)&&(e=a.constructor,ek(e)&&(e===Ub||qb(e.prototype))?e=void 0:tk(e)&&(e=e[ik],e===null&&(e=void 0))),e===void 0?Ub:e}});var Gb=b((rV,Qb)=>{"use strict";var ak=jb();Qb.exports=function(a,e){return new(ak(a))(e===0?0:e)}});var Wb=b(()=>{"use strict";var sk=me(),nk=Fb(),ok=ht(),uk=Or(),lk=Hr(),ck=Gb();sk({target:"Array",proto:!0},{flatMap:function(e){var t=uk(this),r=lk(t),i;return ok(e),i=ck(t,0),i.length=nk(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var Yb=b(()=>{"use strict";var dk=$i();dk("flatMap")});var Kb=b((oV,zb)=>{"use strict";Wb();Yb();var pk=Qt();zb.exports=pk("Array","flatMap")});var Jb=b((uV,Xb)=>{"use strict";var hk=Kb();Xb.exports=hk});var Uu=b((lV,Zb)=>{"use strict";var mk=Jb();Zb.exports=mk});var ra=b((vV,Sg)=>{"use strict";var Ik=Di(),Ek=String;Sg.exports=function(a){if(Ik(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return Ek(a)}});var ju=b((SV,yg)=>{"use strict";yg.exports=`
|
|
7
|
-
\v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`});var Eg=b((yV,Ig)=>{"use strict";var xk=ge(),Pk=jt(),wk=ra(),Gu=ju(),Tg=xk("".replace),Ak=RegExp("^["+Gu+"]+"),kk=RegExp("(^|[^"+Gu+"])["+Gu+"]+$"),Qu=function(a){return function(e){var t=wk(Pk(e));return a&1&&(t=Tg(t,Ak,"")),a&2&&(t=Tg(t,kk,"$1")),t}};Ig.exports={start:Qu(1),end:Qu(2),trim:Qu(3)}});var Ag=b((TV,wg)=>{"use strict";var Lk=Io().PROPER,Rk=Te(),xg=ju(),Pg="\u200B\x85\u180E";wg.exports=function(a){return Rk(function(){return!!xg[a]()||Pg[a]()!==Pg||Lk&&xg[a].name!==a})}});var Wu=b((IV,kg)=>{"use strict";var $k=Eg().start,Mk=Ag();kg.exports=Mk("trimStart")?function(){return $k(this)}:"".trimStart});var Rg=b(()=>{"use strict";var Dk=me(),Lg=Wu();Dk({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Lg},{trimLeft:Lg})});var Mg=b(()=>{"use strict";Rg();var Ck=me(),$g=Wu();Ck({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==$g},{trimStart:$g})});var Cg=b((AV,Dg)=>{"use strict";Mg();var Vk=Qt();Dg.exports=Vk("String","trimLeft")});var Bg=b((kV,Vg)=>{"use strict";var Bk=Cg();Vg.exports=Bk});var _g=b((LV,Og)=>{"use strict";var Ok=Bg();Og.exports=Ok});var Jg=b(()=>{"use strict"});var Zg=b(()=>{"use strict"});var tv=b((a_,ev)=>{"use strict";var iL=He(),aL=cr(),sL=Ie(),nL=sL("match");ev.exports=function(a){var e;return iL(a)&&((e=a[nL])!==void 0?!!e:aL(a)==="RegExp")}});var iv=b((s_,rv)=>{"use strict";var oL=mt();rv.exports=function(){var a=oL(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 nv=b((n_,sv)=>{"use strict";var uL=Ue(),lL=st(),cL=xi(),dL=iv(),av=RegExp.prototype;sv.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in av)&&!lL(a,"flags")&&cL(av,a)?uL(dL,a):e}});var uv=b((o_,ov)=>{"use strict";var el=ge(),pL=Or(),hL=Math.floor,Ju=el("".charAt),mL=el("".replace),Zu=el("".slice),fL=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,bL=/\$([$&'`]|\d{1,2})/g;ov.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=bL;return i!==void 0&&(i=pL(i),u=fL),mL(s,u,function(l,c){var d;switch(Ju(c,0)){case"$":return"$";case"&":return a;case"`":return Zu(e,0,t);case"'":return Zu(e,n);case"<":d=i[Zu(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=hL(p/10);return h===0?l:h<=o?r[h-1]===void 0?Ju(c,1):r[h-1]+Ju(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var dv=b(()=>{"use strict";var gL=me(),vL=Ue(),rl=ge(),lv=jt(),SL=ce(),yL=Vr(),TL=tv(),oi=ra(),IL=wi(),EL=nv(),xL=uv(),PL=Ie(),wL=at(),AL=PL("replace"),kL=TypeError,tl=rl("".indexOf),LL=rl("".replace),cv=rl("".slice),RL=Math.max;gL({target:"String",proto:!0},{replaceAll:function(e,t){var r=lv(this),i,s,n,o,u,l,c,d,p,h,f=0,g="";if(!yL(e)){if(i=TL(e),i&&(s=oi(lv(EL(e))),!~tl(s,"g")))throw new kL("`.replaceAll` does not allow non-global regexes");if(n=IL(e,AL),n)return vL(n,e,r,t);if(wL&&i)return LL(oi(r),e,t)}for(o=oi(r),u=oi(e),l=SL(t),l||(t=oi(t)),c=u.length,d=RL(1,c),p=tl(o,u);p!==-1;)h=l?oi(t(u,p,o)):xL(u,o,p,[],void 0,t),g+=cv(o,f,p)+h,f=p+c,p=p+d>o.length?-1:tl(o,u,p+d);return f<o.length&&(g+=cv(o,f)),g}})});var hv=b((c_,pv)=>{"use strict";Jg();Zg();dv();var $L=Qt();pv.exports=$L("String","replaceAll")});var fv=b((d_,mv)=>{"use strict";var ML=hv();mv.exports=ML});var gv=b((p_,bv)=>{"use strict";var DL=fv();bv.exports=DL});var Sv=b((h_,vv)=>{"use strict";var CL=Ri(),VL=ra(),BL=jt(),OL=RangeError;vv.exports=function(e){var t=VL(BL(this)),r="",i=CL(e);if(i<0||i===1/0)throw new OL("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var xv=b((m_,Ev)=>{"use strict";var Iv=ge(),_L=uo(),yv=ra(),NL=Sv(),FL=jt(),qL=Iv(NL),UL=Iv("".slice),HL=Math.ceil,Tv=function(a){return function(e,t,r){var i=yv(FL(e)),s=_L(t),n=i.length,o=r===void 0?" ":yv(r),u,l;return s<=n||o===""?i:(u=s-n,l=qL(o,HL(u/o.length)),l.length>u&&(l=UL(l,0,u)),a?i+l:l+i)}};Ev.exports={start:Tv(!1),end:Tv(!0)}});var wv=b((f_,Pv)=>{"use strict";var jL=pr();Pv.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(jL)});var Av=b(()=>{"use strict";var QL=me(),GL=xv().start,WL=wv();QL({target:"String",proto:!0,forced:WL},{padStart:function(e){return GL(this,e,arguments.length>1?arguments[1]:void 0)}})});var Lv=b((v_,kv)=>{"use strict";Av();var YL=Qt();kv.exports=YL("String","padStart")});var $v=b((S_,Rv)=>{"use strict";var zL=Lv();Rv.exports=zL});var Dv=b((y_,Mv)=>{"use strict";var KL=$v();Mv.exports=KL});var mR={};NS(mR,{ChromecastState:()=>Si,HttpConnectionType:()=>ls,Observable:()=>yt.Observable,PlaybackState:()=>ke,Player:()=>Ya,PredefinedQualityLimits:()=>yi,SDK_VERSION:()=>hR,Subject:()=>yt.Subject,Subscription:()=>yt.Subscription,Surface:()=>cs,VERSION:()=>Mn,ValueSubject:()=>yt.ValueSubject,VideoFormat:()=>It,VideoQuality:()=>yt.VideoQuality});module.exports=FS(mR);var Mn="2.0.126-dev.3f94cfc5.0";var ke=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(ke||{}),It=(x=>(x.MPEG="MPEG",x.DASH="DASH",x.DASH_SEP="DASH_SEP",x.DASH_SEP_VK="DASH_SEP",x.DASH_WEBM="DASH_WEBM",x.DASH_WEBM_AV1="DASH_WEBM_AV1",x.DASH_STREAMS="DASH_STREAMS",x.DASH_WEBM_VK="DASH_WEBM",x.DASH_ONDEMAND="DASH_ONDEMAND",x.DASH_ONDEMAND_VK="DASH_ONDEMAND",x.DASH_LIVE="DASH_LIVE",x.DASH_LIVE_CMAF="DASH_LIVE_CMAF",x.DASH_LIVE_WEBM="DASH_LIVE_WEBM",x.HLS="HLS",x.HLS_ONDEMAND="HLS_ONDEMAND",x.HLS_JS="HLS",x.HLS_LIVE="HLS_LIVE",x.HLS_LIVE_CMAF="HLS_LIVE_CMAF",x.WEB_RTC_LIVE="WEB_RTC_LIVE",x))(It||{});var Si=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(Si||{}),ls=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(ls||{});var cs=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(cs||{}),yi=(r=>(r.TRAFFIC_SAVING="traffic_saving",r.HIGH_QUALITY="high_quality",r.UNKNOWN="unknown",r))(yi||{});var wS=U(nt(),1);var N=require("@vkontakte/videoplayer-shared/es2018");var Jd=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e(),r.onerror=i=>t(i),document.body.appendChild(r)});var fs=class{constructor(e){this.connection$=new N.ValueSubject(void 0);this.castState$=new N.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new N.Subject;this.realCastState$=new N.ValueSubject("NOT_AVAILABLE");this.subscription=new N.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 r=(0,N.isNonNullable)((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},i||Jd("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:N.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 r,i,s;(s=(i=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:i.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,N.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,N.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,N.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),r=cast.framework.CastContext.getInstance();this.subscription.add((0,N.fromEvent)(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{var s,n,o;switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=r.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,N.assertNever)(i.sessionState)}})).add((0,N.merge)((0,N.fromEvent)(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,N.tap)(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),(0,N.map)(i=>i.castState)),(0,N.observableFrom)([r.getCastState()])).pipe((0,N.filterChanged)(),(0,N.map)(uI),(0,N.tap)(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=(0,N.isNonNullable)(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();(0,N.assertNonNullable)(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;((0,N.isNullable)(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?(0,N.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":i)}))}initializeCastApi(){var i;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(i=this.params.receiverApplicationId)!=null?i:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:N.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},uI=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,N.assertNever)(a)}};var Il=U(nt(),1),hS=U(jr(),1),mS=U(Oo(),1);var Kf=U(Hs(),1);var Eu=require("@vkontakte/videoplayer-shared/es2018");var Ee=(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 r=new URL(a);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(a);return!r.searchParams.get("offset_p")&&e===0?a:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:(0,Eu.assertNever)(t)}return a},js=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(a);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(a);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:(0,Eu.assertNever)(e)}};var A=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};var ft=require("@vkontakte/videoplayer-shared/es2018"),H=class{constructor(e){this.transitionStarted$=new ft.Subject;this.transitionEnded$=new ft.Subject;this.transitionUpdated$=new ft.Subject;this.forceChanged$=new ft.Subject;this.stateChangeStarted$=(0,ft.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,ft.merge)(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,r=this.state;this.transition=void 0,this.prevState=r,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:r,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,r=this.state;r===e||(0,ft.isNonNullable)(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};var Wf=require("@vkontakte/videoplayer-shared/es2018"),Yf=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_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,Wf.assertNever)(a)}};var R=require("@vkontakte/videoplayer-shared/es2018");var bA=5,gA=5,vA=500,zf=7e3,ji=class{constructor(e){this.subscription=new R.Subscription;this.loadMediaTimeoutSubscription=new R.Subscription;this.videoState=new H("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,R.assertNever)(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,R.assertNever)(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,R.assertNever)(e)}break}default:(0,R.assertNever)(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Yf(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new R.Subscription;this.subscription.add(e),this.subscription.add((0,R.merge)(this.videoState.stateChangeStarted$.pipe((0,R.map)(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe((0,R.map)(i=>`stateChangeEnded$ ${JSON.stringify(i)}`))).subscribe(i=>this.log({message:`[videoState] ${i}`})));let t=(i,s)=>this.subscription.add(i.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let i=new R.Subject;e.add(i.pipe((0,R.debounce)(vA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>bA)&&i.next(o),s=o})),e.add((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);let{remotePlayer:s}=this.params.connection,n=i.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<gA&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),A(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:(0,R.assertNever)(n)}}),t((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=(0,R.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,R.observableFrom)(["init"])).pipe((0,R.debounce)(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),A(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),A(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"),A(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"&&A(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let c=t[e];(0,R.assertNonNullable)(c);let d=(0,R.getHighestQuality)(Object.keys(c));(0,R.assertNonNullable)(d);let p=c[d];(0,R.assertNonNullable)(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];(0,R.assertNonNullable)(c),r=c.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];(0,R.assertNonNullable)(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];(0,R.assertNonNullable)(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];(0,R.assertNonNullable)(c),r=Ee(c.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:R.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,R.assertNever)(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:r,i);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return(0,R.isNonNullable)(o)&&(n.metadata.title=o),(0,R.isNonNullable)(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((i,s)=>{this.loadMediaTimeoutSubscription.add((0,R.timeout)(zf).subscribe(()=>s(`timeout(${zf})`)))});(0,Kf.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},i=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${i}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:R.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Nu=U(nt(),1);var Au=require("@vkontakte/videoplayer-shared/es2018");var Xf=require("@vkontakte/videoplayer-shared/es2018"),Jf=a=>{try{a.pause(),a.playbackRate=0,(0,Xf.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var Qs=require("@vkontakte/videoplayer-shared/es2018"),xu=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)}},Pu=window.WeakMap?new WeakMap:new xu,wu=window.WeakMap?new WeakMap:new Map,SA=(a,e=20)=>{let t=0;return(0,Qs.fromEvent)(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Me=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let r=a.querySelector("video"),i=!!r;r?(0,Au.clearVideoElement)(r):(r=document.createElement("video"),a.appendChild(r)),Pu.set(r,i);let s=new Qs.Subscription;return s.add(SA(r,e)),wu.set(r,s),r.setAttribute("crossorigin","anonymous"),r.setAttribute("playsinline","playsinline"),t&&r.setAttribute("x-yandex-pip","false"),r.controls=!1,r.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),r},De=a=>{let e=wu.get(a);e==null||e.unsubscribe(),wu.delete(a);let t=Pu.get(a);Pu.delete(a),t?(0,Au.clearVideoElement)(a):Jf(a)};var ku=U(ei(),1),$=require("@vkontakte/videoplayer-shared/es2018");var Wt=require("@vkontakte/videoplayer-shared/es2018"),Gs=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=(0,Wt.isNullable)(i),l=new Wt.Subscription;return i&&l.add(i.subscribe(c=>{let d=a.getState();r(c,d)&&a.setState(c)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},bt=(a,e,t)=>Gs(e,()=>a.loop,r=>{(0,Wt.isNonNullable)(r)&&(a.loop=r)},{onError:t}),Ce=(a,e,t,r)=>Gs(e,()=>({muted:a.muted,volume:a.volume}),i=>{(0,Wt.isNonNullable)(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),Ye=(a,e,t,r)=>Gs(e,()=>a.playbackRate,i=>{(0,Wt.isNonNullable)(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Yt=Gs;var PA=a=>["__",a.language,a.label].join("|"),wA=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},Lu=class a{constructor(e){this.available$=new $.Subject;this.current$=new $.ValueSubject(void 0);this.error$=new $.Subject;this.subscription=new $.Subscription;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:$.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(Yt(t.internalTextTracks,()=>(0,ku.default)(this.internalTracks),s=>{(0,$.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,$.isNonNullable)(s)&&(0,$.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,$.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Yt(t.externalTextTracks,()=>(0,ku.default)(this.externalTracks),s=>{(0,$.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,$.isNonNullable)(s)&&(0,$.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,$.map)(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Yt(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:i})),this.subscription.add(Yt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,$.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,$.fromEvent)(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add((0,$.merge)((0,$.fromEvent)(e,"addtrack"),(0,$.fromEvent)(e,"removetrack"),(0,$.observableFrom)(["init"])).pipe((0,$.map)(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),(0,$.filterChanged)((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add((0,$.merge)((0,$.fromEvent)(e,"change"),(0,$.observableFrom)(["init"])).pipe((0,$.map)(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),(0,$.map)(r=>r&&this.htmlTextTrackToITextTrack(r).id),(0,$.filterChanged)()).subscribe(this.current$));let t=r=>{var i,s;return this.applyCueSettings((s=(i=r.target)==null?void 0:i.activeCues)!=null?s:null)};this.subscription.add((0,$.fromEvent)(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,p,h;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add((0,$.fromEvent)(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;(0,$.isNonNullable)(t.align)&&(i.align=t.align),(0,$.isNonNullable)(t.position)&&(i.position=t.position),(0,$.isNonNullable)(t.size)&&(i.size=t.size),(0,$.isNonNullable)(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,$.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c,d;let{language:t,label:r}=e,i=e.id?e.id:PA(e),s=this.externalTracks.has(i),n=(l=s?(o=this.externalTracks.get(i))==null?void 0:o.isAuto:(u=this.internalTracks.get(i))==null?void 0:u.isAuto)!=null?l:i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(c=this.externalTracks.get(i))==null?void 0:c.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(d=this.internalTracks.get(i))==null?void 0:d.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){(0,$.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,$.isNullable)(e)||!wA(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,$.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,$.assertNonNullable)(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},ze=Lu;var wt=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 sb=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},Ru=a=>{let e=sb(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},nb=a=>{let e=sb(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var M=require("@vkontakte/videoplayer-shared/es2018");var AA=3,ob=(a,e,t=AA)=>{let r=0,i=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(r=n,i=o,!t)return{from:r,to:i};for(let u=s-1;u>=0;u--)a.end(u)+t>=r&&(r=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=i&&(i=a.end(u))}}return{from:r,to:i}};var Ve=a=>{let e=x=>(0,M.fromEvent)(a,x).pipe((0,M.mapTo)(void 0)),r=(0,M.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(x=>(0,M.fromEvent)(a,x))).pipe((0,M.map)(x=>x.type==="ended"?a.readyState<2:a.readyState<3),(0,M.filterChanged)()),i=(0,M.merge)((0,M.fromEvent)(a,"progress"),(0,M.fromEvent)(a,"timeupdate")).pipe((0,M.map)(()=>ob(a.buffered,a.currentTime))),s=M.clientChecker.isSafari?(0,M.combine)({play:e("play").pipe((0,M.once)()),playing:e("playing")}).pipe((0,M.mapTo)(void 0)):e("playing"),n=(0,M.fromEvent)(a,"volumechange").pipe((0,M.map)(()=>({muted:a.muted,volume:a.volume}))),o=(0,M.fromEvent)(a,"ratechange").pipe((0,M.map)(()=>a.playbackRate)),u=(0,M.fromEvent)(a,"error").pipe((0,M.filter)(()=>!!(a.error||a.played.length)),(0,M.map)(()=>{var k;let x=a.error;return{id:x?`MediaError#${x.code}`:"HtmlVideoError",category:M.ErrorCategory.VIDEO_PIPELINE,message:x?x.message:"Error event from HTML video element",thrown:(k=a.error)!=null?k:void 0}})),l=(0,M.fromEvent)(a,"timeupdate").pipe((0,M.map)(()=>a.currentTime)),c=new M.Subject,d=.3,p;l.subscribe(x=>{a.loop&&(0,M.isNonNullable)(p)&&(0,M.isNonNullable)(x)&&p>=a.duration-d&&x<=d&&c.next(p),p=x});let h=e("pause").pipe((0,M.filter)(()=>!a.error&&p!==a.duration)),f=(0,M.fromEvent)(a,"enterpictureinpicture"),g=(0,M.fromEvent)(a,"leavepictureinpicture"),S=new M.ValueSubject(nb(a));f.subscribe(()=>S.next(!0)),g.subscribe(()=>S.next(!1));let I=new M.ValueSubject(Ru(a));return(0,M.fromEvent)(a,"fullscreenchange").pipe((0,M.map)(()=>Ru(a))).subscribe(I),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:(0,M.fromEvent)(a,"durationchange").pipe((0,M.map)(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:I,enterPip$:f,leavePip$:g}};var At=require("@vkontakte/videoplayer-shared/es2018"),zt=a=>{switch(a){case"mobile":return At.VideoQuality.Q_144P;case"lowest":return At.VideoQuality.Q_240P;case"low":return At.VideoQuality.Q_360P;case"sd":case"medium":return At.VideoQuality.Q_480P;case"hd":case"high":return At.VideoQuality.Q_720P;case"fullhd":case"full":return At.VideoQuality.Q_1080P;case"quadhd":case"quad":return At.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return At.VideoQuality.Q_2160P}};var Xt=U(Kt(),1),Sb=U(nt(),1),Ws=U(jr(),1),B=require("@vkontakte/videoplayer-shared/es2018");var $u=!1,kt={},mb=a=>{$u=a},fb=()=>{kt={}},bb=a=>{a(kt)},Qi=(a,e)=>{var t;$u&&(kt.meta=(t=kt.meta)!=null?t:{},kt.meta[a]=e)},Le=class{constructor(e){this.name=e}next(e){var r,i;if(!$u)return;kt.series=(r=kt.series)!=null?r:{};let t=(i=kt.series[this.name])!=null?i:[];t.push([Date.now(),e]),kt.series[this.name]=t}};var fe=require("@vkontakte/videoplayer-shared/es2018");function Mu({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function Du({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!!a&&Mu({limits:a,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}function Gi({limits:a,highestAvailableQuality:e,lowestAvailableQuality:t}){return(0,fe.isNullable)(a)||(0,fe.isNonNullable)(a.min)&&(0,fe.isNonNullable)(a.max)&&(0,fe.isLower)(a.max,a.min)||(0,fe.isNonNullable)(a.min)&&e&&(0,fe.isHigher)(a.min,e)||(0,fe.isNonNullable)(a.max)&&t&&(0,fe.isLower)(a.max,t)}function gb({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return Gi({limits:{max:a!=null&&a.max?(0,fe.videoHeightToQuality)(a.max):void 0,min:a!=null&&a.min?(0,fe.videoHeightToQuality)(a.min):void 0},highestAvailableQuality:e?(0,fe.videoHeightToQuality)(e):void 0,lowestAvailableQuality:t?(0,fe.videoHeightToQuality)(t):void 0})}var BA=new Le("best_bitrate"),yb=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var Cu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Wi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,B.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Tb='Assertion "ABR Tracks is empty array" failed',Ys=(a,e,t,r)=>{var u;let i=[...e].sort(Cu(1)),s=[...t].sort(Cu(1)),n=s.filter(l=>(0,B.isNonNullable)(l.bitrate)&&(0,B.isNonNullable)(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Xt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Xt.default)(s,-1);return o&&(0,Sb.default)(n,o)?o:n.length?(0,Xt.default)(n,-1):(0,Xt.default)(s,0)},vb=a=>"quality"in a,Ib=(a,e,t,r)=>{var n;let i=(0,B.isNonNullable)((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&(0,B.isNonNullable)(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&(0,B.now)()-r.history[t.id]<=i&&(!r.last||t.id!==r.last.id);if(t!=null&&t.id&&r&&!s&&r.recordSelection(t),s&&(r!=null&&r.last)){let o=r.last;r==null||r.recordSwitch(o);let u=vb(o)?"video":"audio",l=vb(o)?o.quality:o.bitrate;return e({message:`
|
|
6
|
+
"use strict";var _S=Object.create;var os=Object.defineProperty;var NS=Object.getOwnPropertyDescriptor;var FS=Object.getOwnPropertyNames;var qS=Object.getPrototypeOf,US=Object.prototype.hasOwnProperty;var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),HS=(a,e)=>{for(var t in e)os(a,t,{get:e[t],enumerable:!0})},lc=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of FS(e))!US.call(a,i)&&i!==t&&os(a,i,{get:()=>e[i],enumerable:!(r=NS(e,i))||r.enumerable});return a};var U=(a,e,t)=>(t=a!=null?_S(qS(a)):{},lc(e||!a||!a.__esModule?os(t,"default",{value:a,enumerable:!0}):t,a)),jS=a=>lc(os({},"__esModule",{value:!0}),a);var he=b((Mn,cc)=>{"use strict";var Ti=function(a){return a&&a.Math===Math&&a};cc.exports=Ti(typeof globalThis=="object"&&globalThis)||Ti(typeof window=="object"&&window)||Ti(typeof self=="object"&&self)||Ti(typeof global=="object"&&global)||Ti(typeof Mn=="object"&&Mn)||function(){return this}()||Function("return this")()});var Ie=b((IR,dc)=>{"use strict";dc.exports=function(a){try{return!!a()}catch(e){return!0}}});var Ii=b((ER,pc)=>{"use strict";var QS=Ie();pc.exports=!QS(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Dn=b((xR,bc)=>{"use strict";var GS=Ii(),fc=Function.prototype,hc=fc.apply,mc=fc.call;bc.exports=typeof Reflect=="object"&&Reflect.apply||(GS?mc.bind(hc):function(){return mc.apply(hc,arguments)})});var ve=b((PR,Sc)=>{"use strict";var gc=Ii(),vc=Function.prototype,Cn=vc.call,WS=gc&&vc.bind.bind(Cn,Cn);Sc.exports=gc?WS:function(a){return function(){return Cn.apply(a,arguments)}}});var lr=b((wR,Tc)=>{"use strict";var yc=ve(),YS=yc({}.toString),zS=yc("".slice);Tc.exports=function(a){return zS(YS(a),8,-1)}});var Vn=b((AR,Ic)=>{"use strict";var KS=lr(),XS=ve();Ic.exports=function(a){if(KS(a)==="Function")return XS(a)}});var de=b((kR,Ec)=>{"use strict";var Bn=typeof document=="object"&&document.all;Ec.exports=typeof Bn=="undefined"&&Bn!==void 0?function(a){return typeof a=="function"||a===Bn}:function(a){return typeof a=="function"}});var Ue=b((LR,xc)=>{"use strict";var JS=Ie();xc.exports=!JS(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var He=b((RR,Pc)=>{"use strict";var ZS=Ii(),cs=Function.prototype.call;Pc.exports=ZS?cs.bind(cs):function(){return cs.apply(cs,arguments)}});var On=b(kc=>{"use strict";var wc={}.propertyIsEnumerable,Ac=Object.getOwnPropertyDescriptor,ey=Ac&&!wc.call({1:2},1);kc.f=ey?function(e){var t=Ac(this,e);return!!t&&t.enumerable}:wc});var Ei=b((MR,Lc)=>{"use strict";Lc.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var $c=b((DR,Rc)=>{"use strict";var ty=ve(),ry=Ie(),iy=lr(),_n=Object,ay=ty("".split);Rc.exports=ry(function(){return!_n("z").propertyIsEnumerable(0)})?function(a){return iy(a)==="String"?ay(a,""):_n(a)}:_n});var Vr=b((CR,Mc)=>{"use strict";Mc.exports=function(a){return a==null}});var jt=b((VR,Dc)=>{"use strict";var sy=Vr(),ny=TypeError;Dc.exports=function(a){if(sy(a))throw new ny("Can't call method on "+a);return a}});var cr=b((BR,Cc)=>{"use strict";var oy=$c(),uy=jt();Cc.exports=function(a){return oy(uy(a))}});var je=b((OR,Vc)=>{"use strict";var ly=de();Vc.exports=function(a){return typeof a=="object"?a!==null:ly(a)}});var Br=b((_R,Bc)=>{"use strict";Bc.exports={}});var xt=b((NR,_c)=>{"use strict";var Nn=Br(),Fn=he(),cy=de(),Oc=function(a){return cy(a)?a:void 0};_c.exports=function(a,e){return arguments.length<2?Oc(Nn[a])||Oc(Fn[a]):Nn[a]&&Nn[a][e]||Fn[a]&&Fn[a][e]}});var xi=b((FR,Nc)=>{"use strict";var dy=ve();Nc.exports=dy({}.isPrototypeOf)});var dr=b((qR,Uc)=>{"use strict";var py=he(),Fc=py.navigator,qc=Fc&&Fc.userAgent;Uc.exports=qc?String(qc):""});var Un=b((UR,Yc)=>{"use strict";var Wc=he(),qn=dr(),Hc=Wc.process,jc=Wc.Deno,Qc=Hc&&Hc.versions||jc&&jc.version,Gc=Qc&&Qc.v8,at,ds;Gc&&(at=Gc.split("."),ds=at[0]>0&&at[0]<4?1:+(at[0]+at[1]));!ds&&qn&&(at=qn.match(/Edge\/(\d+)/),(!at||at[1]>=74)&&(at=qn.match(/Chrome\/(\d+)/),at&&(ds=+at[1])));Yc.exports=ds});var Hn=b((HR,Kc)=>{"use strict";var zc=Un(),hy=Ie(),my=he(),fy=my.String;Kc.exports=!!Object.getOwnPropertySymbols&&!hy(function(){var a=Symbol("symbol detection");return!fy(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&zc&&zc<41})});var jn=b((jR,Xc)=>{"use strict";var by=Hn();Xc.exports=by&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Qn=b((QR,Jc)=>{"use strict";var gy=xt(),vy=de(),Sy=xi(),yy=jn(),Ty=Object;Jc.exports=yy?function(a){return typeof a=="symbol"}:function(a){var e=gy("Symbol");return vy(e)&&Sy(e.prototype,Ty(a))}});var Pi=b((GR,Zc)=>{"use strict";var Iy=String;Zc.exports=function(a){try{return Iy(a)}catch(e){return"Object"}}});var mt=b((WR,ed)=>{"use strict";var Ey=de(),xy=Pi(),Py=TypeError;ed.exports=function(a){if(Ey(a))return a;throw new Py(xy(a)+" is not a function")}});var wi=b((YR,td)=>{"use strict";var wy=mt(),Ay=Vr();td.exports=function(a,e){var t=a[e];return Ay(t)?void 0:wy(t)}});var id=b((zR,rd)=>{"use strict";var Gn=He(),Wn=de(),Yn=je(),ky=TypeError;rd.exports=function(a,e){var t,r;if(e==="string"&&Wn(t=a.toString)&&!Yn(r=Gn(t,a))||Wn(t=a.valueOf)&&!Yn(r=Gn(t,a))||e!=="string"&&Wn(t=a.toString)&&!Yn(r=Gn(t,a)))return r;throw new ky("Can't convert object to primitive value")}});var st=b((KR,ad)=>{"use strict";ad.exports=!0});var od=b((XR,nd)=>{"use strict";var sd=he(),Ly=Object.defineProperty;nd.exports=function(a,e){try{Ly(sd,a,{value:e,configurable:!0,writable:!0})}catch(t){sd[a]=e}return e}});var Ai=b((JR,cd)=>{"use strict";var Ry=st(),$y=he(),My=od(),ud="__core-js_shared__",ld=cd.exports=$y[ud]||My(ud,{});(ld.versions||(ld.versions=[])).push({version:"3.38.0",mode:Ry?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var zn=b((ZR,pd)=>{"use strict";var dd=Ai();pd.exports=function(a,e){return dd[a]||(dd[a]=e||{})}});var Or=b((e$,hd)=>{"use strict";var Dy=jt(),Cy=Object;hd.exports=function(a){return Cy(Dy(a))}});var nt=b((t$,md)=>{"use strict";var Vy=ve(),By=Or(),Oy=Vy({}.hasOwnProperty);md.exports=Object.hasOwn||function(e,t){return Oy(By(e),t)}});var Kn=b((r$,fd)=>{"use strict";var _y=ve(),Ny=0,Fy=Math.random(),qy=_y(1 .toString);fd.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+qy(++Ny+Fy,36)}});var Ee=b((i$,gd)=>{"use strict";var Uy=he(),Hy=zn(),bd=nt(),jy=Kn(),Qy=Hn(),Gy=jn(),_r=Uy.Symbol,Xn=Hy("wks"),Wy=Gy?_r.for||_r:_r&&_r.withoutSetter||jy;gd.exports=function(a){return bd(Xn,a)||(Xn[a]=Qy&&bd(_r,a)?_r[a]:Wy("Symbol."+a)),Xn[a]}});var Td=b((a$,yd)=>{"use strict";var Yy=He(),vd=je(),Sd=Qn(),zy=wi(),Ky=id(),Xy=Ee(),Jy=TypeError,Zy=Xy("toPrimitive");yd.exports=function(a,e){if(!vd(a)||Sd(a))return a;var t=zy(a,Zy),r;if(t){if(e===void 0&&(e="default"),r=Yy(t,a,e),!vd(r)||Sd(r))return r;throw new Jy("Can't convert object to primitive value")}return e===void 0&&(e="number"),Ky(a,e)}});var Jn=b((s$,Id)=>{"use strict";var eT=Td(),tT=Qn();Id.exports=function(a){var e=eT(a,"string");return tT(e)?e:e+""}});var ps=b((n$,xd)=>{"use strict";var rT=he(),Ed=je(),Zn=rT.document,iT=Ed(Zn)&&Ed(Zn.createElement);xd.exports=function(a){return iT?Zn.createElement(a):{}}});var eo=b((o$,Pd)=>{"use strict";var aT=Ue(),sT=Ie(),nT=ps();Pd.exports=!aT&&!sT(function(){return Object.defineProperty(nT("div"),"a",{get:function(){return 7}}).a!==7})});var kd=b(Ad=>{"use strict";var oT=Ue(),uT=He(),lT=On(),cT=Ei(),dT=cr(),pT=Jn(),hT=nt(),mT=eo(),wd=Object.getOwnPropertyDescriptor;Ad.f=oT?wd:function(e,t){if(e=dT(e),t=pT(t),mT)try{return wd(e,t)}catch(r){}if(hT(e,t))return cT(!uT(lT.f,e,t),e[t])}});var to=b((l$,Ld)=>{"use strict";var fT=Ie(),bT=de(),gT=/#|\.prototype\./,ki=function(a,e){var t=ST[vT(a)];return t===TT?!0:t===yT?!1:bT(e)?fT(e):!!e},vT=ki.normalize=function(a){return String(a).replace(gT,".").toLowerCase()},ST=ki.data={},yT=ki.NATIVE="N",TT=ki.POLYFILL="P";Ld.exports=ki});var Nr=b((c$,$d)=>{"use strict";var Rd=Vn(),IT=mt(),ET=Ii(),xT=Rd(Rd.bind);$d.exports=function(a,e){return IT(a),e===void 0?a:ET?xT(a,e):function(){return a.apply(e,arguments)}}});var ro=b((d$,Md)=>{"use strict";var PT=Ue(),wT=Ie();Md.exports=PT&&wT(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var ft=b((p$,Dd)=>{"use strict";var AT=je(),kT=String,LT=TypeError;Dd.exports=function(a){if(AT(a))return a;throw new LT(kT(a)+" is not an object")}});var pr=b(Vd=>{"use strict";var RT=Ue(),$T=eo(),MT=ro(),hs=ft(),Cd=Jn(),DT=TypeError,io=Object.defineProperty,CT=Object.getOwnPropertyDescriptor,ao="enumerable",so="configurable",no="writable";Vd.f=RT?MT?function(e,t,r){if(hs(e),t=Cd(t),hs(r),typeof e=="function"&&t==="prototype"&&"value"in r&&no in r&&!r[no]){var i=CT(e,t);i&&i[no]&&(e[t]=r.value,r={configurable:so in r?r[so]:i[so],enumerable:ao in r?r[ao]:i[ao],writable:!1})}return io(e,t,r)}:io:function(e,t,r){if(hs(e),t=Cd(t),hs(r),$T)try{return io(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new DT("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Fr=b((m$,Bd)=>{"use strict";var VT=Ue(),BT=pr(),OT=Ei();Bd.exports=VT?function(a,e,t){return BT.f(a,e,OT(1,t))}:function(a,e,t){return a[e]=t,a}});var fe=b((f$,_d)=>{"use strict";var Li=he(),_T=Dn(),NT=Vn(),FT=de(),qT=kd().f,UT=to(),qr=Br(),HT=Nr(),Ur=Fr(),Od=nt();Ai();var jT=function(a){var e=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,r)}return new a(t,r,i)}return _T(a,this,arguments)};return e.prototype=a.prototype,e};_d.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?Li:i?Li[t]:Li[t]&&Li[t].prototype,o=r?qr:qr[t]||Ur(qr,t,{})[t],u=o.prototype,l,c,d,p,h,f,g,S,I;for(p in e)l=UT(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&Od(n,p),f=o[p],c&&(a.dontCallGetSet?(I=qT(n,p),g=I&&I.value):g=n[p]),h=c&&g?g:e[p],!(!l&&!s&&typeof f==typeof h)&&(a.bind&&c?S=HT(h,Li):a.wrap&&c?S=jT(h):s&&FT(h)?S=NT(h):S=h,(a.sham||h&&h.sham||f&&f.sham)&&Ur(S,"sham",!0),Ur(o,p,S),s&&(d=t+"Prototype",Od(qr,d)||Ur(qr,d,{}),Ur(qr[d],p,h),a.real&&u&&(l||!u[p])&&Ur(u,p,h)))}});var Fd=b((b$,Nd)=>{"use strict";var QT=Math.ceil,GT=Math.floor;Nd.exports=Math.trunc||function(e){var t=+e;return(t>0?GT:QT)(t)}});var Ri=b((g$,qd)=>{"use strict";var WT=Fd();qd.exports=function(a){var e=+a;return e!==e||e===0?0:WT(e)}});var Hd=b((v$,Ud)=>{"use strict";var YT=Ri(),zT=Math.max,KT=Math.min;Ud.exports=function(a,e){var t=YT(a);return t<0?zT(t+e,0):KT(t,e)}});var oo=b((S$,jd)=>{"use strict";var XT=Ri(),JT=Math.min;jd.exports=function(a){var e=XT(a);return e>0?JT(e,9007199254740991):0}});var Hr=b((y$,Qd)=>{"use strict";var ZT=oo();Qd.exports=function(a){return ZT(a.length)}});var uo=b((T$,Wd)=>{"use strict";var eI=cr(),tI=Hd(),rI=Hr(),Gd=function(a){return function(e,t,r){var i=eI(e),s=rI(i);if(s===0)return!a&&-1;var n=tI(r,s),o;if(a&&t!==t){for(;s>n;)if(o=i[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in i)&&i[n]===t)return a||n||0;return!a&&-1}};Wd.exports={includes:Gd(!0),indexOf:Gd(!1)}});var $i=b((I$,Yd)=>{"use strict";Yd.exports=function(){}});var zd=b(()=>{"use strict";var iI=fe(),aI=uo().includes,sI=Ie(),nI=$i(),oI=sI(function(){return!Array(1).includes()});iI({target:"Array",proto:!0,forced:oI},{includes:function(e){return aI(this,e,arguments.length>1?arguments[1]:void 0)}});nI("includes")});var Qt=b((P$,Kd)=>{"use strict";var uI=xt();Kd.exports=uI});var Jd=b((w$,Xd)=>{"use strict";zd();var lI=Qt();Xd.exports=lI("Array","includes")});var ep=b((A$,Zd)=>{"use strict";var cI=Jd();Zd.exports=cI});var ot=b((k$,tp)=>{"use strict";var dI=ep();tp.exports=dI});var fs=b((N$,ap)=>{"use strict";var hI=zn(),mI=Kn(),ip=hI("keys");ap.exports=function(a){return ip[a]||(ip[a]=mI(a))}});var np=b((F$,sp)=>{"use strict";var fI=Ie();sp.exports=!fI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var bs=b((q$,up)=>{"use strict";var bI=nt(),gI=de(),vI=Or(),SI=fs(),yI=np(),op=SI("IE_PROTO"),lo=Object,TI=lo.prototype;up.exports=yI?lo.getPrototypeOf:function(a){var e=vI(a);if(bI(e,op))return e[op];var t=e.constructor;return gI(t)&&e instanceof t?t.prototype:e instanceof lo?TI:null}});var gs=b((U$,lp)=>{"use strict";lp.exports={}});var pp=b((H$,dp)=>{"use strict";var II=ve(),co=nt(),EI=cr(),xI=uo().indexOf,PI=gs(),cp=II([].push);dp.exports=function(a,e){var t=EI(a),r=0,i=[],s;for(s in t)!co(PI,s)&&co(t,s)&&cp(i,s);for(;e.length>r;)co(t,s=e[r++])&&(~xI(i,s)||cp(i,s));return i}});var po=b((j$,hp)=>{"use strict";hp.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var ho=b((Q$,mp)=>{"use strict";var wI=pp(),AI=po();mp.exports=Object.keys||function(e){return wI(e,AI)}});var mo=b((G$,Sp)=>{"use strict";var bp=Ue(),kI=Ie(),gp=ve(),LI=bs(),RI=ho(),$I=cr(),MI=On().f,vp=gp(MI),DI=gp([].push),CI=bp&&kI(function(){var a=Object.create(null);return a[2]=2,!vp(a,2)}),fp=function(a){return function(e){for(var t=$I(e),r=RI(t),i=CI&&LI(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!bp||(i?u in t:vp(t,u)))&&DI(o,a?[u,t[u]]:t[u]);return o}};Sp.exports={entries:fp(!0),values:fp(!1)}});var yp=b(()=>{"use strict";var VI=fe(),BI=mo().entries;VI({target:"Object",stat:!0},{entries:function(e){return BI(e)}})});var Ip=b((z$,Tp)=>{"use strict";yp();var OI=Br();Tp.exports=OI.Object.entries});var xp=b((K$,Ep)=>{"use strict";var _I=Ip();Ep.exports=_I});var jr=b((X$,Pp)=>{"use strict";var NI=xp();Pp.exports=NI});var hr=b((J$,wp)=>{"use strict";wp.exports={}});var Lp=b((Z$,kp)=>{"use strict";var FI=he(),qI=de(),Ap=FI.WeakMap;kp.exports=qI(Ap)&&/native code/.test(String(Ap))});var vo=b((eM,Mp)=>{"use strict";var UI=Lp(),$p=he(),HI=je(),jI=Fr(),fo=nt(),bo=Ai(),QI=fs(),GI=gs(),Rp="Object already initialized",go=$p.TypeError,WI=$p.WeakMap,vs,Mi,Ss,YI=function(a){return Ss(a)?Mi(a):vs(a,{})},zI=function(a){return function(e){var t;if(!HI(e)||(t=Mi(e)).type!==a)throw new go("Incompatible receiver, "+a+" required");return t}};UI||bo.state?(ut=bo.state||(bo.state=new WI),ut.get=ut.get,ut.has=ut.has,ut.set=ut.set,vs=function(a,e){if(ut.has(a))throw new go(Rp);return e.facade=a,ut.set(a,e),e},Mi=function(a){return ut.get(a)||{}},Ss=function(a){return ut.has(a)}):(mr=QI("state"),GI[mr]=!0,vs=function(a,e){if(fo(a,mr))throw new go(Rp);return e.facade=a,jI(a,mr,e),e},Mi=function(a){return fo(a,mr)?a[mr]:{}},Ss=function(a){return fo(a,mr)});var ut,mr;Mp.exports={set:vs,get:Mi,has:Ss,enforce:YI,getterFor:zI}});var To=b((tM,Cp)=>{"use strict";var So=Ue(),KI=nt(),Dp=Function.prototype,XI=So&&Object.getOwnPropertyDescriptor,yo=KI(Dp,"name"),JI=yo&&function(){}.name==="something",ZI=yo&&(!So||So&&XI(Dp,"name").configurable);Cp.exports={EXISTS:yo,PROPER:JI,CONFIGURABLE:ZI}});var Bp=b(Vp=>{"use strict";var eE=Ue(),tE=ro(),rE=pr(),iE=ft(),aE=cr(),sE=ho();Vp.f=eE&&!tE?Object.defineProperties:function(e,t){iE(e);for(var r=aE(t),i=sE(t),s=i.length,n=0,o;s>n;)rE.f(e,o=i[n++],r[o]);return e}});var Io=b((iM,Op)=>{"use strict";var nE=xt();Op.exports=nE("document","documentElement")});var wo=b((aM,jp)=>{"use strict";var oE=ft(),uE=Bp(),_p=po(),lE=gs(),cE=Io(),dE=ps(),pE=fs(),Np=">",Fp="<",xo="prototype",Po="script",Up=pE("IE_PROTO"),Eo=function(){},Hp=function(a){return Fp+Po+Np+a+Fp+"/"+Po+Np},qp=function(a){a.write(Hp("")),a.close();var e=a.parentWindow.Object;return a=null,e},hE=function(){var a=dE("iframe"),e="java"+Po+":",t;return a.style.display="none",cE.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Hp("document.F=Object")),t.close(),t.F},ys,Ts=function(){try{ys=new ActiveXObject("htmlfile")}catch(e){}Ts=typeof document!="undefined"?document.domain&&ys?qp(ys):hE():qp(ys);for(var a=_p.length;a--;)delete Ts[xo][_p[a]];return Ts()};lE[Up]=!0;jp.exports=Object.create||function(e,t){var r;return e!==null?(Eo[xo]=oE(e),r=new Eo,Eo[xo]=null,r[Up]=e):r=Ts(),t===void 0?r:uE.f(r,t)}});var Qr=b((sM,Qp)=>{"use strict";var mE=Fr();Qp.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:mE(a,e,t),a}});var Ro=b((nM,Yp)=>{"use strict";var fE=Ie(),bE=de(),gE=je(),vE=wo(),Gp=bs(),SE=Qr(),yE=Ee(),TE=st(),Lo=yE("iterator"),Wp=!1,Pt,Ao,ko;[].keys&&(ko=[].keys(),"next"in ko?(Ao=Gp(Gp(ko)),Ao!==Object.prototype&&(Pt=Ao)):Wp=!0);var IE=!gE(Pt)||fE(function(){var a={};return Pt[Lo].call(a)!==a});IE?Pt={}:TE&&(Pt=vE(Pt));bE(Pt[Lo])||SE(Pt,Lo,function(){return this});Yp.exports={IteratorPrototype:Pt,BUGGY_SAFARI_ITERATORS:Wp}});var Is=b((oM,Kp)=>{"use strict";var EE=Ee(),xE=EE("toStringTag"),zp={};zp[xE]="z";Kp.exports=String(zp)==="[object z]"});var Di=b((uM,Xp)=>{"use strict";var PE=Is(),wE=de(),Es=lr(),AE=Ee(),kE=AE("toStringTag"),LE=Object,RE=Es(function(){return arguments}())==="Arguments",$E=function(a,e){try{return a[e]}catch(t){}};Xp.exports=PE?Es:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=$E(e=LE(a),kE))=="string"?t:RE?Es(e):(r=Es(e))==="Object"&&wE(e.callee)?"Arguments":r}});var Zp=b((lM,Jp)=>{"use strict";var ME=Is(),DE=Di();Jp.exports=ME?{}.toString:function(){return"[object "+DE(this)+"]"}});var Ci=b((cM,th)=>{"use strict";var CE=Is(),VE=pr().f,BE=Fr(),OE=nt(),_E=Zp(),NE=Ee(),eh=NE("toStringTag");th.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(OE(i,eh)||VE(i,eh,{configurable:!0,value:e}),r&&!CE&&BE(i,"toString",_E))}});var ih=b((dM,rh)=>{"use strict";var FE=Ro().IteratorPrototype,qE=wo(),UE=Ei(),HE=Ci(),jE=hr(),QE=function(){return this};rh.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=qE(FE,{next:UE(+!r,t)}),HE(a,i,!1,!0),jE[i]=QE,a}});var sh=b((pM,ah)=>{"use strict";var GE=ve(),WE=mt();ah.exports=function(a,e,t){try{return GE(WE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var oh=b((hM,nh)=>{"use strict";var YE=je();nh.exports=function(a){return YE(a)||a===null}});var lh=b((mM,uh)=>{"use strict";var zE=oh(),KE=String,XE=TypeError;uh.exports=function(a){if(zE(a))return a;throw new XE("Can't set "+KE(a)+" as a prototype")}});var $o=b((fM,ch)=>{"use strict";var JE=sh(),ZE=je(),ex=jt(),tx=lh();ch.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=JE(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return ex(i),tx(s),ZE(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var Th=b((bM,yh)=>{"use strict";var rx=fe(),ix=He(),xs=st(),vh=To(),ax=de(),sx=ih(),dh=bs(),ph=$o(),nx=Ci(),ox=Fr(),Mo=Qr(),ux=Ee(),hh=hr(),Sh=Ro(),lx=vh.PROPER,cx=vh.CONFIGURABLE,mh=Sh.IteratorPrototype,Ps=Sh.BUGGY_SAFARI_ITERATORS,Vi=ux("iterator"),fh="keys",Bi="values",bh="entries",gh=function(){return this};yh.exports=function(a,e,t,r,i,s,n){sx(t,e,r);var o=function(I){if(I===i&&p)return p;if(!Ps&&I&&I in c)return c[I];switch(I){case fh:return function(){return new t(this,I)};case Bi:return function(){return new t(this,I)};case bh:return function(){return new t(this,I)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[Vi]||c["@@iterator"]||i&&c[i],p=!Ps&&d||o(i),h=e==="Array"&&c.entries||d,f,g,S;if(h&&(f=dh(h.call(new a)),f!==Object.prototype&&f.next&&(!xs&&dh(f)!==mh&&(ph?ph(f,mh):ax(f[Vi])||Mo(f,Vi,gh)),nx(f,u,!0,!0),xs&&(hh[u]=gh))),lx&&i===Bi&&d&&d.name!==Bi&&(!xs&&cx?ox(c,"name",Bi):(l=!0,p=function(){return ix(d,this)})),i)if(g={values:o(Bi),keys:s?p:o(fh),entries:o(bh)},n)for(S in g)(Ps||l||!(S in c))&&Mo(c,S,g[S]);else rx({target:e,proto:!0,forced:Ps||l},g);return(!xs||n)&&c[Vi]!==p&&Mo(c,Vi,p,{name:i}),hh[e]=p,g}});var Eh=b((gM,Ih)=>{"use strict";Ih.exports=function(a,e){return{value:a,done:e}}});var Co=b((vM,kh)=>{"use strict";var dx=cr(),Do=$i(),xh=hr(),wh=vo(),px=pr().f,hx=Th(),ws=Eh(),mx=st(),fx=Ue(),Ah="Array Iterator",bx=wh.set,gx=wh.getterFor(Ah);kh.exports=hx(Array,"Array",function(a,e){bx(this,{type:Ah,target:dx(a),index:0,kind:e})},function(){var a=gx(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,ws(void 0,!0);switch(a.kind){case"keys":return ws(t,!1);case"values":return ws(e[t],!1)}return ws([t,e[t]],!1)},"values");var Ph=xh.Arguments=xh.Array;Do("keys");Do("values");Do("entries");if(!mx&&fx&&Ph.name!=="values")try{px(Ph,"name",{value:"values"})}catch(a){}});var Rh=b((SM,Lh)=>{"use strict";var vx=Ee(),Sx=hr(),yx=vx("iterator"),Tx=Array.prototype;Lh.exports=function(a){return a!==void 0&&(Sx.Array===a||Tx[yx]===a)}});var Vo=b((yM,Mh)=>{"use strict";var Ix=Di(),$h=wi(),Ex=Vr(),xx=hr(),Px=Ee(),wx=Px("iterator");Mh.exports=function(a){if(!Ex(a))return $h(a,wx)||$h(a,"@@iterator")||xx[Ix(a)]}});var Ch=b((TM,Dh)=>{"use strict";var Ax=He(),kx=mt(),Lx=ft(),Rx=Pi(),$x=Vo(),Mx=TypeError;Dh.exports=function(a,e){var t=arguments.length<2?$x(a):e;if(kx(t))return Lx(Ax(t,a));throw new Mx(Rx(a)+" is not iterable")}});var Oh=b((IM,Bh)=>{"use strict";var Dx=He(),Vh=ft(),Cx=wi();Bh.exports=function(a,e,t){var r,i;Vh(a);try{if(r=Cx(a,"return"),!r){if(e==="throw")throw t;return t}r=Dx(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Vh(r),t}});var ks=b((EM,qh)=>{"use strict";var Vx=Nr(),Bx=He(),Ox=ft(),_x=Pi(),Nx=Rh(),Fx=Hr(),_h=xi(),qx=Ch(),Ux=Vo(),Nh=Oh(),Hx=TypeError,As=function(a,e){this.stopped=a,this.result=e},Fh=As.prototype;qh.exports=function(a,e,t){var r=t&&t.that,i=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=Vx(e,r),l,c,d,p,h,f,g,S=function(x){return l&&Nh(l,"normal",x),new As(!0,x)},I=function(x){return i?(Ox(x),o?u(x[0],x[1],S):u(x[0],x[1])):o?u(x,S):u(x)};if(s)l=a.iterator;else if(n)l=a;else{if(c=Ux(a),!c)throw new Hx(_x(a)+" is not iterable");if(Nx(c)){for(d=0,p=Fx(a);p>d;d++)if(h=I(a[d]),h&&_h(Fh,h))return h;return new As(!1)}l=qx(a,c)}for(f=s?a.next:l.next;!(g=Bx(f,l)).done;){try{h=I(g.value)}catch(x){Nh(l,"throw",x)}if(typeof h=="object"&&h&&_h(Fh,h))return h}return new As(!1)}});var Hh=b((xM,Uh)=>{"use strict";var jx=Ue(),Qx=pr(),Gx=Ei();Uh.exports=function(a,e,t){jx?Qx.f(a,e,Gx(0,t)):a[e]=t}});var jh=b(()=>{"use strict";var Wx=fe(),Yx=ks(),zx=Hh();Wx({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Yx(e,function(r,i){zx(t,r,i)},{AS_ENTRIES:!0}),t}})});var Gh=b((AM,Qh)=>{"use strict";Co();jh();var Kx=Br();Qh.exports=Kx.Object.fromEntries});var Yh=b((kM,Wh)=>{"use strict";Wh.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 Kh=b(()=>{"use strict";Co();var Xx=Yh(),Jx=he(),Zx=Ci(),zh=hr();for(Ls in Xx)Zx(Jx[Ls],Ls),zh[Ls]=zh.Array;var Ls});var Jh=b(($M,Xh)=>{"use strict";var eP=Gh();Kh();Xh.exports=eP});var Bo=b((MM,Zh)=>{"use strict";var tP=Jh();Zh.exports=tP});var em=b(()=>{"use strict"});var Oo=b((VM,tm)=>{"use strict";var Oi=he(),rP=dr(),iP=lr(),Rs=function(a){return rP.slice(0,a.length)===a};tm.exports=function(){return Rs("Bun/")?"BUN":Rs("Cloudflare-Workers")?"CLOUDFLARE":Rs("Deno/")?"DENO":Rs("Node.js/")?"NODE":Oi.Bun&&typeof Bun.version=="string"?"BUN":Oi.Deno&&typeof Deno.version=="object"?"DENO":iP(Oi.process)==="process"?"NODE":Oi.window&&Oi.document?"BROWSER":"REST"}()});var $s=b((BM,rm)=>{"use strict";var aP=Oo();rm.exports=aP==="NODE"});var am=b((OM,im)=>{"use strict";var sP=pr();im.exports=function(a,e,t){return sP.f(a,e,t)}});var om=b((_M,nm)=>{"use strict";var nP=xt(),oP=am(),uP=Ee(),lP=Ue(),sm=uP("species");nm.exports=function(a){var e=nP(a);lP&&e&&!e[sm]&&oP(e,sm,{configurable:!0,get:function(){return this}})}});var lm=b((NM,um)=>{"use strict";var cP=xi(),dP=TypeError;um.exports=function(a,e){if(cP(e,a))return a;throw new dP("Incorrect invocation")}});var No=b((FM,cm)=>{"use strict";var pP=ve(),hP=de(),_o=Ai(),mP=pP(Function.toString);hP(_o.inspectSource)||(_o.inspectSource=function(a){return mP(a)});cm.exports=_o.inspectSource});var qo=b((qM,fm)=>{"use strict";var fP=ve(),bP=Ie(),dm=de(),gP=Di(),vP=xt(),SP=No(),pm=function(){},hm=vP("Reflect","construct"),Fo=/^\s*(?:class|function)\b/,yP=fP(Fo.exec),TP=!Fo.test(pm),_i=function(e){if(!dm(e))return!1;try{return hm(pm,[],e),!0}catch(t){return!1}},mm=function(e){if(!dm(e))return!1;switch(gP(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return TP||!!yP(Fo,SP(e))}catch(t){return!0}};mm.sham=!0;fm.exports=!hm||bP(function(){var a;return _i(_i.call)||!_i(Object)||!_i(function(){a=!0})||a})?mm:_i});var gm=b((UM,bm)=>{"use strict";var IP=qo(),EP=Pi(),xP=TypeError;bm.exports=function(a){if(IP(a))return a;throw new xP(EP(a)+" is not a constructor")}});var Uo=b((HM,Sm)=>{"use strict";var vm=ft(),PP=gm(),wP=Vr(),AP=Ee(),kP=AP("species");Sm.exports=function(a,e){var t=vm(a).constructor,r;return t===void 0||wP(r=vm(t)[kP])?e:PP(r)}});var Tm=b((jM,ym)=>{"use strict";var LP=ve();ym.exports=LP([].slice)});var Em=b((QM,Im)=>{"use strict";var RP=TypeError;Im.exports=function(a,e){if(a<e)throw new RP("Not enough arguments");return a}});var Ho=b((GM,xm)=>{"use strict";var $P=dr();xm.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test($P)});var Jo=b((WM,Dm)=>{"use strict";var Qe=he(),MP=Dn(),DP=Nr(),Pm=de(),CP=nt(),Mm=Ie(),wm=Io(),VP=Tm(),Am=ps(),BP=Em(),OP=Ho(),_P=$s(),zo=Qe.setImmediate,Ko=Qe.clearImmediate,NP=Qe.process,jo=Qe.Dispatch,FP=Qe.Function,km=Qe.MessageChannel,qP=Qe.String,Qo=0,Ni={},Lm="onreadystatechange",Fi,fr,Go,Wo;Mm(function(){Fi=Qe.location});var Xo=function(a){if(CP(Ni,a)){var e=Ni[a];delete Ni[a],e()}},Yo=function(a){return function(){Xo(a)}},Rm=function(a){Xo(a.data)},$m=function(a){Qe.postMessage(qP(a),Fi.protocol+"//"+Fi.host)};(!zo||!Ko)&&(zo=function(e){BP(arguments.length,1);var t=Pm(e)?e:FP(e),r=VP(arguments,1);return Ni[++Qo]=function(){MP(t,void 0,r)},fr(Qo),Qo},Ko=function(e){delete Ni[e]},_P?fr=function(a){NP.nextTick(Yo(a))}:jo&&jo.now?fr=function(a){jo.now(Yo(a))}:km&&!OP?(Go=new km,Wo=Go.port2,Go.port1.onmessage=Rm,fr=DP(Wo.postMessage,Wo)):Qe.addEventListener&&Pm(Qe.postMessage)&&!Qe.importScripts&&Fi&&Fi.protocol!=="file:"&&!Mm($m)?(fr=$m,Qe.addEventListener("message",Rm,!1)):Lm in Am("script")?fr=function(a){wm.appendChild(Am("script"))[Lm]=function(){wm.removeChild(this),Xo(a)}}:fr=function(a){setTimeout(Yo(a),0)});Dm.exports={set:zo,clear:Ko}});var Bm=b((YM,Vm)=>{"use strict";var Cm=he(),UP=Ue(),HP=Object.getOwnPropertyDescriptor;Vm.exports=function(a){if(!UP)return Cm[a];var e=HP(Cm,a);return e&&e.value}});var Zo=b((zM,_m)=>{"use strict";var Om=function(){this.head=null,this.tail=null};Om.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}}};_m.exports=Om});var Fm=b((KM,Nm)=>{"use strict";var jP=dr();Nm.exports=/ipad|iphone|ipod/i.test(jP)&&typeof Pebble!="undefined"});var Um=b((XM,qm)=>{"use strict";var QP=dr();qm.exports=/web0s(?!.*chrome)/i.test(QP)});var zm=b((JM,Ym)=>{"use strict";var Wr=he(),GP=Bm(),Hm=Nr(),eu=Jo().set,WP=Zo(),YP=Ho(),zP=Fm(),KP=Um(),tu=$s(),jm=Wr.MutationObserver||Wr.WebKitMutationObserver,Qm=Wr.document,Gm=Wr.process,Ms=Wr.Promise,au=GP("queueMicrotask"),Gr,ru,iu,Ds,Wm;au||(qi=new WP,Ui=function(){var a,e;for(tu&&(a=Gm.domain)&&a.exit();e=qi.get();)try{e()}catch(t){throw qi.head&&Gr(),t}a&&a.enter()},!YP&&!tu&&!KP&&jm&&Qm?(ru=!0,iu=Qm.createTextNode(""),new jm(Ui).observe(iu,{characterData:!0}),Gr=function(){iu.data=ru=!ru}):!zP&&Ms&&Ms.resolve?(Ds=Ms.resolve(void 0),Ds.constructor=Ms,Wm=Hm(Ds.then,Ds),Gr=function(){Wm(Ui)}):tu?Gr=function(){Gm.nextTick(Ui)}:(eu=Hm(eu,Wr),Gr=function(){eu(Ui)}),au=function(a){qi.head||Gr(),qi.add(a)});var qi,Ui;Ym.exports=au});var Xm=b((ZM,Km)=>{"use strict";Km.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Cs=b((eD,Jm)=>{"use strict";Jm.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var br=b((tD,Zm)=>{"use strict";var XP=he();Zm.exports=XP.Promise});var Yr=b((rD,af)=>{"use strict";var JP=he(),Hi=br(),ZP=de(),ew=to(),tw=No(),rw=Ee(),ef=Oo(),iw=st(),su=Un(),tf=Hi&&Hi.prototype,aw=rw("species"),nu=!1,rf=ZP(JP.PromiseRejectionEvent),sw=ew("Promise",function(){var a=tw(Hi),e=a!==String(Hi);if(!e&&su===66||iw&&!(tf.catch&&tf.finally))return!0;if(!su||su<51||!/native code/.test(a)){var t=new Hi(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[aw]=r,nu=t.then(function(){})instanceof r,!nu)return!0}return!e&&(ef==="BROWSER"||ef==="DENO")&&!rf});af.exports={CONSTRUCTOR:sw,REJECTION_EVENT:rf,SUBCLASSING:nu}});var zr=b((iD,nf)=>{"use strict";var sf=mt(),nw=TypeError,ow=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new nw("Bad Promise constructor");e=r,t=i}),this.resolve=sf(e),this.reject=sf(t)};nf.exports.f=function(a){return new ow(a)}});var Pf=b(()=>{"use strict";var uw=fe(),lw=st(),_s=$s(),Gt=he(),Zr=He(),of=Qr(),uf=$o(),cw=Ci(),dw=om(),pw=mt(),Os=de(),hw=je(),mw=lm(),fw=Uo(),hf=Jo().set,du=zm(),bw=Xm(),gw=Cs(),vw=Zo(),mf=vo(),Ns=br(),pu=Yr(),ff=zr(),Fs="Promise",bf=pu.CONSTRUCTOR,Sw=pu.REJECTION_EVENT,yw=pu.SUBCLASSING,ou=mf.getterFor(Fs),Tw=mf.set,Kr=Ns&&Ns.prototype,gr=Ns,Vs=Kr,gf=Gt.TypeError,uu=Gt.document,hu=Gt.process,lu=ff.f,Iw=lu,Ew=!!(uu&&uu.createEvent&&Gt.dispatchEvent),vf="unhandledrejection",xw="rejectionhandled",lf=0,Sf=1,Pw=2,mu=1,yf=2,Bs,cf,ww,df,Tf=function(a){var e;return hw(a)&&Os(e=a.then)?e:!1},If=function(a,e){var t=e.value,r=e.state===Sf,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===yf&&kw(e),e.rejection=mu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new gf("Promise-chain cycle")):(l=Tf(u))?Zr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Ef=function(a,e){a.notified||(a.notified=!0,du(function(){for(var t=a.reactions,r;r=t.get();)If(r,a);a.notified=!1,e&&!a.rejection&&Aw(a)}))},xf=function(a,e,t){var r,i;Ew?(r=uu.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Gt.dispatchEvent(r)):r={promise:e,reason:t},!Sw&&(i=Gt["on"+a])?i(r):a===vf&&bw("Unhandled promise rejection",t)},Aw=function(a){Zr(hf,Gt,function(){var e=a.facade,t=a.value,r=pf(a),i;if(r&&(i=gw(function(){_s?hu.emit("unhandledRejection",t,e):xf(vf,e,t)}),a.rejection=_s||pf(a)?yf:mu,i.error))throw i.value})},pf=function(a){return a.rejection!==mu&&!a.parent},kw=function(a){Zr(hf,Gt,function(){var e=a.facade;_s?hu.emit("rejectionHandled",e):xf(xw,e,a.value)})},Xr=function(a,e,t){return function(r){a(e,r,t)}},Jr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=Pw,Ef(a,!0))},cu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new gf("Promise can't be resolved itself");var r=Tf(e);r?du(function(){var i={done:!1};try{Zr(r,e,Xr(cu,i,a),Xr(Jr,i,a))}catch(s){Jr(i,s,a)}}):(a.value=e,a.state=Sf,Ef(a,!1))}catch(i){Jr({done:!1},i,a)}}};if(bf&&(gr=function(e){mw(this,Vs),pw(e),Zr(Bs,this);var t=ou(this);try{e(Xr(cu,t),Xr(Jr,t))}catch(r){Jr(t,r)}},Vs=gr.prototype,Bs=function(e){Tw(this,{type:Fs,done:!1,notified:!1,parent:!1,reactions:new vw,rejection:!1,state:lf,value:void 0})},Bs.prototype=of(Vs,"then",function(e,t){var r=ou(this),i=lu(fw(this,gr));return r.parent=!0,i.ok=Os(e)?e:!0,i.fail=Os(t)&&t,i.domain=_s?hu.domain:void 0,r.state===lf?r.reactions.add(i):du(function(){If(i,r)}),i.promise}),cf=function(){var a=new Bs,e=ou(a);this.promise=a,this.resolve=Xr(cu,e),this.reject=Xr(Jr,e)},ff.f=lu=function(a){return a===gr||a===ww?new cf(a):Iw(a)},!lw&&Os(Ns)&&Kr!==Object.prototype)){df=Kr.then,yw||of(Kr,"then",function(e,t){var r=this;return new gr(function(i,s){Zr(df,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Kr.constructor}catch(a){}uf&&uf(Kr,Vs)}uw({global:!0,constructor:!0,wrap:!0,forced:bf},{Promise:gr});cw(gr,Fs,!1,!0);dw(Fs)});var Rf=b((nD,Lf)=>{"use strict";var Lw=Ee(),Af=Lw("iterator"),kf=!1;try{wf=0,fu={next:function(){return{done:!!wf++}},return:function(){kf=!0}},fu[Af]=function(){return this},Array.from(fu,function(){throw 2})}catch(a){}var wf,fu;Lf.exports=function(a,e){try{if(!e&&!kf)return!1}catch(i){return!1}var t=!1;try{var r={};r[Af]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var bu=b((oD,$f)=>{"use strict";var Rw=br(),$w=Rf(),Mw=Yr().CONSTRUCTOR;$f.exports=Mw||!$w(function(a){Rw.all(a).then(void 0,function(){})})});var Mf=b(()=>{"use strict";var Dw=fe(),Cw=He(),Vw=mt(),Bw=zr(),Ow=Cs(),_w=ks(),Nw=bu();Dw({target:"Promise",stat:!0,forced:Nw},{all:function(e){var t=this,r=Bw.f(t),i=r.resolve,s=r.reject,n=Ow(function(){var o=Vw(t.resolve),u=[],l=0,c=1;_w(e,function(d){var p=l++,h=!1;c++,Cw(o,t,d).then(function(f){h||(h=!0,u[p]=f,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var Cf=b(()=>{"use strict";var Fw=fe(),qw=st(),Uw=Yr().CONSTRUCTOR,vu=br(),Hw=xt(),jw=de(),Qw=Qr(),Df=vu&&vu.prototype;Fw({target:"Promise",proto:!0,forced:Uw,real:!0},{catch:function(a){return this.then(void 0,a)}});!qw&&jw(vu)&&(gu=Hw("Promise").prototype.catch,Df.catch!==gu&&Qw(Df,"catch",gu,{unsafe:!0}));var gu});var Vf=b(()=>{"use strict";var Gw=fe(),Ww=He(),Yw=mt(),zw=zr(),Kw=Cs(),Xw=ks(),Jw=bu();Gw({target:"Promise",stat:!0,forced:Jw},{race:function(e){var t=this,r=zw.f(t),i=r.reject,s=Kw(function(){var n=Yw(t.resolve);Xw(e,function(o){Ww(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var Bf=b(()=>{"use strict";var Zw=fe(),eA=zr(),tA=Yr().CONSTRUCTOR;Zw({target:"Promise",stat:!0,forced:tA},{reject:function(e){var t=eA.f(this),r=t.reject;return r(e),t.promise}})});var Su=b((bD,Of)=>{"use strict";var rA=ft(),iA=je(),aA=zr();Of.exports=function(a,e){if(rA(a),iA(e)&&e.constructor===a)return e;var t=aA.f(a),r=t.resolve;return r(e),t.promise}});var Ff=b(()=>{"use strict";var sA=fe(),nA=xt(),_f=st(),oA=br(),Nf=Yr().CONSTRUCTOR,uA=Su(),lA=nA("Promise"),cA=_f&&!Nf;sA({target:"Promise",stat:!0,forced:_f||Nf},{resolve:function(e){return uA(cA&&this===lA?oA:this,e)}})});var qf=b(()=>{"use strict";Pf();Mf();Cf();Vf();Bf();Ff()});var Qf=b(()=>{"use strict";var dA=fe(),pA=st(),qs=br(),hA=Ie(),Hf=xt(),jf=de(),mA=Uo(),Uf=Su(),fA=Qr(),Tu=qs&&qs.prototype,bA=!!qs&&hA(function(){Tu.finally.call({then:function(){}},function(){})});dA({target:"Promise",proto:!0,real:!0,forced:bA},{finally:function(a){var e=mA(this,Hf("Promise")),t=jf(a);return this.then(t?function(r){return Uf(e,a()).then(function(){return r})}:a,t?function(r){return Uf(e,a()).then(function(){throw r})}:a)}});!pA&&jf(qs)&&(yu=Hf("Promise").prototype.finally,Tu.finally!==yu&&fA(Tu,"finally",yu,{unsafe:!0}));var yu});var Wf=b((ED,Gf)=>{"use strict";em();qf();Qf();var gA=Qt();Gf.exports=gA("Promise","finally")});var zf=b((xD,Yf)=>{"use strict";var vA=Wf();Yf.exports=vA});var Us=b((PD,Kf)=>{"use strict";var SA=zf();Kf.exports=SA});var ib=b(()=>{"use strict";var xA=fe(),PA=mo().values;xA({target:"Object",stat:!0},{values:function(e){return PA(e)}})});var sb=b((r0,ab)=>{"use strict";ib();var wA=Br();ab.exports=wA.Object.values});var ob=b((i0,nb)=>{"use strict";var AA=sb();nb.exports=AA});var ei=b((a0,ub)=>{"use strict";var kA=ob();ub.exports=kA});var pb=b(()=>{"use strict";var MA=fe(),DA=Or(),CA=Hr(),VA=Ri(),BA=$i();MA({target:"Array",proto:!0},{at:function(e){var t=DA(this),r=CA(t),i=VA(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});BA("at")});var mb=b((k0,hb)=>{"use strict";pb();var OA=Qt();hb.exports=OA("Array","at")});var bb=b((L0,fb)=>{"use strict";var _A=mb();fb.exports=_A});var Kt=b((R0,gb)=>{"use strict";var NA=bb();gb.exports=NA});var Fu=b((rV,Nb)=>{"use strict";var XA=lr();Nb.exports=Array.isArray||function(e){return XA(e)==="Array"}});var qb=b((iV,Fb)=>{"use strict";var JA=TypeError,ZA=9007199254740991;Fb.exports=function(a){if(a>ZA)throw JA("Maximum allowed index exceeded");return a}});var jb=b((aV,Hb)=>{"use strict";var ek=Fu(),tk=Hr(),rk=qb(),ik=Nr(),Ub=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,c=n?ik(n,o):!1,d,p;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&ek(d)?(p=tk(d),u=Ub(a,e,d,p,u,s-1)-1):(rk(u+1),a[u]=d),u++),l++;return u};Hb.exports=Ub});var Yb=b((sV,Wb)=>{"use strict";var Qb=Fu(),ak=qo(),sk=je(),nk=Ee(),ok=nk("species"),Gb=Array;Wb.exports=function(a){var e;return Qb(a)&&(e=a.constructor,ak(e)&&(e===Gb||Qb(e.prototype))?e=void 0:sk(e)&&(e=e[ok],e===null&&(e=void 0))),e===void 0?Gb:e}});var Kb=b((nV,zb)=>{"use strict";var uk=Yb();zb.exports=function(a,e){return new(uk(a))(e===0?0:e)}});var Xb=b(()=>{"use strict";var lk=fe(),ck=jb(),dk=mt(),pk=Or(),hk=Hr(),mk=Kb();lk({target:"Array",proto:!0},{flatMap:function(e){var t=pk(this),r=hk(t),i;return dk(e),i=mk(t,0),i.length=ck(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var Jb=b(()=>{"use strict";var fk=$i();fk("flatMap")});var eg=b((dV,Zb)=>{"use strict";Xb();Jb();var bk=Qt();Zb.exports=bk("Array","flatMap")});var rg=b((pV,tg)=>{"use strict";var gk=eg();tg.exports=gk});var qu=b((hV,ig)=>{"use strict";var vk=rg();ig.exports=vk});var ra=b((IV,Eg)=>{"use strict";var wk=Di(),Ak=String;Eg.exports=function(a){if(wk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return Ak(a)}});var Hu=b((EV,xg)=>{"use strict";xg.exports=`
|
|
7
|
+
\v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`});var Ag=b((xV,wg)=>{"use strict";var kk=ve(),Lk=jt(),Rk=ra(),Qu=Hu(),Pg=kk("".replace),$k=RegExp("^["+Qu+"]+"),Mk=RegExp("(^|[^"+Qu+"])["+Qu+"]+$"),ju=function(a){return function(e){var t=Rk(Lk(e));return a&1&&(t=Pg(t,$k,"")),a&2&&(t=Pg(t,Mk,"$1")),t}};wg.exports={start:ju(1),end:ju(2),trim:ju(3)}});var $g=b((PV,Rg)=>{"use strict";var Dk=To().PROPER,Ck=Ie(),kg=Hu(),Lg="\u200B\x85\u180E";Rg.exports=function(a){return Ck(function(){return!!kg[a]()||Lg[a]()!==Lg||Dk&&kg[a].name!==a})}});var Gu=b((wV,Mg)=>{"use strict";var Vk=Ag().start,Bk=$g();Mg.exports=Bk("trimStart")?function(){return Vk(this)}:"".trimStart});var Cg=b(()=>{"use strict";var Ok=fe(),Dg=Gu();Ok({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Dg},{trimLeft:Dg})});var Bg=b(()=>{"use strict";Cg();var _k=fe(),Vg=Gu();_k({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Vg},{trimStart:Vg})});var _g=b(($V,Og)=>{"use strict";Bg();var Nk=Qt();Og.exports=Nk("String","trimLeft")});var Fg=b((MV,Ng)=>{"use strict";var Fk=_g();Ng.exports=Fk});var Ug=b((DV,qg)=>{"use strict";var qk=Fg();qg.exports=qk});var rv=b(()=>{"use strict"});var iv=b(()=>{"use strict"});var sv=b((u_,av)=>{"use strict";var oL=je(),uL=lr(),lL=Ee(),cL=lL("match");av.exports=function(a){var e;return oL(a)&&((e=a[cL])!==void 0?!!e:uL(a)==="RegExp")}});var ov=b((l_,nv)=>{"use strict";var dL=ft();nv.exports=function(){var a=dL(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 cv=b((c_,lv)=>{"use strict";var pL=He(),hL=nt(),mL=xi(),fL=ov(),uv=RegExp.prototype;lv.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in uv)&&!hL(a,"flags")&&mL(uv,a)?pL(fL,a):e}});var pv=b((d_,dv)=>{"use strict";var Zu=ve(),bL=Or(),gL=Math.floor,Xu=Zu("".charAt),vL=Zu("".replace),Ju=Zu("".slice),SL=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,yL=/\$([$&'`]|\d{1,2})/g;dv.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=yL;return i!==void 0&&(i=bL(i),u=SL),vL(s,u,function(l,c){var d;switch(Xu(c,0)){case"$":return"$";case"&":return a;case"`":return Ju(e,0,t);case"'":return Ju(e,n);case"<":d=i[Ju(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=gL(p/10);return h===0?l:h<=o?r[h-1]===void 0?Xu(c,1):r[h-1]+Xu(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var fv=b(()=>{"use strict";var TL=fe(),IL=He(),tl=ve(),hv=jt(),EL=de(),xL=Vr(),PL=sv(),oi=ra(),wL=wi(),AL=cv(),kL=pv(),LL=Ee(),RL=st(),$L=LL("replace"),ML=TypeError,el=tl("".indexOf),DL=tl("".replace),mv=tl("".slice),CL=Math.max;TL({target:"String",proto:!0},{replaceAll:function(e,t){var r=hv(this),i,s,n,o,u,l,c,d,p,h,f=0,g="";if(!xL(e)){if(i=PL(e),i&&(s=oi(hv(AL(e))),!~el(s,"g")))throw new ML("`.replaceAll` does not allow non-global regexes");if(n=wL(e,$L),n)return IL(n,e,r,t);if(RL&&i)return DL(oi(r),e,t)}for(o=oi(r),u=oi(e),l=EL(t),l||(t=oi(t)),c=u.length,d=CL(1,c),p=el(o,u);p!==-1;)h=l?oi(t(u,p,o)):kL(u,o,p,[],void 0,t),g+=mv(o,f,p)+h,f=p+c,p=p+d>o.length?-1:el(o,u,p+d);return f<o.length&&(g+=mv(o,f)),g}})});var gv=b((m_,bv)=>{"use strict";rv();iv();fv();var VL=Qt();bv.exports=VL("String","replaceAll")});var Sv=b((f_,vv)=>{"use strict";var BL=gv();vv.exports=BL});var Tv=b((b_,yv)=>{"use strict";var OL=Sv();yv.exports=OL});var Ev=b((g_,Iv)=>{"use strict";var _L=Ri(),NL=ra(),FL=jt(),qL=RangeError;Iv.exports=function(e){var t=NL(FL(this)),r="",i=_L(e);if(i<0||i===1/0)throw new qL("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var kv=b((v_,Av)=>{"use strict";var wv=ve(),UL=oo(),xv=ra(),HL=Ev(),jL=jt(),QL=wv(HL),GL=wv("".slice),WL=Math.ceil,Pv=function(a){return function(e,t,r){var i=xv(jL(e)),s=UL(t),n=i.length,o=r===void 0?" ":xv(r),u,l;return s<=n||o===""?i:(u=s-n,l=QL(o,WL(u/o.length)),l.length>u&&(l=GL(l,0,u)),a?i+l:l+i)}};Av.exports={start:Pv(!1),end:Pv(!0)}});var Rv=b((S_,Lv)=>{"use strict";var YL=dr();Lv.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(YL)});var $v=b(()=>{"use strict";var zL=fe(),KL=kv().start,XL=Rv();zL({target:"String",proto:!0,forced:XL},{padStart:function(e){return KL(this,e,arguments.length>1?arguments[1]:void 0)}})});var Dv=b((I_,Mv)=>{"use strict";$v();var JL=Qt();Mv.exports=JL("String","padStart")});var Vv=b((E_,Cv)=>{"use strict";var ZL=Dv();Cv.exports=ZL});var Ov=b((x_,Bv)=>{"use strict";var eR=Vv();Bv.exports=eR});var vR={};HS(vR,{ChromecastState:()=>Si,HttpConnectionType:()=>us,Observable:()=>Tt.Observable,PlaybackState:()=>Me,Player:()=>Wa,PredefinedQualityLimits:()=>yi,SDK_VERSION:()=>gR,Subject:()=>Tt.Subject,Subscription:()=>Tt.Subscription,Surface:()=>ls,VERSION:()=>$n,ValueSubject:()=>Tt.ValueSubject,VideoFormat:()=>Et,VideoQuality:()=>Tt.VideoQuality});module.exports=jS(vR);var $n="2.0.126-dev.4eb5c2dc.0";var Me=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(Me||{}),Et=(E=>(E.MPEG="MPEG",E.DASH="DASH",E.DASH_SEP="DASH_SEP",E.DASH_SEP_VK="DASH_SEP",E.DASH_WEBM="DASH_WEBM",E.DASH_WEBM_AV1="DASH_WEBM_AV1",E.DASH_STREAMS="DASH_STREAMS",E.DASH_WEBM_VK="DASH_WEBM",E.DASH_ONDEMAND="DASH_ONDEMAND",E.DASH_ONDEMAND_VK="DASH_ONDEMAND",E.DASH_LIVE="DASH_LIVE",E.DASH_LIVE_CMAF="DASH_LIVE_CMAF",E.DASH_LIVE_WEBM="DASH_LIVE_WEBM",E.HLS="HLS",E.HLS_ONDEMAND="HLS_ONDEMAND",E.HLS_JS="HLS",E.HLS_LIVE="HLS_LIVE",E.HLS_LIVE_CMAF="HLS_LIVE_CMAF",E.WEB_RTC_LIVE="WEB_RTC_LIVE",E))(Et||{});var Si=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(Si||{}),us=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(us||{});var ls=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(ls||{}),yi=(r=>(r.TRAFFIC_SAVING="traffic_saving",r.HIGH_QUALITY="high_quality",r.UNKNOWN="unknown",r))(yi||{});var RS=U(ot(),1);var N=require("@vkontakte/videoplayer-shared/es2018");var rp=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e(),r.onerror=i=>t(i),document.body.appendChild(r)});var ms=class{constructor(e){this.connection$=new N.ValueSubject(void 0);this.castState$=new N.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new N.Subject;this.realCastState$=new N.ValueSubject("NOT_AVAILABLE");this.subscription=new N.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 r=(0,N.isNonNullable)((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},i||rp("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:N.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 r,i,s;(s=(i=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:i.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,N.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,N.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,N.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),r=cast.framework.CastContext.getInstance();this.subscription.add((0,N.fromEvent)(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{var s,n,o;switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=r.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,N.assertNever)(i.sessionState)}})).add((0,N.merge)((0,N.fromEvent)(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,N.tap)(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),(0,N.map)(i=>i.castState)),(0,N.observableFrom)([r.getCastState()])).pipe((0,N.filterChanged)(),(0,N.map)(pI),(0,N.tap)(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=(0,N.isNonNullable)(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();(0,N.assertNonNullable)(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;((0,N.isNullable)(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?(0,N.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":i)}))}initializeCastApi(){var i;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(i=this.params.receiverApplicationId)!=null?i:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:N.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},pI=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,N.assertNever)(a)}};var Il=U(ot(),1),gS=U(jr(),1),vS=U(Bo(),1);var eb=U(Us(),1);var Iu=require("@vkontakte/videoplayer-shared/es2018");var xe=(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 r=new URL(a);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(a);return!r.searchParams.get("offset_p")&&e===0?a:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:(0,Iu.assertNever)(t)}return a},Hs=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(a);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(a);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:(0,Iu.assertNever)(e)}};var k=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};var bt=require("@vkontakte/videoplayer-shared/es2018"),H=class{constructor(e){this.transitionStarted$=new bt.Subject;this.transitionEnded$=new bt.Subject;this.transitionUpdated$=new bt.Subject;this.forceChanged$=new bt.Subject;this.stateChangeStarted$=(0,bt.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,bt.merge)(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,r=this.state;this.transition=void 0,this.prevState=r,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:r,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,r=this.state;r===e||(0,bt.isNonNullable)(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};var Xf=require("@vkontakte/videoplayer-shared/es2018"),Jf=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_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,Xf.assertNever)(a)}};var R=require("@vkontakte/videoplayer-shared/es2018");var yA=5,TA=5,IA=500,Zf=7e3,ji=class{constructor(e){this.subscription=new R.Subscription;this.loadMediaTimeoutSubscription=new R.Subscription;this.videoState=new H("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,R.assertNever)(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,R.assertNever)(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,R.assertNever)(e)}break}default:(0,R.assertNever)(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Jf(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new R.Subscription;this.subscription.add(e),this.subscription.add((0,R.merge)(this.videoState.stateChangeStarted$.pipe((0,R.map)(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe((0,R.map)(i=>`stateChangeEnded$ ${JSON.stringify(i)}`))).subscribe(i=>this.log({message:`[videoState] ${i}`})));let t=(i,s)=>this.subscription.add(i.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let i=new R.Subject;e.add(i.pipe((0,R.debounce)(IA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>yA)&&i.next(o),s=o})),e.add((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);let{remotePlayer:s}=this.params.connection,n=i.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<TA&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:(0,R.assertNever)(n)}}),t((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=(0,R.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,R.observableFrom)(["init"])).pipe((0,R.debounce)(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),k(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),k(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"),k(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"&&k(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let c=t[e];(0,R.assertNonNullable)(c);let d=(0,R.getHighestQuality)(Object.keys(c));(0,R.assertNonNullable)(d);let p=c[d];(0,R.assertNonNullable)(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];(0,R.assertNonNullable)(c),r=c.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];(0,R.assertNonNullable)(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];(0,R.assertNonNullable)(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];(0,R.assertNonNullable)(c),r=xe(c.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:R.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,R.assertNever)(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:r,i);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return(0,R.isNonNullable)(o)&&(n.metadata.title=o),(0,R.isNonNullable)(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((i,s)=>{this.loadMediaTimeoutSubscription.add((0,R.timeout)(Zf).subscribe(()=>s(`timeout(${Zf})`)))});(0,eb.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},i=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${i}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:R.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var _u=U(ot(),1);var wu=require("@vkontakte/videoplayer-shared/es2018");var tb=require("@vkontakte/videoplayer-shared/es2018"),rb=a=>{try{a.pause(),a.playbackRate=0,(0,tb.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var js=require("@vkontakte/videoplayer-shared/es2018"),Eu=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)}},xu=window.WeakMap?new WeakMap:new Eu,Pu=window.WeakMap?new WeakMap:new Map,EA=(a,e=20)=>{let t=0;return(0,js.fromEvent)(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},De=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let r=a.querySelector("video"),i=!!r;r?(0,wu.clearVideoElement)(r):(r=document.createElement("video"),a.appendChild(r)),xu.set(r,i);let s=new js.Subscription;return s.add(EA(r,e)),Pu.set(r,s),r.setAttribute("crossorigin","anonymous"),r.setAttribute("playsinline","playsinline"),t&&r.setAttribute("x-yandex-pip","false"),r.controls=!1,r.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),r},Ce=a=>{let e=Pu.get(a);e==null||e.unsubscribe(),Pu.delete(a);let t=xu.get(a);xu.delete(a),t?(0,wu.clearVideoElement)(a):rb(a)};var Au=U(ei(),1),$=require("@vkontakte/videoplayer-shared/es2018");var Wt=require("@vkontakte/videoplayer-shared/es2018"),Qs=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=(0,Wt.isNullable)(i),l=new Wt.Subscription;return i&&l.add(i.subscribe(c=>{let d=a.getState();r(c,d)&&a.setState(c)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},gt=(a,e,t)=>Qs(e,()=>a.loop,r=>{(0,Wt.isNonNullable)(r)&&(a.loop=r)},{onError:t}),Ve=(a,e,t,r)=>Qs(e,()=>({muted:a.muted,volume:a.volume}),i=>{(0,Wt.isNonNullable)(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),ze=(a,e,t,r)=>Qs(e,()=>a.playbackRate,i=>{(0,Wt.isNonNullable)(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Yt=Qs;var LA=a=>["__",a.language,a.label].join("|"),RA=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},ku=class a{constructor(e){this.available$=new $.Subject;this.current$=new $.ValueSubject(void 0);this.error$=new $.Subject;this.subscription=new $.Subscription;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:$.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(Yt(t.internalTextTracks,()=>(0,Au.default)(this.internalTracks),s=>{(0,$.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,$.isNonNullable)(s)&&(0,$.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,$.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Yt(t.externalTextTracks,()=>(0,Au.default)(this.externalTracks),s=>{(0,$.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,$.isNonNullable)(s)&&(0,$.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,$.map)(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Yt(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:i})),this.subscription.add(Yt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,$.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,$.fromEvent)(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add((0,$.merge)((0,$.fromEvent)(e,"addtrack"),(0,$.fromEvent)(e,"removetrack"),(0,$.observableFrom)(["init"])).pipe((0,$.map)(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),(0,$.filterChanged)((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add((0,$.merge)((0,$.fromEvent)(e,"change"),(0,$.observableFrom)(["init"])).pipe((0,$.map)(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),(0,$.map)(r=>r&&this.htmlTextTrackToITextTrack(r).id),(0,$.filterChanged)()).subscribe(this.current$));let t=r=>{var i,s;return this.applyCueSettings((s=(i=r.target)==null?void 0:i.activeCues)!=null?s:null)};this.subscription.add((0,$.fromEvent)(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,p,h;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add((0,$.fromEvent)(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;(0,$.isNonNullable)(t.align)&&(i.align=t.align),(0,$.isNonNullable)(t.position)&&(i.position=t.position),(0,$.isNonNullable)(t.size)&&(i.size=t.size),(0,$.isNonNullable)(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,$.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c,d;let{language:t,label:r}=e,i=e.id?e.id:LA(e),s=this.externalTracks.has(i),n=(l=s?(o=this.externalTracks.get(i))==null?void 0:o.isAuto:(u=this.internalTracks.get(i))==null?void 0:u.isAuto)!=null?l:i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(c=this.externalTracks.get(i))==null?void 0:c.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(d=this.internalTracks.get(i))==null?void 0:d.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){(0,$.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,$.isNullable)(e)||!RA(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,$.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,$.assertNonNullable)(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Ke=ku;var vr=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 lb=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},Lu=a=>{let e=lb(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},cb=a=>{let e=lb(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var M=require("@vkontakte/videoplayer-shared/es2018");var $A=3,db=(a,e,t=$A)=>{let r=0,i=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(r=n,i=o,!t)return{from:r,to:i};for(let u=s-1;u>=0;u--)a.end(u)+t>=r&&(r=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=i&&(i=a.end(u))}}return{from:r,to:i}};var Be=a=>{let e=E=>(0,M.fromEvent)(a,E).pipe((0,M.mapTo)(void 0)),r=(0,M.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(E=>(0,M.fromEvent)(a,E))).pipe((0,M.map)(E=>E.type==="ended"?a.readyState<2:a.readyState<3),(0,M.filterChanged)()),i=(0,M.merge)((0,M.fromEvent)(a,"progress"),(0,M.fromEvent)(a,"timeupdate")).pipe((0,M.map)(()=>db(a.buffered,a.currentTime))),s=M.clientChecker.isSafari?(0,M.combine)({play:e("play").pipe((0,M.once)()),playing:e("playing")}).pipe((0,M.mapTo)(void 0)):e("playing"),n=(0,M.fromEvent)(a,"volumechange").pipe((0,M.map)(()=>({muted:a.muted,volume:a.volume}))),o=(0,M.fromEvent)(a,"ratechange").pipe((0,M.map)(()=>a.playbackRate)),u=(0,M.fromEvent)(a,"error").pipe((0,M.filter)(()=>!!(a.error||a.played.length)),(0,M.map)(()=>{var A;let E=a.error;return{id:E?`MediaError#${E.code}`:"HtmlVideoError",category:M.ErrorCategory.VIDEO_PIPELINE,message:E?E.message:"Error event from HTML video element",thrown:(A=a.error)!=null?A:void 0}})),l=(0,M.fromEvent)(a,"timeupdate").pipe((0,M.map)(()=>a.currentTime)),c=new M.Subject,d=.3,p;l.subscribe(E=>{a.loop&&(0,M.isNonNullable)(p)&&(0,M.isNonNullable)(E)&&p>=a.duration-d&&E<=d&&c.next(p),p=E});let h=e("pause").pipe((0,M.filter)(()=>!a.error&&p!==a.duration)),f=(0,M.fromEvent)(a,"enterpictureinpicture"),g=(0,M.fromEvent)(a,"leavepictureinpicture"),S=new M.ValueSubject(cb(a));f.subscribe(()=>S.next(!0)),g.subscribe(()=>S.next(!1));let I=new M.ValueSubject(Lu(a));return(0,M.fromEvent)(a,"fullscreenchange").pipe((0,M.map)(()=>Lu(a))).subscribe(I),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:(0,M.fromEvent)(a,"durationchange").pipe((0,M.map)(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:I,enterPip$:f,leavePip$:g}};var At=require("@vkontakte/videoplayer-shared/es2018"),zt=a=>{switch(a){case"mobile":return At.VideoQuality.Q_144P;case"lowest":return At.VideoQuality.Q_240P;case"low":return At.VideoQuality.Q_360P;case"sd":case"medium":return At.VideoQuality.Q_480P;case"hd":case"high":return At.VideoQuality.Q_720P;case"fullhd":case"full":return At.VideoQuality.Q_1080P;case"quadhd":case"quad":return At.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return At.VideoQuality.Q_2160P}};var Xt=U(Kt(),1),Eb=U(ot(),1),Gs=U(jr(),1),B=require("@vkontakte/videoplayer-shared/es2018");var Ru=!1,kt={},vb=a=>{Ru=a},Sb=()=>{kt={}},yb=a=>{a(kt)},Qi=(a,e)=>{var t;Ru&&(kt.meta=(t=kt.meta)!=null?t:{},kt.meta[a]=e)},Le=class{constructor(e){this.name=e}next(e){var r,i;if(!Ru)return;kt.series=(r=kt.series)!=null?r:{};let t=(i=kt.series[this.name])!=null?i:[];t.push([Date.now(),e]),kt.series[this.name]=t}};var be=require("@vkontakte/videoplayer-shared/es2018");function $u({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function Mu({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!!a&&$u({limits:a,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}function Gi({limits:a,highestAvailableQuality:e,lowestAvailableQuality:t}){return(0,be.isNullable)(a)||(0,be.isNonNullable)(a.min)&&(0,be.isNonNullable)(a.max)&&(0,be.isLower)(a.max,a.min)||(0,be.isNonNullable)(a.min)&&e&&(0,be.isHigher)(a.min,e)||(0,be.isNonNullable)(a.max)&&t&&(0,be.isLower)(a.max,t)}function Tb({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return Gi({limits:{max:a!=null&&a.max?(0,be.videoHeightToQuality)(a.max):void 0,min:a!=null&&a.min?(0,be.videoHeightToQuality)(a.min):void 0},highestAvailableQuality:e?(0,be.videoHeightToQuality)(e):void 0,lowestAvailableQuality:t?(0,be.videoHeightToQuality)(t):void 0})}var FA=new Le("best_bitrate"),xb=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var Du=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Wi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,B.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Pb='Assertion "ABR Tracks is empty array" failed',Ws=(a,e,t,r)=>{var u;let i=[...e].sort(Du(1)),s=[...t].sort(Du(1)),n=s.filter(l=>(0,B.isNonNullable)(l.bitrate)&&(0,B.isNonNullable)(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Xt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Xt.default)(s,-1);return o&&(0,Eb.default)(n,o)?o:n.length?(0,Xt.default)(n,-1):(0,Xt.default)(s,0)},Ib=a=>"quality"in a,wb=(a,e,t,r)=>{var n;let i=(0,B.isNonNullable)((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&(0,B.isNonNullable)(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&(0,B.now)()-r.history[t.id]<=i&&(!r.last||t.id!==r.last.id);if(t!=null&&t.id&&r&&!s&&r.recordSelection(t),s&&(r!=null&&r.last)){let o=r.last;r==null||r.recordSwitch(o);let u=Ib(o)?"video":"audio",l=Ib(o)?o.quality:o.bitrate;return e({message:`
|
|
8
8
|
[last ${u} selected] ${l}
|
|
9
|
-
`}),o}return r==null||r.recordSwitch(t),t},
|
|
9
|
+
`}),o}return r==null||r.recordSwitch(t),t},qA=(a,e)=>Math.log(e)/Math.log(a),UA=({tuning:a,container:e,limits:t})=>{let r=a.containerSizeFactor;if(a.usePixelRatio&&window.devicePixelRatio){let i=window.devicePixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(i-1)+1;else{let s=a.pixelRatioLogBase,[n=0,o=0,u=0]=a.pixelRatioLogCoefficients,l=qA(s,n*i+o)+u;Number.isFinite(l)&&(r*=l)}}return Mu({highQualityLimit:a.highQualityLimit,trafficSavingLimit:a.trafficSavingLimit,limits:t})&&(r*=2),{containerSizeLimit:a.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},Jt=(a,{container:e,estimatedThroughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:f})=>{var Z,C,_,ie,me,L;(0,B.assertNotEmptyArray)(a,Pb);let{containerSizeFactor:g,containerSizeLimit:S}=UA({container:e,tuning:r,limits:i}),I=r.considerPlaybackRate&&(0,B.isNonNullable)(o)?o:1,x=a.filter(P=>!(0,B.isInvariantQuality)(P.quality)).sort((P,q)=>(0,B.isHigher)(P.quality,q.quality)?-1:1),E=(Z=(0,Xt.default)(x,-1))==null?void 0:Z.quality,A=(C=(0,Xt.default)(x,0))==null?void 0:C.quality,w=Gi({limits:i,lowestAvailableQuality:E,highestAvailableQuality:A}),Q=I*xb(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),F={},W=x.filter(P=>{let q=!0;if(S)if(P.size)q=P.size.width<=S.width&&P.size.height<=S.height;else{let Ae=S&&(0,B.videoSizeToQuality)(S);q=Ae?(0,B.isLowerOrEqual)(P.quality,Ae):!0}if(!q)return F[P.quality]="FitsContainer",!1;let ee=h||t,Y=(0,B.isNonNullable)(ee)&&isFinite(ee)&&(0,B.isNonNullable)(P.bitrate)?ee-s>=P.bitrate*Q:!0,qe=Mu({highQualityLimit:r.highQualityLimit,trafficSavingLimit:r.trafficSavingLimit,limits:i})&&(i==null?void 0:i.min)===P.quality;if(!Y&&!qe)return F[P.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&(0,B.isNonNullable)(r.minBufferToSwitchUp)&&u&&!(0,B.isInvariantQuality)(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&(0,B.isHigher)(P.quality,u.quality))return F[P.quality]="Buffer",!1;if(!!d&&(0,B.isHigherOrEqual)(P.quality,d)&&!qe)return F[P.quality]="DroppedFramesLimit",!1;if(!!p&&(0,B.isHigherOrEqual)(P.quality,p)&&!qe)return F[P.quality]="StallsLimit",!1;let Te=w||((0,B.isNullable)(i==null?void 0:i.max)||(0,B.isLowerOrEqual)(P.quality,i.max))&&((0,B.isNullable)(i==null?void 0:i.min)||(0,B.isHigherOrEqual)(P.quality,i.min)),we=(0,B.isNonNullable)(c)&&!c?(0,B.isLowerOrEqual)(P.quality,r.backgroundVideoQualityLimit):!0;return!Te||!we?(F[P.quality]="FitsQualityLimits",!1):!0})[0];W&&W.bitrate&&FA.next(W.bitrate);let J=(_=W!=null?W:(0,Xt.default)(x,-1))!=null?_:a[0];return J.quality!==((ie=l==null?void 0:l.last)==null?void 0:ie.quality)&&f({message:`
|
|
10
10
|
[VIDEO TRACKS ABR]
|
|
11
11
|
[available video tracks]
|
|
12
12
|
${a.map(P=>{var q,ee;return`{ id: ${P.id}, quality: ${P.quality}, bitrate: ${P.bitrate}, size: ${(q=P.size)==null?void 0:q.width}:${(ee=P.size)==null?void 0:ee.height} }`}).join(`
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[tuning]
|
|
16
|
-
${(0,
|
|
16
|
+
${(0,Gs.default)(r!=null?r:{}).map(([P,q])=>`${P}: ${q}`).join(`
|
|
17
17
|
`)}
|
|
18
18
|
|
|
19
19
|
[limit params]
|
|
20
20
|
containerSizeFactor: ${g},
|
|
21
|
-
containerSizeLimit: ${(
|
|
21
|
+
containerSizeLimit: ${(me=S==null?void 0:S.width)!=null?me:0} x ${(L=S==null?void 0:S.height)!=null?L:0},
|
|
22
22
|
estimatedThroughput: ${t},
|
|
23
23
|
stallsPredictedThroughput: ${h},
|
|
24
24
|
reserve: ${s},
|
|
@@ -34,19 +34,19 @@
|
|
|
34
34
|
minQualityLimit: ${i==null?void 0:i.min},
|
|
35
35
|
|
|
36
36
|
[limited video tracks]
|
|
37
|
-
${(0,
|
|
37
|
+
${(0,Gs.default)(F).map(([P,q])=>`${P}: ${q}`).join(`
|
|
38
38
|
`)||"All tracks are available"}
|
|
39
39
|
|
|
40
40
|
[best video track] ${W==null?void 0:W.quality}
|
|
41
41
|
[selected video track] ${J==null?void 0:J.quality}
|
|
42
|
-
`}),
|
|
42
|
+
`}),wb(r,f,J,l)},Ab=(a,e,t,{estimatedThroughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{var I;(0,B.assertNotEmptyArray)(t,Pb);let c=i.considerPlaybackRate&&(0,B.isNonNullable)(s)?s:1,d=[...t].sort(Du(-1)),p=a.bitrate;(0,B.assertNonNullable)(p);let h=c*xb(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),f,g=Ws(a,e,t,i.minVideoAudioRatio),S=l||r;return(0,B.isNonNullable)(S)&&isFinite(S)&&(f=d.find(x=>(0,B.isNonNullable)(x.bitrate)&&(0,B.isNonNullable)(g==null?void 0:g.bitrate)?S-p>=x.bitrate*h&&x.bitrate>=g.bitrate:!1)),f||(f=g),(f==null?void 0:f.bitrate)!==((I=o==null?void 0:o.last)==null?void 0:I.bitrate)&&u({message:`
|
|
43
43
|
[AUDIO TRACKS ABR]
|
|
44
44
|
[available audio tracks]
|
|
45
|
-
${t.map(
|
|
45
|
+
${t.map(x=>`{ id: ${x.id}, bitrate: ${x.bitrate} }`).join(`
|
|
46
46
|
`)}
|
|
47
47
|
|
|
48
48
|
[tuning]
|
|
49
|
-
${(0,
|
|
49
|
+
${(0,Gs.default)(i!=null?i:{}).map(([x,E])=>`${x}: ${E}`).join(`
|
|
50
50
|
`)}
|
|
51
51
|
|
|
52
52
|
[limit params]
|
|
@@ -60,14 +60,14 @@
|
|
|
60
60
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
61
61
|
|
|
62
62
|
[selected audio track] ${f==null?void 0:f.id}
|
|
63
|
-
`}),f&&Ib(i,u,f,o)};var ve=a=>new URL(a).hostname;var D=require("@vkontakte/videoplayer-shared/es2018");var Lb=U(Kt(),1);var Pb=U(nt(),1),xb=a=>{if(a instanceof DOMException&&(0,Pb.default)(["Failed to load because no supported source was found.","The element has no supported sources."],a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},Be=async(a,e)=>{let t=a.muted;try{await a.play()}catch(r){if(!xb(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{await a.play()}catch(i){return xb(i)&&(a.muted=!1,console.warn(i)),!1}}return!0};var Qe=require("@vkontakte/videoplayer-shared/es2018");var wb=U(ei(),1),gt=require("@vkontakte/videoplayer-shared/es2018");function Se(){return(0,gt.now)()}function Vu(a){return Se()-a}function Bu(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,i=n=>r.test(n);return{resolve:(n,o,u=!1)=>{i(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Ab(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function ti(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",f=7e3,g=2e3,S=()=>{if(u)return;(0,gt.assertNonNullable)(c);let C=Vu(c),_;if(C<g){_=g-C,setTimeout(S,_);return}g*=2,g>f&&(g=f),n&&n.abort(),n=new i,Q()},I=C=>(s=C,Z),E=C=>(d=C,Z),x=()=>(h="json",Z),k=()=>{if(!u){if(--l>=0){S(),r&&r();return}u=!0,d&&d(),t&&t()}},w=C=>(p=C,Z),Q=()=>{c=Se(),n=new i,n.open("get",a);let C=0,_,ie=0,he=()=>((0,gt.assertNonNullable)(c),Math.max(c,Math.max(_||0,ie||0)));if(s&&n.addEventListener("progress",L=>{let P=Se();s.updateChunk&&L.loaded>C&&(s.updateChunk(he(),L.loaded-C),C=L.loaded,_=P)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>k())),n.addEventListener("load",()=>{if(u)return;(0,gt.assertNonNullable)(n);let L=n.status;if(L>=200&&L<300){let{response:P,responseType:q}=n,ee=P==null?void 0:P.byteLength;if(typeof ee=="number"&&s){let Y=ee-C;Y&&s.updateChunk&&s.updateChunk(he(),Y)}q==="json"&&(!P||!(0,wb.default)(P).length)?k():(d&&d(),e(P))}else k()}),n.addEventListener("error",()=>{k()}),p){let L=()=>{(0,gt.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ie=Se(),n.removeEventListener("readystatechange",L))};n.addEventListener("readystatechange",L)}return n.responseType=h,n.send(),Z},Z={withBitrateReporting:I,withParallel:w,withJSONResponse:x,withRetryCount:C=>(l=C,Z),withRetryInterval:(C,_)=>((0,gt.isNonNullable)(C)&&(g=C),(0,gt.isNonNullable)(_)&&(f=_),Z),withTimeout:C=>(o=C,Z),withFinally:E,send:Q,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return Z}var Yi=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,i=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,i+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;i+=u,s.start=t,s.bytes-=u}}}if(i>0&&r>0){let s=i*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var kb=U(ei(),1);var zi=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=Se(),i=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=Se()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=ti(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Se()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=Se();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,kb.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,i){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=i,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=i,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var Rb=require("@vkontakte/videoplayer-shared/es2018");var zs=1e4,Ou=3;var FA=6e4,qA=10,UA=1,HA=500,Ki=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.soundProhibitedEvent$=new Rb.Subject,this.chunkRateEstimator=new Yi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Bu(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Bu(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)==null?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,i;r!==0&&(i=t.buffered.start(r-1),t.currentTime<i&&(e("Fixup stall"),t.currentTime=i))}_selectQuality(e){let{videoElement:t}=this.params,r,i,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){s=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!gb({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Lb.default)(this.manifest,-1).video.height})&&(u&&s.video.height>u||l&&s.video.height<l)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!i||s.bitrate>i.bitrate)&&(i=s):(!r||r.bitrate>s.bitrate)&&(r=s))}return i||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,Qe.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:i,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Ab(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new zi(Ou,zs,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let k=s&&(!c||c===this.rep);return k||t("Not running!"),k},p=(k,w,Q)=>{u&&u.abort(),u=ti(this.urlResolver.resolve(k,!1),w,Q,()=>this._retryCallback()).withTimeout(zs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ou).withFinally(()=>{u=null}).send()},h=(k,w,Q)=>{(0,Qe.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(k,!1),w,Q,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=k=>{let w=r.playbackRate;r.playbackRate!==k&&(t(`Playback rate switch: ${w}=>${k}`),r.playbackRate=k)},g=k=>{this.lowLatency=k,t(`lowLatency changed to ${k}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let k=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let Q=Se()-1e4,F=0;for(let W=0;W<this.bufferStates.length;W++){let J=this.bufferStates[W];k=Math.min(k,J.buf),J.ts<Q&&F++}this.bufferStates.splice(0,F),t(`update playback rate; minBuffer=${k} drop=${F} jitter=${this.sourceJitter}`);let re=k-UA;this.sourceJitter>=0?re-=this.sourceJitter/2:this.sourceJitter-=1,re>3?f(1.15):re>1?f(1.1):re>.3?f(1.05):f(1)}},I=k=>{let w,Q=()=>w&&w.start?w.start.length:0,F=L=>w.start[L]/1e3,re=L=>w.dur[L]/1e3,W=L=>w.fragIndex+L,J=(L,P)=>({chunkIdx:W(L),startTS:F(L),dur:re(L),discontinuity:P}),Z=()=>{let L=0;if(w&&w.dur){let P=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,q=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ee=P;this.sourceJitter>1&&(ee+=this.sourceJitter-1);let Y=w.dur.length-1;for(;Y>=0&&(ee-=w.dur[Y],!(ee<=0));--Y);L=Math.min(Y,w.dur.length-1-q),L=Math.max(L,0)}return J(L,!0)},C=L=>{let P=Q();if(!(P<=0)){if((0,Qe.isNonNullable)(L)){for(let q=0;q<P;q++)if(F(q)>L)return J(q)}return Z()}},_=L=>{let P=Q(),q=L?L.chunkIdx+1:0,ee=q-w.fragIndex;if(!(P<=0)){if(!L||ee<0||ee-P>qA)return t(`Resync: offset=${ee} bChunks=${P} chunk=`+JSON.stringify(L)),Z();if(!(ee>=P))return J(q-w.fragIndex,!1)}},ie=(L,P,q)=>{l&&l.abort(),l=ti(this.urlResolver.resolve(L,!0,this.lowLatency),P,q,()=>this._retryCallback()).withTimeout(zs).withRetryCount(Ou).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(L,P)=>{ie(k,q=>{if(!d())return;w=q;let ee=!!w.lowLatency;ee!==this.lowLatency&&g(ee);let Y=0;for(let Fe=0;Fe<w.dur.length;++Fe)Y+=w.dur[Fe];Y>0&&((0,Qe.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Y/w.dur.length)),i({name:"index",zeroTime:w.zeroTime,shiftDuration:w.shiftDuration}),this.sourceJitter=w.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,w.jitter/1e3)):1,L(C(P))},()=>this._handleNetworkError())},nextChunk:_}},E=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),(0,Qe.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:k=>{let{videoElement:w,logger:Q}=this.params,F=I(e.jidxUrl),re,W,J,Z,C=0,_,ie,he,L=()=>{_&&(clearTimeout(_),_=void 0);let te=Math.max(HA,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ye=C+te,Pe=Se(),we=Math.min(1e4,ye-Pe);C=Pe;let Bt=()=>{l||d()&&F.seek(()=>{d()&&(C=Se(),P(),L())})};we>0?_=window.setTimeout(()=>{this.paused?L():Bt()},we):Bt()},P=()=>{let te;for(;te=F.nextChunk(Z);)Z=te,di(te);let ye=F.nextChunk(J);if(ye){if(J&&ye.discontinuity){Q("Detected discontinuity; restarting playback"),this.paused?L():(E(),this._initPlayerWith(e));return}Fe(ye)}else L()},q=(te,ye)=>{if(!d()||!this.sourceBuffer)return;let Pe,we,Bt,Ar=Ot=>{window.setTimeout(()=>{d()&&q(te,ye)},Ot)};if(this.sourceBuffer.updating)Q("Source buffer is updating; delaying appendBuffer"),Ar(100);else{let Ot=Se(),ir=w.currentTime;!this.paused&&w.buffered.length>1&&ie===ir&&Ot-he>500&&(Q("Stall suspected; trying to fix"),this._fixupStall()),ie!==ir&&(ie=ir,he=Ot);let kr=this._getBufferSizeSec();if(kr>30)Q(`Buffered ${kr} seconds; delaying appendBuffer`),Ar(2e3);else try{this.sourceBuffer.appendBuffer(te),this.videoPlayStarted?(this.bufferStates.push({ts:Ot,buf:kr}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ye&&ye()}catch(pi){if(pi.name==="QuotaExceededError")Q("QuotaExceededError; delaying appendBuffer"),Bt=this.sourceBuffer.buffered.length,Bt!==0&&(Pe=this.sourceBuffer.buffered.start(0),we=ir,we-Pe>4&&this.sourceBuffer.remove(Pe,we-3)),Ar(1e3);else throw pi}}},ee=()=>{W&&re&&(Q([`Appending chunk, sz=${W.byteLength}:`,JSON.stringify(J)]),q(W,function(){W=null,P()}))},Y=te=>e.fragUrlTemplate.replace("%%id%%",te.chunkIdx),Fe=te=>{d()&&h(Y(te),(ye,Pe)=>{if(d()){if(Pe/=1e3,W=ye,J=te,n=te.startTS,Pe){let we=Math.min(10,te.dur/Pe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*we:we}ee()}},()=>this._handleNetworkError())},di=te=>{d()&&((0,Qe.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Y(te),!1)))},wr=te=>{d()&&(e.cachedHeader=te,q(te,()=>{re=!0,ee()}))};s=!0,F.seek(te=>{if(d()){if(C=Se(),!te){L();return}Z=te,!(0,Qe.isNullable)(k)||te.startTS>k?Fe(te):(J=te,P())}},k),e.cachedHeader?wr(e.cachedHeader):p(e.headerUrl,wr,()=>this._handleNetworkError())},stop:E,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),(0,Qe.isNonNullable)(i)&&(i+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,(0,Qe.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,Qe.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),f=d/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let f=Se();if(this.chunkRateEstimator.addInterval(p,f,h)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:S}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Vu(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=Se();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=ti(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(zs).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;Be(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{var c,d;u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&((d=(c=window.MediaSource)==null?void 0:c.isTypeSupported)!=null&&d.call(c,u.codecs))&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},FA))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var $b=U(jr(),1),le=require("@vkontakte/videoplayer-shared/es2018"),_u=class{constructor(){this.onDroopedVideoFramesLimit$=new le.Subject;this.subscription=new le.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new le.Subject;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!(0,le.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,i=t-this.prevDroppedVideoFrames,s=1-(r-i)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&(0,le.isHigher)(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add((0,le.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,le.interval)(this.droppedFramesChecker.checkTime).pipe((0,le.filter)(()=>this.playing),(0,le.filter)(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe((0,le.debounce)(this.droppedFramesChecker.checkTime)),r=(0,le.merge)(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var r,i;let t=(i=(r=(0,$b.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>(0,le.isLower)(s,n)?-1:1))==null?void 0:r[0])==null?void 0:i[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Ks=_u;var Xs=require("@vkontakte/videoplayer-shared/es2018"),Mb=require("@vkontakte/videoplayer-shared/es2018");var Xi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var jA=(a,e)=>new Xs.Observable(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Xi()))},{...r,...e});i.observe(a);let s=(0,Mb.fromEvent)(document,"visibilitychange").pipe((0,Xs.map)(n=>!document.hidden||Xi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Ke=jA;var QA=["paused","playing","ready"],GA=["paused","playing","ready"],Ji=class{constructor(e){this.subscription=new D.Subscription;this.videoState=new H("stopped");this.representations$=new D.ValueSubject([]);this.droppedFramesManager=new Ks;this.maxSeekBackTime$=new D.ValueSubject(1/0);this.zeroTime$=new D.ValueSubject(void 0);this.liveOffset=new wt;this._dashCb=e=>{var t,r,i,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:D.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(r=zt(u.name))!=null?r:(0,D.videoSizeToQuality)(u.video),d=u.bitrate/1e3,p={...u.video};if(!c)continue;let h={id:l,quality:c,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),(0,D.isNonNullable)(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,Nu.default)(GA,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,Nu.default)(QA,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Ee(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=i==null?void 0:i.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(Ee(this.params.source.url,u))}return;default:return(0,D.assertNever)(e)}};this.textTracksManager=new ze(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:D.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:i})};(0,D.merge)(this.videoState.stateChangeStarted$.pipe((0,D.map)(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,D.map)(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=Me(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ve(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=Ve(this.video);this.subscription.add(this.representations$.pipe((0,D.map)(i=>i.map(({track:s})=>s)),(0,D.filter)(i=>!!i.length),(0,D.once)()).subscribe(i=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:i}))),this.subscription.add(r.canplay$.subscribe(()=>{var i;((i=this.videoState.getTransition())==null?void 0:i.to)==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((0,D.filterChanged)(),(0,D.map)(i=>-i/1e3)).subscribe(this.params.output.duration$)).add((0,D.combine)({zeroTime:this.zeroTime$.pipe((0,D.filter)(D.isNonNullable)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(bt(this.video,this.params.desiredState.isLooped,t)).add(Ce(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Ye(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ke(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i,min:s}})=>{this.dash.setAutoQualityLimits({max:i&&(0,D.videoQualityToHeight)(i),min:s&&(0,D.videoQualityToHeight)(s)}),this.params.output.autoVideoTrackLimits$.next({max:i,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(i=>{var s;switch(i.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return(0,D.assertNever)(i.to)}},t)).add((0,D.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,D.observableFrom)(["init"])).pipe((0,D.debounce)(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),De(this.video)}createLiveDashPlayer(){let e=new Ki({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,p,h,f;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&(0,D.isNonNullable)(t)?t:Jt(e.map(({track:g})=>g),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=i==null?void 0:i.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let g=(f=e.find(({track:S})=>S.id===s))==null?void 0:f.representation;(0,D.assertNonNullable)(g,"Representations missing"),this.dash.startPlay(g,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:i})=>i.id===e.id))==null?void 0:r.representation;(0,D.assertNonNullable)(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Ee(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var Db=Ji;var rS=U(nt(),1);var vt=(a,e)=>{let t=0;for(let r=0;r<a.length;r++){let i=a.start(r)*1e3,s=a.end(r)*1e3;i<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var O=require("@vkontakte/videoplayer-shared/es2018");var Js=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},ri=class extends Js{constructor(){super(),this.listeners||Js.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},Zi=class{constructor(){Object.defineProperty(this,"signal",{value:new ri,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(i){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Zi.prototype[Symbol.toStringTag]="AbortController",ri.prototype[Symbol.toStringTag]="AbortSignal");function Zs(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function Fu(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!Zs({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var ea=Zs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Cb=ea?Fu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ut=ea?Cb.fetch:window.fetch,zC=ea?Cb.Request:window.Request,xe=ea?Zi:window.AbortController,KC=ea?ri:window.AbortSignal;var fl=U(Uu(),1);var ln=U(Kt(),1);var Lt=()=>window.ManagedMediaSource||window.MediaSource,en=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},eg=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},tg=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var St=require("@vkontakte/videoplayer-shared/es2018"),Xe=document.createElement("video"),gk='video/mp4; codecs="avc1.42000a,mp4a.40.2"',vk='video/mp4; codecs="hev1.1.6.L93.B0"',pg='video/webm; codecs="vp09.00.10.08"',hg='video/webm; codecs="av01.0.00M.08"',Sk='audio/mp4; codecs="mp4a.40.2"',yk='audio/webm; codecs="opus"',rg,ig,ta={mms:en(),mse:eg(),hls:!!((rg=Xe.canPlayType)!=null&&rg.call(Xe,"application/x-mpegurl")||(ig=Xe.canPlayType)!=null&&ig.call(Xe,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},ag,sg,Oe={mp4:!!((ag=Xe.canPlayType)!=null&&ag.call(Xe,"video/mp4")),webm:!!((sg=Xe.canPlayType)!=null&&sg.call(Xe,"video/webm")),cmaf:!0},rn,ng,an,og,sn,ug,nn,lg,on,cg,un,dg,_e={h264:!!((ng=(rn=Lt())==null?void 0:rn.isTypeSupported)!=null&&ng.call(rn,gk)),h265:!!((og=(an=Lt())==null?void 0:an.isTypeSupported)!=null&&og.call(an,vk)),vp9:!!((ug=(sn=Lt())==null?void 0:sn.isTypeSupported)!=null&&ug.call(sn,pg)),av1:!!((lg=(nn=Lt())==null?void 0:nn.isTypeSupported)!=null&&lg.call(nn,hg)),aac:!!((cg=(on=Lt())==null?void 0:on.isTypeSupported)!=null&&cg.call(on,Sk)),opus:!!((dg=(un=Lt())==null?void 0:un.isTypeSupported)!=null&&dg.call(un,yk))},ii=(_e.h264||_e.h265)&&_e.aac,Sr,Tk=async()=>{if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:hg}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:pg}})]);Sr={DASH_WEBM_AV1:e,DASH_WEBM:t}};Tk().catch(a=>{console.error(a)});var ai=ta.hls&&Oe.mp4,mg=()=>Object.keys(_e).filter(a=>_e[a]),fg=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let i=ta.mse&&(!r||!!window.MediaStreamTrack)||ta.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return i&&Oe.mp4&ⅈcase"DASH_WEBM":return i&&Oe.webm&&_e.vp9&&_e.opus;case"DASH_WEBM_AV1":return i&&Oe.webm&&_e.av1&&_e.opus;case"DASH_STREAMS":return i&&(Oe.mp4&&ii||Oe.webm&&(_e.vp9||_e.av1)&&(_e.opus||_e.aac));case"DASH_LIVE":return i&&Oe.mp4&ⅈcase"DASH_LIVE_CMAF":return i&&Oe.mp4&&ii&&Oe.cmaf;case"DASH_ONDEMAND":return i&&Oe.mp4&ⅈcase"HLS":case"HLS_ONDEMAND":return ai||e&&i&&Oe.mp4&ⅈcase"HLS_LIVE":case"HLS_LIVE_CMAF":return ai;case"MPEG":return Oe.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return ta.webrtc&&ta.ws&&_e.h264&&(Oe.mp4||Oe.webm);default:return(0,St.assertNever)(s)}})},tn=a=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(a){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return Sr?Sr[t].smooth?[t,e]:Sr[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Sr?Sr[t].powerEfficient?[t,e]:Sr[e].powerEfficient?[e,t]:[t,e]:[e,t];default:(0,St.assertNever)(a)}return[e,t]},bg=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...tn(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(St.clientChecker.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[...i,"MPEG",...tn(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...tn(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...tn(a),...i,"HLS","HLS_ONDEMAND"];default:(0,St.assertNever)(e)}return ai?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},gg=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],i=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...i],n=[...i,...r],o,u=St.clientChecker.isMac&&St.clientChecker.isSafari;if(St.clientChecker.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,St.assertNever)(a)}else ai&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Hu=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],vg=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,ln.default)(t.value.split("."),0)}for(let t of a){let r=(0,ln.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,ln.default)(e.value.split("."),0)};var Ng=U(_g(),1),si=require("@vkontakte/videoplayer-shared/es2018"),Fg=a=>{if(!a)return{id:"EmptyResponse",category:si.ErrorCategory.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:si.ErrorCategory.NETWORK,message:`UV Error ${a}`};let e=(0,Ng.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:si.ErrorCategory.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:si.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:si.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var Zt=(a,e,t=0)=>{for(let r=0;r<a.length;r++)if(a.start(r)*1e3-t<=e&&a.end(r)*1e3+t>e)return!0;return!1};var v=require("@vkontakte/videoplayer-shared/es2018");var cn=U(nt(),1),ui=U(Kt(),1),dn=U(Uu(),1);var _k=(a,e={})=>{let r=e.timeout||1,i=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-i-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-i))}})},1)},Nk=a=>window.clearTimeout(a),qg=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),Ug=!qg(window.requestIdleCallback)||!qg(window.cancelIdleCallback),Yu=Ug?_k:window.requestIdleCallback,ia=Ug?Nk:window.cancelIdleCallback;var Yv=U(Hs(),1);var Je=require("@vkontakte/videoplayer-shared/es2018"),Fk=18,Hg=!1;try{Hg=Je.clientChecker.isSafari&&!!Je.clientChecker.macVersion&&Je.clientChecker.macVersion<=Fk}catch(a){console.error(a)}var zu=class{constructor(e){this.bufferFull$=new Je.Subject;this.error$=new Je.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!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.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Je.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})}async remove(e,t,r){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let r,i=s=>{this.abortRequested=!1,t(s)};Hg&&e?r={operation:"safariAbort",init:e,callback:i}:r={operation:"abort",callback:i};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,r&&(this.queue=[r]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var i;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((i=e.signal)!=null&&i.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:Je.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,Je.assertNever)(t)}}},jg=zu;var Ku=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};var T=require("@vkontakte/videoplayer-shared/es2018");var z=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let i=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,i)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}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 ni=class extends z{};var aa=class extends z{constructor(t,r){super(t,r);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let i=this.content.byteOffset,s=i+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(i,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var sa=class extends z{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let i=this.readString(4);this.compatibleBrands.push(i),r-=4}}};var na=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ne=class extends z{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var oa=class extends ne{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var ua=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var la=class extends z{constructor(e,t){super(e,t),this.data=this.content}};var yr=class extends ne{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,l=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var ca=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var da=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pa=class extends ne{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var ha=class extends ne{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ma=class extends ne{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var fa=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ba=class extends ne{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 ga=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var va=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Sa=class extends ne{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ya=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ta=class extends ne{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 Ia=class extends ne{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Ea=class extends ne{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)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 xa=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Pa=class extends ne{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var wa=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var Uk={ftyp:sa,moov:na,mvhd:oa,moof:ua,mdat:la,sidx:yr,trak:ca,mdia:fa,mfhd:Sa,tkhd:ba,traf:ya,tfhd:Ta,tfdt:Ia,trun:Ea,minf:ga,sv3d:da,st3d:pa,prhd:ha,proj:va,equi:ma,uuid:aa,stbl:xa,stsd:Pa,avc1:wa,unknown:ni},Rt=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=Uk[e];return r?new r(t,new a):new ni(t,new a)}};var er=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),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 jk=new TextDecoder("ascii"),Qk=a=>jk.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",Gk=a=>{let e=new yr(a,new Rt),t=e.earliestPresentationTime/e.timescale*1e3,r=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:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},Wk=(a,e)=>{let r=new Rt().parse(a),i=new er(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},Yk=a=>{let t=new Rt().parse(a),r=new er(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},zk=a=>{var i;let t=new Rt().parse(a);return(i=new er(t).find("sidx"))==null?void 0:i.timescale},Kk=(a,e)=>{let r=new Rt().parse(a),s=new er(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},Xk=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}}},r=new Rt().parse(a),i=new er(r);if(i.find("sv3d")){e.is3dVideo=!0;let n=i.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=i.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=i.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},Qg={validateData:Qk,parseInit:Xk,getIndexRange:()=>{},parseSegments:Gk,parseFeedableSegmentChunk:Wk,getChunkEndTime:Kk,getServerLatencyTimestamps:Yk,getTimescaleFromIndex:zk};var ka=U(nt(),1),$t=require("@vkontakte/videoplayer-shared/es2018");var Wg=require("@vkontakte/videoplayer-shared/es2018");var Gg={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"}},Yg=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 r=Aa(a,t),i=r in Gg,s=i?Gg[r].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),l=n&255>>o,c=Aa(u),d=l*2**((o-1)*8)+c,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},Aa=(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},lt=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Aa(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,Wg.assertNever)(e)}},Tr=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=Yg(r);if(!e(i))return;i.type==="master"&&Tr(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},zg=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=Yg(a);return Tr(i.value,({tag:s,type:n,value:o})=>(s===17143?e=lt(o,n):s===17026?t=lt(o,n):s===17029&&(r=lt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Kg=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Jk=[231,22612,22743,167,171,163,160,175],Zk=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return Tr(a,({tag:p,type:h,value:f,valueSize:g})=>{if(p===21419){let S=lt(f,h);l=Aa(S)}else p!==21420&&(l=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+g):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=lt(f,h):p===17545?i=lt(f,h):p===21420&&l===475249515?u=lt(f,h):p===374648427?Tr(f,({tag:S,type:I,value:E})=>S===30321?(c=lt(E,I)===1,!1):!0):s&&n&&(0,ka.default)(Kg,p)&&(o=!0),!o}),(0,$t.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,$t.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,$t.assertNonNullable)(i,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},eL=a=>{if((0,$t.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},tL=(a,e)=>{let t=!1,r=!1,i=o=>(0,$t.isNonNullable)(o.time)&&(0,$t.isNonNullable)(o.position),s=[],n;return Tr(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=lt(l,u));break;case 183:break;case 241:n&&(n.position=lt(l,u));break;default:t&&(0,ka.default)(Kg,o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},rL=a=>{let e=0,t=!1;try{Tr(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,ka.default)(Jk,r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=(0,ka.default)([163,160,175],r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},Xg={validateData:zg,parseInit:Zk,getIndexRange:eL,parseSegments:tL,parseFeedableSegmentChunk:rL};var La=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return Xg;case"mp4":return Qg}}throw new ReferenceError(`Unsupported mime type ${a}`)};var ll=U(gv(),1),Hv=U(jr(),1),jv=U(Dv(),1),Qv=U(Kt(),1),cl=U(ei(),1);var Cv=U(nt(),1),il=a=>{let e=a.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[i,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[i,s,n]=r;return!!(i&&parseInt(i,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let i=r[0];if(!i||i.length!==6)return!1;let[s,n]=i.toUpperCase(),o=s+n;return(0,Cv.default)(["6E","7A","F4"],o)}}return!1};var $a=require("@vkontakte/videoplayer-shared/es2018");var Vv=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Bv=a=>{var e;try{let t=XL(),r=a.match(t),{groups:i}=r!=null?r:{};if(i){let s={};if(i.extensions){let u=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=i.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function XL(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
|
|
63
|
+
`}),f&&wb(i,u,f,o)};var Se=a=>new URL(a).hostname;var D=require("@vkontakte/videoplayer-shared/es2018");var Db=U(Kt(),1);var Lb=U(ot(),1),kb=a=>{if(a instanceof DOMException&&(0,Lb.default)(["Failed to load because no supported source was found.","The element has no supported sources."],a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},Oe=async(a,e)=>{let t=a.muted;try{await a.play()}catch(r){if(!kb(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{await a.play()}catch(i){return kb(i)&&(a.muted=!1,console.warn(i)),!1}}return!0};var Ge=require("@vkontakte/videoplayer-shared/es2018");var Rb=U(ei(),1),vt=require("@vkontakte/videoplayer-shared/es2018");function ye(){return(0,vt.now)()}function Cu(a){return ye()-a}function Vu(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,i=n=>r.test(n);return{resolve:(n,o,u=!1)=>{i(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function $b(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function ti(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",f=7e3,g=2e3,S=()=>{if(u)return;(0,vt.assertNonNullable)(c);let C=Cu(c),_;if(C<g){_=g-C,setTimeout(S,_);return}g*=2,g>f&&(g=f),n&&n.abort(),n=new i,Q()},I=C=>(s=C,Z),x=C=>(d=C,Z),E=()=>(h="json",Z),A=()=>{if(!u){if(--l>=0){S(),r&&r();return}u=!0,d&&d(),t&&t()}},w=C=>(p=C,Z),Q=()=>{c=ye(),n=new i,n.open("get",a);let C=0,_,ie=0,me=()=>((0,vt.assertNonNullable)(c),Math.max(c,Math.max(_||0,ie||0)));if(s&&n.addEventListener("progress",L=>{let P=ye();s.updateChunk&&L.loaded>C&&(s.updateChunk(me(),L.loaded-C),C=L.loaded,_=P)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>A())),n.addEventListener("load",()=>{if(u)return;(0,vt.assertNonNullable)(n);let L=n.status;if(L>=200&&L<300){let{response:P,responseType:q}=n,ee=P==null?void 0:P.byteLength;if(typeof ee=="number"&&s){let Y=ee-C;Y&&s.updateChunk&&s.updateChunk(me(),Y)}q==="json"&&(!P||!(0,Rb.default)(P).length)?A():(d&&d(),e(P))}else A()}),n.addEventListener("error",()=>{A()}),p){let L=()=>{(0,vt.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ie=ye(),n.removeEventListener("readystatechange",L))};n.addEventListener("readystatechange",L)}return n.responseType=h,n.send(),Z},Z={withBitrateReporting:I,withParallel:w,withJSONResponse:E,withRetryCount:C=>(l=C,Z),withRetryInterval:(C,_)=>((0,vt.isNonNullable)(C)&&(g=C),(0,vt.isNonNullable)(_)&&(f=_),Z),withTimeout:C=>(o=C,Z),withFinally:x,send:Q,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return Z}var Yi=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,i=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,i+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;i+=u,s.start=t,s.bytes-=u}}}if(i>0&&r>0){let s=i*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Mb=U(ei(),1);var zi=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=ye(),i=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=ye()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=ti(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ye()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=ye();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,Mb.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,i){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=i,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=i,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var Cb=require("@vkontakte/videoplayer-shared/es2018");var Ys=1e4,Bu=3;var jA=6e4,QA=10,GA=1,WA=500,Ki=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.soundProhibitedEvent$=new Cb.Subject,this.chunkRateEstimator=new Yi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Vu(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Vu(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)==null?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,i;r!==0&&(i=t.buffered.start(r-1),t.currentTime<i&&(e("Fixup stall"),t.currentTime=i))}_selectQuality(e){let{videoElement:t}=this.params,r,i,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){s=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!Tb({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Db.default)(this.manifest,-1).video.height})&&(u&&s.video.height>u||l&&s.video.height<l)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!i||s.bitrate>i.bitrate)&&(i=s):(!r||r.bitrate>s.bitrate)&&(r=s))}return i||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,Ge.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:i,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{$b(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new zi(Bu,Ys,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let A=s&&(!c||c===this.rep);return A||t("Not running!"),A},p=(A,w,Q)=>{u&&u.abort(),u=ti(this.urlResolver.resolve(A,!1),w,Q,()=>this._retryCallback()).withTimeout(Ys).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Bu).withFinally(()=>{u=null}).send()},h=(A,w,Q)=>{(0,Ge.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(A,!1),w,Q,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=A=>{let w=r.playbackRate;r.playbackRate!==A&&(t(`Playback rate switch: ${w}=>${A}`),r.playbackRate=A)},g=A=>{this.lowLatency=A,t(`lowLatency changed to ${A}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let A=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let Q=ye()-1e4,F=0;for(let W=0;W<this.bufferStates.length;W++){let J=this.bufferStates[W];A=Math.min(A,J.buf),J.ts<Q&&F++}this.bufferStates.splice(0,F),t(`update playback rate; minBuffer=${A} drop=${F} jitter=${this.sourceJitter}`);let re=A-GA;this.sourceJitter>=0?re-=this.sourceJitter/2:this.sourceJitter-=1,re>3?f(1.15):re>1?f(1.1):re>.3?f(1.05):f(1)}},I=A=>{let w,Q=()=>w&&w.start?w.start.length:0,F=L=>w.start[L]/1e3,re=L=>w.dur[L]/1e3,W=L=>w.fragIndex+L,J=(L,P)=>({chunkIdx:W(L),startTS:F(L),dur:re(L),discontinuity:P}),Z=()=>{let L=0;if(w&&w.dur){let P=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,q=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ee=P;this.sourceJitter>1&&(ee+=this.sourceJitter-1);let Y=w.dur.length-1;for(;Y>=0&&(ee-=w.dur[Y],!(ee<=0));--Y);L=Math.min(Y,w.dur.length-1-q),L=Math.max(L,0)}return J(L,!0)},C=L=>{let P=Q();if(!(P<=0)){if((0,Ge.isNonNullable)(L)){for(let q=0;q<P;q++)if(F(q)>L)return J(q)}return Z()}},_=L=>{let P=Q(),q=L?L.chunkIdx+1:0,ee=q-w.fragIndex;if(!(P<=0)){if(!L||ee<0||ee-P>QA)return t(`Resync: offset=${ee} bChunks=${P} chunk=`+JSON.stringify(L)),Z();if(!(ee>=P))return J(q-w.fragIndex,!1)}},ie=(L,P,q)=>{l&&l.abort(),l=ti(this.urlResolver.resolve(L,!0,this.lowLatency),P,q,()=>this._retryCallback()).withTimeout(Ys).withRetryCount(Bu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(L,P)=>{ie(A,q=>{if(!d())return;w=q;let ee=!!w.lowLatency;ee!==this.lowLatency&&g(ee);let Y=0;for(let qe=0;qe<w.dur.length;++qe)Y+=w.dur[qe];Y>0&&((0,Ge.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Y/w.dur.length)),i({name:"index",zeroTime:w.zeroTime,shiftDuration:w.shiftDuration}),this.sourceJitter=w.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,w.jitter/1e3)):1,L(C(P))},()=>this._handleNetworkError())},nextChunk:_}},x=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),(0,Ge.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:A=>{let{videoElement:w,logger:Q}=this.params,F=I(e.jidxUrl),re,W,J,Z,C=0,_,ie,me,L=()=>{_&&(clearTimeout(_),_=void 0);let te=Math.max(WA,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Te=C+te,we=ye(),Ae=Math.min(1e4,Te-we);C=we;let Bt=()=>{l||d()&&F.seek(()=>{d()&&(C=ye(),P(),L())})};Ae>0?_=window.setTimeout(()=>{this.paused?L():Bt()},Ae):Bt()},P=()=>{let te;for(;te=F.nextChunk(Z);)Z=te,di(te);let Te=F.nextChunk(J);if(Te){if(J&&Te.discontinuity){Q("Detected discontinuity; restarting playback"),this.paused?L():(x(),this._initPlayerWith(e));return}qe(Te)}else L()},q=(te,Te)=>{if(!d()||!this.sourceBuffer)return;let we,Ae,Bt,Ar=Ot=>{window.setTimeout(()=>{d()&&q(te,Te)},Ot)};if(this.sourceBuffer.updating)Q("Source buffer is updating; delaying appendBuffer"),Ar(100);else{let Ot=ye(),rr=w.currentTime;!this.paused&&w.buffered.length>1&&ie===rr&&Ot-me>500&&(Q("Stall suspected; trying to fix"),this._fixupStall()),ie!==rr&&(ie=rr,me=Ot);let kr=this._getBufferSizeSec();if(kr>30)Q(`Buffered ${kr} seconds; delaying appendBuffer`),Ar(2e3);else try{this.sourceBuffer.appendBuffer(te),this.videoPlayStarted?(this.bufferStates.push({ts:Ot,buf:kr}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Te&&Te()}catch(pi){if(pi.name==="QuotaExceededError")Q("QuotaExceededError; delaying appendBuffer"),Bt=this.sourceBuffer.buffered.length,Bt!==0&&(we=this.sourceBuffer.buffered.start(0),Ae=rr,Ae-we>4&&this.sourceBuffer.remove(we,Ae-3)),Ar(1e3);else throw pi}}},ee=()=>{W&&re&&(Q([`Appending chunk, sz=${W.byteLength}:`,JSON.stringify(J)]),q(W,function(){W=null,P()}))},Y=te=>e.fragUrlTemplate.replace("%%id%%",te.chunkIdx),qe=te=>{d()&&h(Y(te),(Te,we)=>{if(d()){if(we/=1e3,W=Te,J=te,n=te.startTS,we){let Ae=Math.min(10,te.dur/we);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ae:Ae}ee()}},()=>this._handleNetworkError())},di=te=>{d()&&((0,Ge.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Y(te),!1)))},wr=te=>{d()&&(e.cachedHeader=te,q(te,()=>{re=!0,ee()}))};s=!0,F.seek(te=>{if(d()){if(C=ye(),!te){L();return}Z=te,!(0,Ge.isNullable)(A)||te.startTS>A?qe(te):(J=te,P())}},A),e.cachedHeader?wr(e.cachedHeader):p(e.headerUrl,wr,()=>this._handleNetworkError())},stop:x,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),(0,Ge.isNonNullable)(i)&&(i+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,(0,Ge.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,Ge.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),f=d/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let f=ye();if(this.chunkRateEstimator.addInterval(p,f,h)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:S}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Cu(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=ye();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=ti(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Ys).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;Oe(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{var c,d;u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&((d=(c=window.MediaSource)==null?void 0:c.isTypeSupported)!=null&&d.call(c,u.codecs))&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},jA))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Vb=U(jr(),1),ce=require("@vkontakte/videoplayer-shared/es2018"),Ou=class{constructor(){this.onDroopedVideoFramesLimit$=new ce.Subject;this.subscription=new ce.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new ce.Subject;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!(0,ce.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,i=t-this.prevDroppedVideoFrames,s=1-(r-i)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&(0,ce.isHigher)(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add((0,ce.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,ce.interval)(this.droppedFramesChecker.checkTime).pipe((0,ce.filter)(()=>this.playing),(0,ce.filter)(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe((0,ce.debounce)(this.droppedFramesChecker.checkTime)),r=(0,ce.merge)(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var r,i;let t=(i=(r=(0,Vb.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>(0,ce.isLower)(s,n)?-1:1))==null?void 0:r[0])==null?void 0:i[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},zs=Ou;var Ks=require("@vkontakte/videoplayer-shared/es2018"),Bb=require("@vkontakte/videoplayer-shared/es2018");var Xi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var YA=(a,e)=>new Ks.Observable(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Xi()))},{...r,...e});i.observe(a);let s=(0,Bb.fromEvent)(document,"visibilitychange").pipe((0,Ks.map)(n=>!document.hidden||Xi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Xe=YA;var zA=["paused","playing","ready"],KA=["paused","playing","ready"],Ji=class{constructor(e){this.subscription=new D.Subscription;this.videoState=new H("stopped");this.representations$=new D.ValueSubject([]);this.droppedFramesManager=new zs;this.maxSeekBackTime$=new D.ValueSubject(1/0);this.zeroTime$=new D.ValueSubject(void 0);this.liveOffset=new vr;this._dashCb=e=>{var t,r,i,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:D.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(r=zt(u.name))!=null?r:(0,D.videoSizeToQuality)(u.video),d=u.bitrate/1e3,p={...u.video};if(!c)continue;let h={id:l,quality:c,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),(0,D.isNonNullable)(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,_u.default)(KA,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,_u.default)(zA,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(xe(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=i==null?void 0:i.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(xe(this.params.source.url,u))}return;default:return(0,D.assertNever)(e)}};this.textTracksManager=new Ke(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:D.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:i})};(0,D.merge)(this.videoState.stateChangeStarted$.pipe((0,D.map)(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,D.map)(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=De(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Se(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=Be(this.video);this.subscription.add(this.representations$.pipe((0,D.map)(i=>i.map(({track:s})=>s)),(0,D.filter)(i=>!!i.length),(0,D.once)()).subscribe(i=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:i}))),this.subscription.add(r.canplay$.subscribe(()=>{var i;((i=this.videoState.getTransition())==null?void 0:i.to)==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((0,D.filterChanged)(),(0,D.map)(i=>-i/1e3)).subscribe(this.params.output.duration$)).add((0,D.combine)({zeroTime:this.zeroTime$.pipe((0,D.filter)(D.isNonNullable)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(gt(this.video,this.params.desiredState.isLooped,t)).add(Ve(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(ze(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Xe(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i,min:s}})=>{this.dash.setAutoQualityLimits({max:i&&(0,D.videoQualityToHeight)(i),min:s&&(0,D.videoQualityToHeight)(s)}),this.params.output.autoVideoTrackLimits$.next({max:i,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(i=>{var s;switch(i.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return(0,D.assertNever)(i.to)}},t)).add((0,D.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,D.observableFrom)(["init"])).pipe((0,D.debounce)(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Ce(this.video)}createLiveDashPlayer(){let e=new Ki({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,p,h,f;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&(0,D.isNonNullable)(t)?t:Jt(e.map(({track:g})=>g),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=i==null?void 0:i.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let g=(f=e.find(({track:S})=>S.id===s))==null?void 0:f.representation;(0,D.assertNonNullable)(g,"Representations missing"),this.dash.startPlay(g,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:i})=>i.id===e.id))==null?void 0:r.representation;(0,D.assertNonNullable)(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(xe(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var Ob=Ji;var nS=U(ot(),1);var St=(a,e)=>{let t=0;for(let r=0;r<a.length;r++){let i=a.start(r)*1e3,s=a.end(r)*1e3;i<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var O=require("@vkontakte/videoplayer-shared/es2018");var Xs=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},ri=class extends Xs{constructor(){super(),this.listeners||Xs.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},Zi=class{constructor(){Object.defineProperty(this,"signal",{value:new ri,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(i){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Zi.prototype[Symbol.toStringTag]="AbortController",ri.prototype[Symbol.toStringTag]="AbortSignal");function Js(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function Nu(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!Js({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var ea=Js({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),_b=ea?Nu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,lt=ea?_b.fetch:window.fetch,ZC=ea?_b.Request:window.Request,Pe=ea?Zi:window.AbortController,eV=ea?ri:window.AbortSignal;var fl=U(qu(),1);var un=U(Kt(),1);var Lt=()=>window.ManagedMediaSource||window.MediaSource,Zs=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},ag=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},sg=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var yt=require("@vkontakte/videoplayer-shared/es2018"),Je=document.createElement("video"),Tk='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Ik='video/mp4; codecs="hev1.1.6.L93.B0"',bg='video/webm; codecs="vp09.00.10.08"',gg='video/webm; codecs="av01.0.00M.08"',Ek='audio/mp4; codecs="mp4a.40.2"',xk='audio/webm; codecs="opus"',ng,og,ta={mms:Zs(),mse:ag(),hls:!!((ng=Je.canPlayType)!=null&&ng.call(Je,"application/x-mpegurl")||(og=Je.canPlayType)!=null&&og.call(Je,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},ug,lg,_e={mp4:!!((ug=Je.canPlayType)!=null&&ug.call(Je,"video/mp4")),webm:!!((lg=Je.canPlayType)!=null&&lg.call(Je,"video/webm")),cmaf:!0},tn,cg,rn,dg,an,pg,sn,hg,nn,mg,on,fg,Ne={h264:!!((cg=(tn=Lt())==null?void 0:tn.isTypeSupported)!=null&&cg.call(tn,Tk)),h265:!!((dg=(rn=Lt())==null?void 0:rn.isTypeSupported)!=null&&dg.call(rn,Ik)),vp9:!!((pg=(an=Lt())==null?void 0:an.isTypeSupported)!=null&&pg.call(an,bg)),av1:!!((hg=(sn=Lt())==null?void 0:sn.isTypeSupported)!=null&&hg.call(sn,gg)),aac:!!((mg=(nn=Lt())==null?void 0:nn.isTypeSupported)!=null&&mg.call(nn,Ek)),opus:!!((fg=(on=Lt())==null?void 0:on.isTypeSupported)!=null&&fg.call(on,xk))},ii=(Ne.h264||Ne.h265)&&Ne.aac,Sr,Pk=async()=>{if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:gg}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:bg}})]);Sr={DASH_WEBM_AV1:e,DASH_WEBM:t}};Pk().catch(a=>{console.error(a)});var ai=ta.hls&&_e.mp4,vg=()=>Object.keys(Ne).filter(a=>Ne[a]),Sg=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let i=ta.mse&&(!r||!!window.MediaStreamTrack)||ta.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return i&&_e.mp4&ⅈcase"DASH_WEBM":return i&&_e.webm&&Ne.vp9&&Ne.opus;case"DASH_WEBM_AV1":return i&&_e.webm&&Ne.av1&&Ne.opus;case"DASH_STREAMS":return i&&(_e.mp4&&ii||_e.webm&&(Ne.vp9||Ne.av1)&&(Ne.opus||Ne.aac));case"DASH_LIVE":return i&&_e.mp4&ⅈcase"DASH_LIVE_CMAF":return i&&_e.mp4&&ii&&_e.cmaf;case"DASH_ONDEMAND":return i&&_e.mp4&ⅈcase"HLS":case"HLS_ONDEMAND":return ai||e&&i&&_e.mp4&ⅈcase"HLS_LIVE":case"HLS_LIVE_CMAF":return ai;case"MPEG":return _e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return ta.webrtc&&ta.ws&&Ne.h264&&(_e.mp4||_e.webm);default:return(0,yt.assertNever)(s)}})},en=a=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(a){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return Sr?Sr[t].smooth?[t,e]:Sr[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Sr?Sr[t].powerEfficient?[t,e]:Sr[e].powerEfficient?[e,t]:[t,e]:[e,t];default:(0,yt.assertNever)(a)}return[e,t]},yg=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...en(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(yt.clientChecker.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[...i,"MPEG",...en(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...en(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...en(a),...i,"HLS","HLS_ONDEMAND"];default:(0,yt.assertNever)(e)}return ai?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Tg=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],i=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...i],n=[...i,...r],o,u=yt.clientChecker.isMac&&yt.clientChecker.isSafari;if(yt.clientChecker.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,yt.assertNever)(a)}else ai&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Uu=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Ig=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,un.default)(t.value.split("."),0)}for(let t of a){let r=(0,un.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,un.default)(e.value.split("."),0)};var Hg=U(Ug(),1),si=require("@vkontakte/videoplayer-shared/es2018"),jg=a=>{if(!a)return{id:"EmptyResponse",category:si.ErrorCategory.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:si.ErrorCategory.NETWORK,message:`UV Error ${a}`};let e=(0,Hg.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:si.ErrorCategory.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:si.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:si.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var Zt=(a,e,t=0)=>{for(let r=0;r<a.length;r++)if(a.start(r)*1e3-t<=e&&a.end(r)*1e3+t>e)return!0;return!1};var v=require("@vkontakte/videoplayer-shared/es2018");var ln=U(ot(),1),ui=U(Kt(),1),cn=U(qu(),1);var Uk=(a,e={})=>{let r=e.timeout||1,i=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-i-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-i))}})},1)},Hk=a=>window.clearTimeout(a),Qg=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),Gg=!Qg(window.requestIdleCallback)||!Qg(window.cancelIdleCallback),Wu=Gg?Uk:window.requestIdleCallback,ia=Gg?Hk:window.cancelIdleCallback;var Jv=U(Us(),1);var Ze=require("@vkontakte/videoplayer-shared/es2018"),jk=18,Wg=!1;try{Wg=Ze.clientChecker.isSafari&&!!Ze.clientChecker.macVersion&&Ze.clientChecker.macVersion<=jk}catch(a){console.error(a)}var Yu=class{constructor(e){this.bufferFull$=new Ze.Subject;this.error$=new Ze.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!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.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Ze.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})}async remove(e,t,r){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let r,i=s=>{this.abortRequested=!1,t(s)};Wg&&e?r={operation:"safariAbort",init:e,callback:i}:r={operation:"abort",callback:i};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,r&&(this.queue=[r]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var i;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((i=e.signal)!=null&&i.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:Ze.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,Ze.assertNever)(t)}}},Yg=Yu;var zu=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};var T=require("@vkontakte/videoplayer-shared/es2018");var z=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let i=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,i)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}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 ni=class extends z{};var aa=class extends z{constructor(t,r){super(t,r);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let i=this.content.byteOffset,s=i+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(i,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var sa=class extends z{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let i=this.readString(4);this.compatibleBrands.push(i),r-=4}}};var na=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ne=class extends z{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var oa=class extends ne{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var ua=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var la=class extends z{constructor(e,t){super(e,t),this.data=this.content}};var yr=class extends ne{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,l=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var ca=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var da=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pa=class extends ne{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var ha=class extends ne{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ma=class extends ne{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var fa=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ba=class extends ne{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 ga=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var va=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Sa=class extends ne{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ya=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ta=class extends ne{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 Ia=class extends ne{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Ea=class extends ne{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)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 xa=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Pa=class extends ne{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var wa=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var Gk={ftyp:sa,moov:na,mvhd:oa,moof:ua,mdat:la,sidx:yr,trak:ca,mdia:fa,mfhd:Sa,tkhd:ba,traf:ya,tfhd:Ta,tfdt:Ia,trun:Ea,minf:ga,sv3d:da,st3d:pa,prhd:ha,proj:va,equi:ma,uuid:aa,stbl:xa,stsd:Pa,avc1:wa,unknown:ni},Rt=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=Gk[e];return r?new r(t,new a):new ni(t,new a)}};var er=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),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 Yk=new TextDecoder("ascii"),zk=a=>Yk.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",Kk=a=>{let e=new yr(a,new Rt),t=e.earliestPresentationTime/e.timescale*1e3,r=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:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},Xk=(a,e)=>{let r=new Rt().parse(a),i=new er(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},Jk=a=>{let t=new Rt().parse(a),r=new er(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},Zk=a=>{var i;let t=new Rt().parse(a);return(i=new er(t).find("sidx"))==null?void 0:i.timescale},eL=(a,e)=>{let r=new Rt().parse(a),s=new er(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},tL=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}}},r=new Rt().parse(a),i=new er(r);if(i.find("sv3d")){e.is3dVideo=!0;let n=i.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=i.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=i.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},zg={validateData:zk,parseInit:tL,getIndexRange:()=>{},parseSegments:Kk,parseFeedableSegmentChunk:Xk,getChunkEndTime:eL,getServerLatencyTimestamps:Jk,getTimescaleFromIndex:Zk};var ka=U(ot(),1),$t=require("@vkontakte/videoplayer-shared/es2018");var Xg=require("@vkontakte/videoplayer-shared/es2018");var Kg={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"}},Jg=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 r=Aa(a,t),i=r in Kg,s=i?Kg[r].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),l=n&255>>o,c=Aa(u),d=l*2**((o-1)*8)+c,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},Aa=(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},ct=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Aa(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,Xg.assertNever)(e)}},Tr=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=Jg(r);if(!e(i))return;i.type==="master"&&Tr(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},Zg=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=Jg(a);return Tr(i.value,({tag:s,type:n,value:o})=>(s===17143?e=ct(o,n):s===17026?t=ct(o,n):s===17029&&(r=ct(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var ev=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],rL=[231,22612,22743,167,171,163,160,175],iL=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return Tr(a,({tag:p,type:h,value:f,valueSize:g})=>{if(p===21419){let S=ct(f,h);l=Aa(S)}else p!==21420&&(l=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+g):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=ct(f,h):p===17545?i=ct(f,h):p===21420&&l===475249515?u=ct(f,h):p===374648427?Tr(f,({tag:S,type:I,value:x})=>S===30321?(c=ct(x,I)===1,!1):!0):s&&n&&(0,ka.default)(ev,p)&&(o=!0),!o}),(0,$t.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,$t.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,$t.assertNonNullable)(i,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},aL=a=>{if((0,$t.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},sL=(a,e)=>{let t=!1,r=!1,i=o=>(0,$t.isNonNullable)(o.time)&&(0,$t.isNonNullable)(o.position),s=[],n;return Tr(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=ct(l,u));break;case 183:break;case 241:n&&(n.position=ct(l,u));break;default:t&&(0,ka.default)(ev,o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},nL=a=>{let e=0,t=!1;try{Tr(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,ka.default)(rL,r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=(0,ka.default)([163,160,175],r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},tv={validateData:Zg,parseInit:iL,getIndexRange:aL,parseSegments:sL,parseFeedableSegmentChunk:nL};var La=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return tv;case"mp4":return zg}}throw new ReferenceError(`Unsupported mime type ${a}`)};var ul=U(Tv(),1),Wv=U(jr(),1),Yv=U(Ov(),1),zv=U(Kt(),1),ll=U(ei(),1);var _v=U(ot(),1),rl=a=>{let e=a.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[i,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[i,s,n]=r;return!!(i&&parseInt(i,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let i=r[0];if(!i||i.length!==6)return!1;let[s,n]=i.toUpperCase(),o=s+n;return(0,_v.default)(["6E","7A","F4"],o)}}return!1};var $a=require("@vkontakte/videoplayer-shared/es2018");var Nv=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Fv=a=>{var e;try{let t=tR(),r=a.match(t),{groups:i}=r!=null?r:{};if(i){let s={};if(i.extensions){let u=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=i.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function tR(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
|
|
64
64
|
(?<language>${`(?:[a-z]{2,3}(?:-${a})?|[a-z]{4}|[a-z]{5,8})`})
|
|
65
65
|
(-(?<script>[a-z]{4}))?
|
|
66
66
|
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
67
67
|
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
68
68
|
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
69
69
|
(?:-(?<privateuse>(?:${e})))?
|
|
70
|
-
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var sl=U(Kt(),1);var Ov=require("@vkontakte/videoplayer-shared/es2018"),_v=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s,streamId:n})=>{var u;let o=(u=s?zt(s):void 0)!=null?u:(0,Ov.videoSizeToQuality)({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},Nv=({id:a,bitrate:e})=>({id:a,bitrate:e}),Fv=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),qv=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),nl=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,sl.default)(r.split("."),0),isDefault:i}),ol=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,sl.default)(i.split("."),0)}),ul=a=>"url"in a,Re=a=>a.type==="template",Ra=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Uv=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},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),i=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],i),hours:e(r==null?void 0:r[6],i),minutes:e(r==null?void 0:r[7],i),seconds:e(r==null?void 0:r[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},Mt=(a,e)=>{let t=a;t=(0,ll.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of(0,Hv.default)(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,ll.default)(t,n,(o,u)=>(0,$a.isNullable)(s)?o:(0,$a.isNullable)(u)?s:(0,jv.default)(s,parseInt(u,10),"0"))}return t},Gv=(a,e)=>{var w,Q,F,re,W,J,Z,C,_,ie,he,L,P,q,ee,Y,Fe,di,wr,te,ye,Pe,we,Bt,Ar,Ot,ir,kr,pi,Pl,wl,Al,kl,Ll,Rl,$l,Ml,Dl,Cl,Vl,Bl,Ol,_l,Nl,Fl,ql,Ul,Hl,jl,Ql,Gl,Wl,Yl,zl,Kl,Xl,Jl,Zl,ec,tc,rc;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(et=>{var se,ar;return(ar=(se=et.textContent)==null?void 0:se.trim())!=null?ar:""}),o=(w=(0,Qv.default)(n,0))!=null?w:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=l?new Date(l).getTime():void 0,d,p=s.getAttribute("mediaPresentationDuration"),h=s.getElementsByTagName("vk:Attrs")[0],f=h==null?void 0:h.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g=[...s.getElementsByTagName("Period")],S=g.reduce((et,se)=>({...et,[se.id]:se.children}),{}),I=g.reduce((et,se)=>({...et,[se.id]:se.getAttribute("duration")}),{});p?d=Uv(p):(0,cl.default)(I).filter(et=>et).length&&!u?d=(0,cl.default)(I).reduce((et,se)=>{var ar;return et+((ar=Uv(se))!=null?ar:0)},0):f&&(d=parseInt(f,10));let E=0,x=(F=(Q=s.getAttribute("profiles"))==null?void 0:Q.split(","))!=null?F:[];for(let et of g.map(se=>se.id))for(let se of S[et]){let ar=(re=se.getAttribute("id"))!=null?re:"id"+(E++).toString(10),hi=(W=se.getAttribute("mimeType"))!=null?W:"",An=(J=se.getAttribute("codecs"))!=null?J:"",kn=(Z=se.getAttribute("contentType"))!=null?Z:hi==null?void 0:hi.split("/")[0],AS=(_=(C=se.getAttribute("profiles"))==null?void 0:C.split(","))!=null?_:[],ic=(he=Bv((ie=se.getAttribute("lang"))!=null?ie:""))!=null?he:{},za=(q=(P=(L=se.querySelector("Label"))==null?void 0:L.textContent)==null?void 0:P.trim())!=null?q:void 0,kS=se.querySelectorAll("Representation"),LS=se.querySelector("SegmentTemplate"),RS=(Y=(ee=se.querySelector("Role"))==null?void 0:ee.getAttribute("value"))!=null?Y:void 0,Lr=kn,de={id:ar,language:ic.language,isDefault:RS==="main",label:za,codecs:An,hdr:Lr==="video"&&il(An),mime:hi,representations:[]};for(let ae of kS){let _t=(Fe=ae.getAttribute("lang"))!=null?Fe:void 0,mi=(wr=(di=za!=null?za:se.getAttribute("label"))!=null?di:ae.getAttribute("label"))!=null?wr:void 0,Ka=(Pe=(ye=(te=ae.querySelector("BaseURL"))==null?void 0:te.textContent)==null?void 0:ye.trim())!=null?Pe:"",sr=new URL(Ka||o,e).toString(),Nt=(we=ae.getAttribute("mimeType"))!=null?we:hi,Xa=(Ar=(Bt=ae.getAttribute("codecs"))!=null?Bt:An)!=null?Ar:"",Ja;if(kn==="text"){let Ft=ae.getAttribute("id")||"",Za=((Ot=ic.privateuse)==null?void 0:Ot.includes("x-auto"))||Ft.includes("_auto"),nr=ae.querySelector("SegmentTemplate");if(nr){let fi={representationId:(ir=ae.getAttribute("id"))!=null?ir:void 0,bandwidth:(kr=ae.getAttribute("bandwidth"))!=null?kr:void 0},es=parseInt((pi=ae.getAttribute("bandwidth"))!=null?pi:"",10)/1e3,ts=(wl=parseInt((Pl=nr.getAttribute("startNumber"))!=null?Pl:"",10))!=null?wl:1,Rr=parseInt((Al=nr.getAttribute("timescale"))!=null?Al:"",10),Ln=(kl=nr.querySelectorAll("SegmentTimeline S"))!=null?kl:[],$r=nr.getAttribute("media");if(!$r)continue;let rs=[],is=0,as="",Mr=0,bi=ts,Ae=0;for(let tt of Ln){let or=parseInt((Ll=tt.getAttribute("d"))!=null?Ll:"",10),We=parseInt((Rl=tt.getAttribute("r"))!=null?Rl:"",10)||0,qt=parseInt(($l=tt.getAttribute("t"))!=null?$l:"",10);Ae=Number.isFinite(qt)?qt:Ae;let ur=or/Rr*1e3,Ut=Ae/Rr*1e3;for(let dt=0;dt<We+1;dt++){let Ht=Mt($r,{...fi,segmentNumber:bi.toString(10),segmentTime:(Ae+dt*or).toString(10)}),Dr=(Ut!=null?Ut:0)+dt*ur,vi=Dr+ur;bi++,rs.push({time:{from:Dr,to:vi},url:Ht})}Ae+=(We+1)*or,is+=(We+1)*ur}Mr=Ae/Rr*1e3,as=Mt($r,{...fi,segmentNumber:bi.toString(10),segmentTime:Ae.toString(10)});let gi={time:{from:Mr,to:1/0},url:as},Tt={type:"template",baseUrl:sr,segmentTemplateUrl:$r,initUrl:"",totalSegmentsDurationMs:is,segments:rs,nextSegmentBeyondManifest:gi,timescale:Rr};Ja={id:Ft,kind:"text",segmentReference:Tt,profiles:[],duration:d,bitrate:es,mime:"",codecs:"",width:0,height:0,isAuto:Za}}else Ja={id:Ft,isAuto:Za,kind:"text",url:sr}}else{let Ft=(Dl=(Ml=ae.getAttribute("contentType"))!=null?Ml:Nt==null?void 0:Nt.split("/")[0])!=null?Dl:kn,Za=(Vl=(Cl=se.getAttribute("profiles"))==null?void 0:Cl.split(","))!=null?Vl:[],nr=parseInt((Bl=ae.getAttribute("width"))!=null?Bl:"",10),fi=parseInt((Ol=ae.getAttribute("height"))!=null?Ol:"",10),es=parseInt((_l=ae.getAttribute("bandwidth"))!=null?_l:"",10)/1e3,ts=(Nl=ae.getAttribute("frameRate"))!=null?Nl:"",Rr=(Fl=ae.getAttribute("quality"))!=null?Fl:void 0,Ln=ts?Vv(ts):void 0,$r=(ql=ae.getAttribute("id"))!=null?ql:"id"+(E++).toString(10),rs=Ft==="video"?`${fi}p`:Ft==="audio"?`${es}Kbps`:Xa,is=`${$r}@${rs}`,as=[...x,...AS,...Za],Mr,bi=ae.querySelector("SegmentBase"),Ae=(Ul=ae.querySelector("SegmentTemplate"))!=null?Ul:LS;if(bi){let Tt=(jl=(Hl=ae.querySelector("SegmentBase Initialization"))==null?void 0:Hl.getAttribute("range"))!=null?jl:"",[tt,or]=Tt.split("-").map(Ht=>parseInt(Ht,10)),We={from:tt,to:or},qt=(Ql=ae.querySelector("SegmentBase"))==null?void 0:Ql.getAttribute("indexRange"),[ur,Ut]=qt?qt.split("-").map(Ht=>parseInt(Ht,10)):[],dt=qt?{from:ur,to:Ut}:void 0;Mr={type:"byteRange",url:sr,initRange:We,indexRange:dt}}else if(Ae){let Tt={representationId:(Gl=ae.getAttribute("id"))!=null?Gl:void 0,bandwidth:(Wl=ae.getAttribute("bandwidth"))!=null?Wl:void 0},tt=parseInt((Yl=Ae.getAttribute("timescale"))!=null?Yl:"",10),or=(zl=Ae.getAttribute("initialization"))!=null?zl:"",We=Ae.getAttribute("media"),qt=(Xl=parseInt((Kl=Ae.getAttribute("startNumber"))!=null?Kl:"",10))!=null?Xl:1,ur=Mt(or,Tt);if(!We)throw new ReferenceError("No media attribute in SegmentTemplate");let Ut=(Jl=Ae.querySelectorAll("SegmentTimeline S"))!=null?Jl:[],dt=[],Ht=0,Dr="",vi=0;if(Ut.length){let ss=qt,rt=0;for(let Cr of Ut){let pt=parseInt((Zl=Cr.getAttribute("d"))!=null?Zl:"",10),lr=parseInt((ec=Cr.getAttribute("r"))!=null?ec:"",10)||0,ns=parseInt((tc=Cr.getAttribute("t"))!=null?tc:"",10);rt=Number.isFinite(ns)?ns:rt;let Rn=pt/tt*1e3,$n=rt/tt*1e3;for(let os=0;os<lr+1;os++){let MS=Mt(We,{...Tt,segmentNumber:ss.toString(10),segmentTime:(rt+os*pt).toString(10)}),ac=($n!=null?$n:0)+os*Rn,DS=ac+Rn;ss++,dt.push({time:{from:ac,to:DS},url:MS})}rt+=(lr+1)*pt,Ht+=(lr+1)*Rn}vi=rt/tt*1e3,Dr=Mt(We,{...Tt,segmentNumber:ss.toString(10),segmentTime:rt.toString(10)})}else if((0,$a.isNonNullable)(d)){let rt=parseInt((rc=Ae.getAttribute("duration"))!=null?rc:"",10)/tt*1e3,Cr=Math.ceil(d/rt),pt=0;for(let lr=1;lr<Cr;lr++){let ns=Mt(We,{...Tt,segmentNumber:lr.toString(10),segmentTime:pt.toString(10)});dt.push({time:{from:pt,to:pt+rt},url:ns}),pt+=rt}vi=pt,Dr=Mt(We,{...Tt,segmentNumber:Cr.toString(10),segmentTime:pt.toString(10)})}let $S={time:{from:vi,to:1/0},url:Dr};Mr={type:"template",baseUrl:sr,segmentTemplateUrl:We,initUrl:ur,totalSegmentsDurationMs:Ht,segments:dt,nextSegmentBeyondManifest:$S,timescale:tt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ft||!Nt)continue;let gi={video:"video",audio:"audio",text:"text"}[Ft];if(!gi)continue;Lr||(Lr=gi),Ja={id:is,kind:gi,segmentReference:Mr,profiles:as,duration:d,bitrate:es,mime:Nt,codecs:Xa,width:nr,height:fi,fps:Ln,quality:Rr}}de.language||(de.language=_t),de.label||(de.label=mi),de.mime||(de.mime=Nt),de.codecs||(de.codecs=Xa),de.hdr||(de.hdr=Lr==="video"&&il(Xa)),de.representations.push(Ja)}if(Lr){let ae=i[Lr].find(_t=>_t.id===de.id);if(ae&&de.representations.every(_t=>Re(_t.segmentReference)))for(let _t of ae.representations){let mi=de.representations.find(Nt=>Nt.id===_t.id),Ka=mi==null?void 0:mi.segmentReference,sr=_t.segmentReference;sr.segments.push(...Ka.segments),sr.nextSegmentBeyondManifest=Ka.nextSegmentBeyondManifest}else i[Lr].push(de)}}return{dynamic:u,liveAvailabilityStartTime:c,duration:d,streams:i,baseUrls:n}};var Wv=U(nt(),1),pl=require("@vkontakte/videoplayer-shared/es2018"),$e=(a,e)=>(0,pl.isNonNullable)(a)&&(0,pl.isNonNullable)(e)&&a.readyState==="open"&&(0,Wv.default)([...a.activeSourceBuffers],e);var Ma=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new T.ValueSubject(0);this.currentLowLatencySegmentLength$=new T.ValueSubject(0);this.currentSegmentLength$=new T.ValueSubject(0);this.onLastSegment$=new T.ValueSubject(!1);this.fullyBuffered$=new T.ValueSubject(!1);this.playingRepresentation$=new T.ValueSubject(void 0);this.playingRepresentationInit$=new T.ValueSubject(void 0);this.error$=new T.Subject;this.gaps=[];this.subscription=new T.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new xe;this.switchAbortController=new xe;this.destroyAbortController=new xe;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,T.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,T.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new jg(this.sourceBuffer),this.subscription.add((0,T.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:T.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add((0,T.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:T.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!$e(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Ku(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=vt(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,T.assertNonNullable)(r,"No init buffer for starting representation"),(0,T.assertNonNullable)(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=(0,T.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);(0,T.assertNonNullable)(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if((0,T.isNullable)(s)||(0,T.isNullable)(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),(0,T.assertNonNullable)(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!$e(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,T.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,T.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);(0,T.assertNonNullable)(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if((0,T.isNullable)(s)||(0,T.isNullable)(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),(0,T.assertNonNullable)(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!$e(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,T.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=(0,T.abortable)(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,dn.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(f=>f.id===c);d&&this.representations.set(c,d);let p=this.representations.get(c);if(!p||!Re(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let r=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,i=this.representations.get(r);(0,T.assertNonNullable)(i);let s=this.segments.get(r);(0,T.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(r);if((0,T.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))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,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var c;this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new xe,(0,T.abortable)(this.switchAbortController.signal,async function*(r,i=!1){this.switchingToRepresentationId=r;let s=this.representations.get(r);(0,T.assertNonNullable)(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if((0,T.isNullable)(o)||(0,T.isNullable)(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),(0,T.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!$e(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),i)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=r,yield this.dropBuffer();else{let u=this.getCurrentPosition();(0,T.isNonNullable)(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=r,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!(0,T.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 xe,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,T.isNullable)(e)||(0,T.isNullable)(this.downloadingRepresentationId)||(0,T.isNullable)(this.playingRepresentationId)||(0,T.isNullable)(this.sourceBuffer)||!$e(this.mediaSource,this.sourceBuffer)||(0,T.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if((0,T.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(l=>e>=l.time.from&&e<l.time.to);(0,T.isNonNullable)(i)&&isFinite(i.time.from)&&isFinite(i.time.to)&&this.currentSegmentLength$.next((i==null?void 0:i.time.to)-i.time.from);let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=vt(this.sourceBuffer.buffered,e),d=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=i.time.to-e+100&&(s=d)}if(isFinite(this.bufferLimit)&&Ku(this.sourceBuffer.buffered)>=this.bufferLimit){let l=vt(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")});return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if((0,cn.default)(o,i))l="high";else{let c=(0,ui.default)(o,0);c&&c.time.from-i.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&vt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,ui.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let r=0,i=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+i}),r=s.time.to;(0,T.isNonNullable)(t.duration)&&t.duration-r>0&&!this.isLive&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=(0,dn.default)(e==null?void 0:e.streams[this.kind],i=>i.representations).find(i=>i.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var r,i,s,n;let t=(r=(0,dn.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?r:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!Re(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>({...h,status:"none",size:void 0})),l=100,c=(i=this.segments.get(o.id))!=null?i:[],d=(n=(s=(0,ui.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,p=u==null?void 0:u.findIndex(h=>d>=h.time.from+l&&d<=h.time.to+l);if(p===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(p+1);this.segments.set(o.id,[...c,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,T.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){var r;let t=0;for(let i of this.representations.values()){let s=i.segmentReference;if(!Re(s))return;let n=(r=this.segments.get(i.id))!=null?r:[],o=n.find(l=>Math.floor(l.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(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*s.timescale/1e3).toString(10),c=Mt(s.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}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 r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.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&&ia&&ia(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&ia&&ia(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,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:p,to:h}},f)=>{let g=p<=r&&h>=r,S=p>r||g||f===0&&r===0,I=Math.min(this.forwardBufferTarget,this.bufferLimit),E=this.preloadOnly&&p<=r+I||h<=r+I;return(d==="none"||d==="partially_ejected"&&S&&E&&this.sourceBuffer&&$e(this.mediaSource,this.sourceBuffer)&&!(Zt(this.sourceBuffer.buffered,p)&&Zt(this.sourceBuffer.buffered,h)))&&S&&E});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=l||o<=c);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,r="auto"){Re(t.segmentReference)?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await(0,T.abortable)(o,async function*(){let c=(0,T.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=(0,T.now)(),!c)return;let d=new DataView(c),p=La(t.mime);if(!isFinite(i.segment.time.to)){let g=t.segmentReference.timescale;i.segment.time.to=p.getChunkEndTime(d,g)}u&&i.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=p.getServerLatencyTimestamps(d);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Ra(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Re(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,r="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:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await(0,T.abortable)(n,async function*(){let u=(0,T.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,T.fromEvent)(window,"online").pipe((0,T.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=(0,T.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ra(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Re(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,ui.default)(e,0).byte.from,to:(0,ui.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,T.now)(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Re(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,T.now)();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,cn.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){i();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=La(n.mime).parseFeedableSegmentChunk(l,this.isLive);c!=null&&c.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){await n();continue}let c=l.byte.from-r,d=l.byte.to-r,p=d-c+1,h=c<i,f=d<=i;if(!h)continue;let g=La(o.mime);if(l.status==="downloading"&&f){l.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+c,p);await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,i-c),u.loadedBytes>u.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),I=u.loadedBytes===p?S:g.parseFeedableSegmentChunk(S);I!=null&&I.byteLength&&(l.status="partially_fed",u.feedingBytes+=I.byteLength,await this.sourceBufferTaskQueue.append(I,s)&&!s.aborted?(u.fedBytes+=I.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var r;if(!((0,T.isNullable)(this.sourceBuffer)||!$e(this.mediaSource,this.sourceBuffer))){!this.isLive&&T.clientChecker.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Zt(this.sourceBuffer.buffered,e.segment.time.from,100)&&Zt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",ul(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let s of(r=this.segments.get(i.id))!=null?r:[])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[i,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=Yu(()=>(0,Yv.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",r=!1){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?(0,T.abortable)(this.destroyAbortController.signal,async function*(){let o=(0,T.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,La(e.mime),i)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&Re(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:T.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,r=!1){if(!this.sourceBuffer||!$e(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,T.isNullable)(e))return!1;let i=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:p}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,p):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push({...u.time}),i=n(i);let l=ul(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)(0,cn.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return i.length?(await Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!$e(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||!$e(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(){let e=this.getCurrentPosition();return!this.sourceBuffer||!$e(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,T.isNullable)(e)?0:vt(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!$e(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!$e(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=Yu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:T.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,T.isNullable)(this.sourceBuffer)||!$e(this.mediaSource,this.sourceBuffer)||(0,T.isNullable)(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=100;for(let r of this.segments.values())for(let i of r){let{status:s}=i;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(i.time.from),o=Math.ceil(i.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?i.status="partially_ejected":this.gaps.some(c=>c.from===i.time.from||c.to===i.time.to)?i.status="partially_ejected":i.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:T.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Da=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var zv=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,i=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:i}};var K=require("@vkontakte/videoplayer-shared/es2018");var Kv=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var pn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new K.ValueSubject(void 0);this.lastConnectionReused$=new K.ValueSubject(void 0);this.lastRequestFirstBytes$=new K.ValueSubject(void 0);this.abortAllController=new xe;this.subscription=new K.Subscription;this.fetchManifest=(0,K.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Da(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=Kv(r));let i=yield ut(r,{signal:this.abortAllController.signal}).catch(Ca);return i?(t.log("success",(0,K.flattenObject)({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",(0,K.flattenObject)({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,K.abortable)(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var Z,C;let l=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{c.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let _=new URL(l,location.href);_.searchParams.append("bytes",`${r.from}-${r.to}`),l=_.toString();break}default:(0,K.assertNever)(t)}this.requestQuic&&(l=Da(l));let p=this.abortAllController.signal,h;if(n){let _=new xe;if(h=(0,K.merge)((0,K.fromEvent)(this.abortAllController.signal,"abort"),(0,K.fromEvent)(n,"abort")).subscribe(()=>{try{_.abort()}catch(ie){Ca(ie)}}),this.abortAllController.signal.aborted||n.aborted)try{_.abort()}catch(ie){Ca(ie)}p=_.signal}let f=(0,K.now)();d.log("startRequest",(0,K.flattenObject)({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:f}));let g=yield ut(l,{priority:s,headers:c,signal:p}).catch(Ca),S=(0,K.now)();if(!g)return d.error("error",{message:"No response in request"}),d.end(),h==null||h.unsubscribe(),null;if((Z=this.throughputEstimator)==null||Z.addRawRtt(S-f),!g.ok||!g.body){h==null||h.unsubscribe();let _=`Fetch error ${g.status}: ${g.statusText}`;return d.error("error",{message:_}),d.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!i&&!o){h==null||h.unsubscribe();let _=(0,K.now)(),ie={requestStartedAt:f,requestEndedAt:_,duration:_-f};return d.log("endRequest",(0,K.flattenObject)(ie)),d.end(),g.arrayBuffer()}let[I,E]=g.body.tee(),x=I.getReader();o&&((C=this.throughputEstimator)==null||C.trackStream(E,u));let k=0,w=new Uint8Array(0),Q=!1,F=_=>{h==null||h.unsubscribe(),Q=!0,Ca(_)},re=(0,K.abortable)(p,async function*({done:_,value:ie}){if(k===0&&this.lastRequestFirstBytes$.next((0,K.now)()-f),p.aborted){h==null||h.unsubscribe();return}if(!_&&ie){let he=new Uint8Array(w.length+ie.length);he.set(w),he.set(ie,w.length),w=he,k+=ie.byteLength,i==null||i(new DataView(w.buffer),k),yield x==null?void 0:x.read().then(re,F)}}.bind(this));yield x==null?void 0:x.read().then(re,F),h==null||h.unsubscribe();let W=(0,K.now)(),J={failed:Q,requestStartedAt:f,requestEndedAt:W,duration:W-f};return Q?(d.error("endRequest",(0,K.flattenObject)(J)),d.end(),null):(d.log("endRequest",(0,K.flattenObject)(J)),d.end(),w.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,K.abortable)(this.abortAllController.signal,async function*(e,t,r){var I;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=(I=e.indexRange)!=null?I:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let g;if(u)g=new DataView(d,f.from-n,f.to-f.from+1);else{let E=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!E)return null;g=new DataView(E)}let S=t.parseSegments(g,h,f);return{init:h,dataView:new DataView(d),segments:S}}.bind(this));this.fetchTemplateRepresentation=(0,K.abortable)(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(i)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:r}=zv(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,r))!=null?n:null;default:(0,K.assertNever)(i)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Ca=a=>{if(!Ra(a))throw a};var Ir=(a,e,t)=>t*e+(1-t)*a,hl=(a,e)=>a.reduce((t,r)=>t+r,0)/e,Xv=(a,e,t,r)=>{let i=0,s=t,n=hl(a,e),o=e<r?e:r;for(let u=0;u<o;u++)a[s]>n?i++:i--,s=(a.length+s-1)%a.length;return Math.abs(i)===o};var Va=require("@vkontakte/videoplayer-shared/es2018"),tr=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Va.ValueSubject(e.initial),this.debounced$=new Va.ValueSubject(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Le(`raw_${t}`),this.smoothedSeries$=new Le(`smoothed_${t}`),this.reportedSeries$=new Le(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,r++);this.takenMeasures=r,t/=r;let i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;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,Va.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 hn=class extends tr{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Ir(this.slow,e,this.params.emaAlphaSlow),this.fast=Ir(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var mn=class extends tr{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=hl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ir(this.emaSmoothed,e,this.params.emaAlpha);let r=Xv(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var fn=class extends tr{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?Ir(this.smoothed,t,this.params.emaAlpha):t}};var Er=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new hn({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new mn({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new fn({initial:e,label:"liveEdgeDelay",...t})}};var ml=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var bn=require("@vkontakte/videoplayer-shared/es2018");var Ba=class a{constructor(e,t){this.currentRepresentation$=new bn.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,bn.isNullable)(e))for(let r of this.representations)for(let i of r){let s=i.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 l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let r=a.filterRepresentations(t.representations);if(r){this.representations[this.representationsCursor]=r,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&&Re(t.segmentReference))}};var eR=["timeupdate","progress","play","seeked","stalled","waiting"],tR=["timeupdate","progress","loadeddata","playing","seeked"];var gn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new v.Subscription;this.representationSubscription=new v.Subscription;this.state$=new H("none");this.currentVideoRepresentation$=new v.ValueSubject(void 0);this.currentVideoRepresentationInit$=new v.ValueSubject(void 0);this.currentAudioRepresentation$=new v.ValueSubject(void 0);this.currentVideoSegmentLength$=new v.ValueSubject(0);this.currentAudioSegmentLength$=new v.ValueSubject(0);this.error$=new v.Subject;this.lastConnectionType$=new v.ValueSubject(void 0);this.lastConnectionReused$=new v.ValueSubject(void 0);this.lastRequestFirstBytes$=new v.ValueSubject(void 0);this.currentLiveTextRepresentation$=new v.ValueSubject(null);this.isLive$=new v.ValueSubject(!1);this.isActiveLive$=new v.ValueSubject(!1);this.isLowLatency$=new v.ValueSubject(!1);this.liveDuration$=new v.ValueSubject(0);this.liveAvailabilityStartTime$=new v.ValueSubject(void 0);this.bufferLength$=new v.ValueSubject(0);this.liveLatency$=new v.ValueSubject(void 0);this.liveLoadBufferLength$=new v.ValueSubject(0);this.livePositionFromPlayer$=new v.ValueSubject(0);this.currentStallDuration$=new v.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new v.ValueSubject(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new v.Subject;this.gapWatchdogActive=!1;this.destroyController=new xe;this.initManifest=(0,v.abortable)(this.destroyController.signal,async function*(e,t,r){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Ee(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:v.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,v.abortable)(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:v.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Gv(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Fg(e))!=null?n:{id:"ManifestParsing",category:v.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let r=(u,l,c)=>{var d,p,h,f;return!!((p=(d=this.element)==null?void 0:d.canPlayType)!=null&&p.call(d,l)&&((f=(h=Lt())==null?void 0:h.isTypeSupported)!=null&&f.call(h,`${l}; codecs="${c}"`))||u==="text")};if(t.dynamic){this.isLive$.next(t.dynamic),this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime);let u=((o=t.duration)!=null?o:0)/1e3;this.liveDuration$.next(-1*u)}let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:h,codecs:f})=>r(u,h,f)),d=new Set(c.map(({codecs:h})=>h)),p=vg(d);if(p&&(i[u]=c.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,f=i.video.some(S=>S.hdr),g=i.video.some(S=>!S.hdr);v.clientChecker.isHDR&&h&&f?i.video=i.video.filter(S=>S.hdr):g&&(i.video=i.video.filter(S=>!S.hdr))}}let s={...t,streams:i};return this.tracer.log("updateManifestEnd",(0,v.flattenObject)(s)),s}.bind(this));this.initRepresentations=(0,v.abortable)(this.destroyController.signal,async function*(e,t,r){var d;this.tracer.log("initRepresentationsStart",(0,v.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:r})),(0,v.assertNonNullable)(this.manifest),(0,v.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add((0,v.fromEvent)(p,"error").pipe((0,v.filter)(h=>{var f;return!!((f=this.element)!=null&&f.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:v.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?tg():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&en())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.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 Ma("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,v.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new Ma("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Ba.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ba(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,v.interval)(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let f=js(this.manifestUrlString,2);this.manifestUrlString=Ee(this.manifestUrlString,f+1e3,2)}}));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,v.merge)(...tR.map(p=>(0,v.fromEvent)(this.element,p))).pipe((0,v.map)(p=>this.element?vt(this.element.buffered,this.element.currentTime*1e3):0),(0,v.filterChanged)(),(0,v.tap)(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,v.merge)((0,v.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add((0,v.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,v.map)(({isActiveLive:h,isLowLatency:f})=>h&&f),(0,v.filterChanged)()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||ml(this.element,1)})),this.representationSubscription.add((0,v.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,v.filter)(({bufferLength:h,isActiveLive:f,isLowLatency:g})=>f&&g&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add((0,v.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$,currentLowLatencySegmentLength:this.videoBufferManager.currentLowLatencySegmentLength$}).pipe((0,v.filter)(({isActiveLive:h,isLowLatency:f,currentLowLatencySegmentLength:g})=>h&&f&&!!g)).subscribe(({currentLowLatencySegmentLength:h})=>{let f=this.liveDuration$.getValue()-h/1e3;this.liveDuration$.next(Math.min(f,this.tuning.dashCmafLive.maxLiveDuration))})),this.representationSubscription.add((0,v.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,v.filter)(({isLive:h})=>h),(0,v.map)(h=>({...h})),(0,v.filterChanged)((h,f)=>f.bufferLength<h.bufferLength),(0,v.map)(({rtt:h,bufferLength:f,segmentServerLatency:g})=>{let S=js(this.manifestUrlString,2);return(h/2+f+g+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,v.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:f,isLowLatency:g})=>{if(!g||!f)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,I=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,E=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,x=h-S;if(this.isManualDecreasePlaybackInLive())return;let k=1;Math.abs(x)>I&&(k=1+Math.sign(x)*E),ml(this.element,k)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var g,S;let f=0;if(h){let I=((S=(g=this.element)==null?void 0:g.currentTime)!=null?S:0)*1e3;f=Math.min(...this.bufferManagers.map(x=>{var k,w;return(w=(k=x.getLiveSegmentsToLoadState(this.manifest))==null?void 0:k.to)!=null?w:I}))-I}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add((0,v.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,v.throttle)(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if((0,v.assertNonNullable)(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,S=js(this.manifestUrlString,2),I=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,E=Math.min(I,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),x=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,k=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,w=isFinite(h)?h:f,Q=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),F=I<=this.tuning.live.activeLiveDelay&&S===0;this.isActiveLive$.next(F);let re="none";if(Q?re="active_low_latency":this.isLowLatency$.getValue()&&F?(this.bufferManagers.forEach(W=>W.proceedLowLatencyLive()),re="active_low_latency"):S!==0&&w<E?re="live_forward_buffering":w<E+k&&(re="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),re==="live_forward_buffering"||re==="live_with_target_offset"){let W=p-(E+x),J=this.normolizeLiveOffset(Math.trunc(S+W/g)),Z=Math.abs(J-S),C;!h||Z<=this.tuning.dashCmafLive.offsetCalculationError?C=S:J>0&&Z>this.tuning.dashCmafLive.offsetCalculationError?C=J:C=0,this.manifestUrlString=Ee(this.manifestUrlString,C,2)}re!=="none"&&re!=="active_low_latency"&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:v.ErrorCategory.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=(0,v.merge)(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe((0,v.map)(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=(0,v.merge)(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe((0,v.map)(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));if(this.representationSubscription.add((0,v.merge)(this.forceEnded$,(0,v.combine)({allBuffersFull:l,someBufferEnded:c}).pipe((0,v.filter)(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).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(),this.bufferManagers.forEach(h=>h.warmUpMediaSource())}catch(h){this.error$.next({id:"EndOfStream",category:v.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add((0,v.merge)(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)})),!this.isLive$.getValue()){let p=[(d=this.manifest.duration)!=null?d:0,...(0,fl.default)((0,fl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),Re(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&(0,v.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,r,i;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(i=this.audioBufferManager)!=null&&i.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,v.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:v.ErrorCategory.WTF,message:"Error handling gaps",thrown:s})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new pn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=Er.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,i,s;(0,v.assertNonNullable)(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLive$.next(t===0),this.liveLastSeekOffset=t,this.manifestUrlString=Ee(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((i=this.audioBufferManager)==null?void 0:i.seekLive(this.manifest.streams.audio)),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))}initBuffer(){(0,v.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,v.merge)(...eR.map(e=>(0,v.fromEvent)(this.element,e)),(0,v.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:v.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,v.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,v.fromEvent)(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Zt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var h,f,g,S,I,E,x,k,w,Q;if(!this.element)return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let i={timeInWaiting:r},s=(0,v.now)(),n=100,o=(f=(h=this.videoBufferManager)==null?void 0:h.lastDataObtainedTimestamp)!=null?f:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(S=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?S:0,l=(E=(I=this.videoBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?E:0,c=(k=(x=this.audioBufferManager)==null?void 0:x.getForwardBufferDuration())!=null?k:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%5e3===0)this.seekLive(this.liveLastSeekOffset).catch(F=>{this.error$.next({id:"stallIntervalCallback",category:v.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:F})}),i.liveLastSeekOffset=this.liveLastSeekOffset;else{let F=this.element.currentTime*1e3;(w=this.videoBufferManager)==null||w.maintain(F),(Q=this.audioBufferManager)==null||Q.maintain(F),i.position=F}this.tracer.log("stallIntervalCallback",(0,v.flattenObject)(i))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=(0,v.interval)(50).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:v.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?i==null?void 0:i.switchToWithPreviousAbort(t,r):i==null?void 0:i.switchTo(t,r):i==null?void 0:i.switchToOld(t,r)}async seek(e,t){var i,s,n,o,u;(0,v.assertNonNullable)(this.element),(0,v.assertNonNullable)(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!=null?i:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),Zt(this.element.buffered,r)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",(0,v.flattenObject)({requestedPosition:e,forcePrecise:t,position:r}))}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>{URL.revokeObjectURL(i.src),i.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.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}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),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,v.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(r=>r.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.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(),r={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let i=this.element.currentTime*1e3,s=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-n<=i&&u.to+n>i&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?s.push(1/0):s.push(u.to));if(s.length){let o=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,r={...r,gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",(0,v.flattenObject)(r)))}}};var vn=class{constructor(e,t){this.fov=e,this.orientation=t}};var Sn=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Zv=`attribute vec2 a_vertex;
|
|
70
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var al=U(Kt(),1);var qv=require("@vkontakte/videoplayer-shared/es2018"),Uv=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s,streamId:n})=>{var u;let o=(u=s?zt(s):void 0)!=null?u:(0,qv.videoSizeToQuality)({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},Hv=({id:a,bitrate:e})=>({id:a,bitrate:e}),jv=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Qv=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),sl=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,al.default)(r.split("."),0),isDefault:i}),nl=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,al.default)(i.split("."),0)}),ol=a=>"url"in a,Re=a=>a.type==="template",Ra=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Gv=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},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),i=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],i),hours:e(r==null?void 0:r[6],i),minutes:e(r==null?void 0:r[7],i),seconds:e(r==null?void 0:r[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},Mt=(a,e)=>{let t=a;t=(0,ul.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of(0,Wv.default)(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,ul.default)(t,n,(o,u)=>(0,$a.isNullable)(s)?o:(0,$a.isNullable)(u)?s:(0,Yv.default)(s,parseInt(u,10),"0"))}return t},Kv=(a,e)=>{var W,J,Z,C,_,ie,me,L,P,q,ee,Y,qe,di,wr,te,Te,we,Ae,Bt,Ar,Ot,rr,kr,pi,Pl,wl,Al,kl,Ll,Rl,$l,Ml,Dl,Cl,Vl,Bl,Ol,_l,Nl,Fl,ql,Ul,Hl,jl,Ql,Gl,Wl,Yl,zl,Kl,Xl,Jl,Zl,ec,tc,rc,ic,ac,sc,nc;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(tt=>{var se,ir;return(ir=(se=tt.textContent)==null?void 0:se.trim())!=null?ir:""}),o=(W=(0,zv.default)(n,0))!=null?W:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=s.getAttribute("publishTime"),d=s.getElementsByTagName("vk:Attrs")[0],p=d==null?void 0:d.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=d==null?void 0:d.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=d==null?void 0:d.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,g=d==null?void 0:d.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,S;u&&(S={availabilityStartTime:l?new Date(l).getTime():0,publishTime:c?new Date(c).getTime():0,latestSegmentPublishTime:p?new Date(p).getTime():0,streamIsAlive:h?h==="yes":!1,streamIsUnpublished:f?f==="yes":!1});let I,x=s.getAttribute("mediaPresentationDuration"),E=[...s.getElementsByTagName("Period")],A=E.reduce((tt,se)=>({...tt,[se.id]:se.children}),{}),w=E.reduce((tt,se)=>({...tt,[se.id]:se.getAttribute("duration")}),{});x?I=Gv(x):(0,ll.default)(w).filter(tt=>tt).length&&!u?I=(0,ll.default)(w).reduce((tt,se)=>{var ir;return tt+((ir=Gv(se))!=null?ir:0)},0):g&&(I=parseInt(g,10));let Q=0,F=(Z=(J=s.getAttribute("profiles"))==null?void 0:J.split(","))!=null?Z:[];for(let tt of E.map(se=>se.id))for(let se of A[tt]){let ir=(C=se.getAttribute("id"))!=null?C:"id"+(Q++).toString(10),hi=(_=se.getAttribute("mimeType"))!=null?_:"",wn=(ie=se.getAttribute("codecs"))!=null?ie:"",An=(me=se.getAttribute("contentType"))!=null?me:hi==null?void 0:hi.split("/")[0],$S=(P=(L=se.getAttribute("profiles"))==null?void 0:L.split(","))!=null?P:[],oc=(ee=Fv((q=se.getAttribute("lang"))!=null?q:""))!=null?ee:{},Ya=(di=(qe=(Y=se.querySelector("Label"))==null?void 0:Y.textContent)==null?void 0:qe.trim())!=null?di:void 0,MS=se.querySelectorAll("Representation"),DS=se.querySelector("SegmentTemplate"),CS=(te=(wr=se.querySelector("Role"))==null?void 0:wr.getAttribute("value"))!=null?te:void 0,Lr=An,pe={id:ir,language:oc.language,isDefault:CS==="main",label:Ya,codecs:wn,hdr:Lr==="video"&&rl(wn),mime:hi,representations:[]};for(let ae of MS){let _t=(Te=ae.getAttribute("lang"))!=null?Te:void 0,mi=(Ae=(we=Ya!=null?Ya:se.getAttribute("label"))!=null?we:ae.getAttribute("label"))!=null?Ae:void 0,za=(Ot=(Ar=(Bt=ae.querySelector("BaseURL"))==null?void 0:Bt.textContent)==null?void 0:Ar.trim())!=null?Ot:"",ar=new URL(za||o,e).toString(),Nt=(rr=ae.getAttribute("mimeType"))!=null?rr:hi,Ka=(pi=(kr=ae.getAttribute("codecs"))!=null?kr:wn)!=null?pi:"",Xa;if(An==="text"){let Ft=ae.getAttribute("id")||"",Ja=((Pl=oc.privateuse)==null?void 0:Pl.includes("x-auto"))||Ft.includes("_auto"),sr=ae.querySelector("SegmentTemplate");if(sr){let fi={representationId:(wl=ae.getAttribute("id"))!=null?wl:void 0,bandwidth:(Al=ae.getAttribute("bandwidth"))!=null?Al:void 0},Za=parseInt((kl=ae.getAttribute("bandwidth"))!=null?kl:"",10)/1e3,es=(Rl=parseInt((Ll=sr.getAttribute("startNumber"))!=null?Ll:"",10))!=null?Rl:1,Rr=parseInt(($l=sr.getAttribute("timescale"))!=null?$l:"",10),kn=(Ml=sr.querySelectorAll("SegmentTimeline S"))!=null?Ml:[],$r=sr.getAttribute("media");if(!$r)continue;let ts=[],rs=0,is="",Mr=0,bi=es,ke=0;for(let rt of kn){let nr=parseInt((Dl=rt.getAttribute("d"))!=null?Dl:"",10),Ye=parseInt((Cl=rt.getAttribute("r"))!=null?Cl:"",10)||0,qt=parseInt((Vl=rt.getAttribute("t"))!=null?Vl:"",10);ke=Number.isFinite(qt)?qt:ke;let or=nr/Rr*1e3,Ut=ke/Rr*1e3;for(let pt=0;pt<Ye+1;pt++){let Ht=Mt($r,{...fi,segmentNumber:bi.toString(10),segmentTime:(ke+pt*nr).toString(10)}),Dr=(Ut!=null?Ut:0)+pt*or,vi=Dr+or;bi++,ts.push({time:{from:Dr,to:vi},url:Ht})}ke+=(Ye+1)*nr,rs+=(Ye+1)*or}Mr=ke/Rr*1e3,is=Mt($r,{...fi,segmentNumber:bi.toString(10),segmentTime:ke.toString(10)});let gi={time:{from:Mr,to:1/0},url:is},It={type:"template",baseUrl:ar,segmentTemplateUrl:$r,initUrl:"",totalSegmentsDurationMs:rs,segments:ts,nextSegmentBeyondManifest:gi,timescale:Rr};Xa={id:Ft,kind:"text",segmentReference:It,profiles:[],duration:I,bitrate:Za,mime:"",codecs:"",width:0,height:0,isAuto:Ja}}else Xa={id:Ft,isAuto:Ja,kind:"text",url:ar}}else{let Ft=(Ol=(Bl=ae.getAttribute("contentType"))!=null?Bl:Nt==null?void 0:Nt.split("/")[0])!=null?Ol:An,Ja=(Nl=(_l=se.getAttribute("profiles"))==null?void 0:_l.split(","))!=null?Nl:[],sr=parseInt((Fl=ae.getAttribute("width"))!=null?Fl:"",10),fi=parseInt((ql=ae.getAttribute("height"))!=null?ql:"",10),Za=parseInt((Ul=ae.getAttribute("bandwidth"))!=null?Ul:"",10)/1e3,es=(Hl=ae.getAttribute("frameRate"))!=null?Hl:"",Rr=(jl=ae.getAttribute("quality"))!=null?jl:void 0,kn=es?Nv(es):void 0,$r=(Ql=ae.getAttribute("id"))!=null?Ql:"id"+(Q++).toString(10),ts=Ft==="video"?`${fi}p`:Ft==="audio"?`${Za}Kbps`:Ka,rs=`${$r}@${ts}`,is=[...F,...$S,...Ja],Mr,bi=ae.querySelector("SegmentBase"),ke=(Gl=ae.querySelector("SegmentTemplate"))!=null?Gl:DS;if(bi){let It=(Yl=(Wl=ae.querySelector("SegmentBase Initialization"))==null?void 0:Wl.getAttribute("range"))!=null?Yl:"",[rt,nr]=It.split("-").map(Ht=>parseInt(Ht,10)),Ye={from:rt,to:nr},qt=(zl=ae.querySelector("SegmentBase"))==null?void 0:zl.getAttribute("indexRange"),[or,Ut]=qt?qt.split("-").map(Ht=>parseInt(Ht,10)):[],pt=qt?{from:or,to:Ut}:void 0;Mr={type:"byteRange",url:ar,initRange:Ye,indexRange:pt}}else if(ke){let It={representationId:(Kl=ae.getAttribute("id"))!=null?Kl:void 0,bandwidth:(Xl=ae.getAttribute("bandwidth"))!=null?Xl:void 0},rt=parseInt((Jl=ke.getAttribute("timescale"))!=null?Jl:"",10),nr=(Zl=ke.getAttribute("initialization"))!=null?Zl:"",Ye=ke.getAttribute("media"),qt=(tc=parseInt((ec=ke.getAttribute("startNumber"))!=null?ec:"",10))!=null?tc:1,or=Mt(nr,It);if(!Ye)throw new ReferenceError("No media attribute in SegmentTemplate");let Ut=(rc=ke.querySelectorAll("SegmentTimeline S"))!=null?rc:[],pt=[],Ht=0,Dr="",vi=0;if(Ut.length){let as=qt,it=0;for(let Cr of Ut){let ht=parseInt((ic=Cr.getAttribute("d"))!=null?ic:"",10),ur=parseInt((ac=Cr.getAttribute("r"))!=null?ac:"",10)||0,ss=parseInt((sc=Cr.getAttribute("t"))!=null?sc:"",10);it=Number.isFinite(ss)?ss:it;let Ln=ht/rt*1e3,Rn=it/rt*1e3;for(let ns=0;ns<ur+1;ns++){let BS=Mt(Ye,{...It,segmentNumber:as.toString(10),segmentTime:(it+ns*ht).toString(10)}),uc=(Rn!=null?Rn:0)+ns*Ln,OS=uc+Ln;as++,pt.push({time:{from:uc,to:OS},url:BS})}it+=(ur+1)*ht,Ht+=(ur+1)*Ln}vi=it/rt*1e3,Dr=Mt(Ye,{...It,segmentNumber:as.toString(10),segmentTime:it.toString(10)})}else if((0,$a.isNonNullable)(I)){let it=parseInt((nc=ke.getAttribute("duration"))!=null?nc:"",10)/rt*1e3,Cr=Math.ceil(I/it),ht=0;for(let ur=1;ur<Cr;ur++){let ss=Mt(Ye,{...It,segmentNumber:ur.toString(10),segmentTime:ht.toString(10)});pt.push({time:{from:ht,to:ht+it},url:ss}),ht+=it}vi=ht,Dr=Mt(Ye,{...It,segmentNumber:Cr.toString(10),segmentTime:ht.toString(10)})}let VS={time:{from:vi,to:1/0},url:Dr};Mr={type:"template",baseUrl:ar,segmentTemplateUrl:Ye,initUrl:or,totalSegmentsDurationMs:Ht,segments:pt,nextSegmentBeyondManifest:VS,timescale:rt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ft||!Nt)continue;let gi={video:"video",audio:"audio",text:"text"}[Ft];if(!gi)continue;Lr||(Lr=gi),Xa={id:rs,kind:gi,segmentReference:Mr,profiles:is,duration:I,bitrate:Za,mime:Nt,codecs:Ka,width:sr,height:fi,fps:kn,quality:Rr}}pe.language||(pe.language=_t),pe.label||(pe.label=mi),pe.mime||(pe.mime=Nt),pe.codecs||(pe.codecs=Ka),pe.hdr||(pe.hdr=Lr==="video"&&rl(Ka)),pe.representations.push(Xa)}if(Lr){let ae=i[Lr].find(_t=>_t.id===pe.id);if(ae&&pe.representations.every(_t=>Re(_t.segmentReference)))for(let _t of ae.representations){let mi=pe.representations.find(Nt=>Nt.id===_t.id),za=mi==null?void 0:mi.segmentReference,ar=_t.segmentReference;ar.segments.push(...za.segments),ar.nextSegmentBeyondManifest=za.nextSegmentBeyondManifest}else i[Lr].push(pe)}}return{duration:I,streams:i,baseUrls:n,live:S}};var Xv=U(ot(),1),dl=require("@vkontakte/videoplayer-shared/es2018"),$e=(a,e)=>(0,dl.isNonNullable)(a)&&(0,dl.isNonNullable)(e)&&a.readyState==="open"&&(0,Xv.default)([...a.activeSourceBuffers],e);var Ma=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new T.ValueSubject(0);this.currentLowLatencySegmentLength$=new T.ValueSubject(0);this.currentSegmentLength$=new T.ValueSubject(0);this.onLastSegment$=new T.ValueSubject(!1);this.fullyBuffered$=new T.ValueSubject(!1);this.playingRepresentation$=new T.ValueSubject(void 0);this.playingRepresentationInit$=new T.ValueSubject(void 0);this.error$=new T.Subject;this.gaps=[];this.subscription=new T.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Pe;this.switchAbortController=new Pe;this.destroyAbortController=new Pe;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,T.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,T.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Yg(this.sourceBuffer),this.subscription.add((0,T.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:T.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add((0,T.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:T.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!$e(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,zu(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=St(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,T.assertNonNullable)(r,"No init buffer for starting representation"),(0,T.assertNonNullable)(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=(0,T.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);(0,T.assertNonNullable)(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if((0,T.isNullable)(s)||(0,T.isNullable)(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),(0,T.assertNonNullable)(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!$e(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,T.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,T.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);(0,T.assertNonNullable)(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if((0,T.isNullable)(s)||(0,T.isNullable)(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),(0,T.assertNonNullable)(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!$e(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,T.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=(0,T.abortable)(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,cn.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(f=>f.id===c);d&&this.representations.set(c,d);let p=this.representations.get(c);if(!p||!Re(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let r=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,i=this.representations.get(r);(0,T.assertNonNullable)(i);let s=this.segments.get(r);(0,T.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(r);if((0,T.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))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,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var c;this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Pe,(0,T.abortable)(this.switchAbortController.signal,async function*(r,i=!1){this.switchingToRepresentationId=r;let s=this.representations.get(r);(0,T.assertNonNullable)(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if((0,T.isNullable)(o)||(0,T.isNullable)(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),(0,T.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!$e(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),i)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=r,yield this.dropBuffer();else{let u=this.getCurrentPosition();(0,T.isNonNullable)(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=r,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!(0,T.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 Pe,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,T.isNullable)(e)||(0,T.isNullable)(this.downloadingRepresentationId)||(0,T.isNullable)(this.playingRepresentationId)||(0,T.isNullable)(this.sourceBuffer)||!$e(this.mediaSource,this.sourceBuffer)||(0,T.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if((0,T.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(l=>e>=l.time.from&&e<l.time.to);(0,T.isNonNullable)(i)&&isFinite(i.time.from)&&isFinite(i.time.to)&&this.currentSegmentLength$.next((i==null?void 0:i.time.to)-i.time.from);let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=St(this.sourceBuffer.buffered,e),d=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=i.time.to-e+100&&(s=d)}if(isFinite(this.bufferLimit)&&zu(this.sourceBuffer.buffered)>=this.bufferLimit){let l=St(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")});return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if((0,ln.default)(o,i))l="high";else{let c=(0,ui.default)(o,0);c&&c.time.from-i.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&St(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,ui.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let r=0,i=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+i}),r=s.time.to;(0,T.isNonNullable)(t.duration)&&t.duration-r>0&&!this.isLive&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=(0,cn.default)(e==null?void 0:e.streams[this.kind],i=>i.representations).find(i=>i.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var r,i,s,n;let t=(r=(0,cn.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?r:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!Re(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>({...h,status:"none",size:void 0})),l=100,c=(i=this.segments.get(o.id))!=null?i:[],d=(n=(s=(0,ui.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,p=u==null?void 0:u.findIndex(h=>d>=h.time.from+l&&d<=h.time.to+l);if(p===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(p+1);this.segments.set(o.id,[...c,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,T.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){var r;let t=0;for(let i of this.representations.values()){let s=i.segmentReference;if(!Re(s))return;let n=(r=this.segments.get(i.id))!=null?r:[],o=n.find(l=>Math.floor(l.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(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*s.timescale/1e3).toString(10),c=Mt(s.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}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 r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.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&&ia&&ia(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&ia&&ia(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,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:p,to:h}},f)=>{let g=p<=r&&h>=r,S=p>r||g||f===0&&r===0,I=Math.min(this.forwardBufferTarget,this.bufferLimit),x=this.preloadOnly&&p<=r+I||h<=r+I;return(d==="none"||d==="partially_ejected"&&S&&x&&this.sourceBuffer&&$e(this.mediaSource,this.sourceBuffer)&&!(Zt(this.sourceBuffer.buffered,p)&&Zt(this.sourceBuffer.buffered,h)))&&S&&x});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=l||o<=c);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,r="auto"){Re(t.segmentReference)?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await(0,T.abortable)(o,async function*(){let c=(0,T.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=(0,T.now)(),!c)return;let d=new DataView(c),p=La(t.mime);if(!isFinite(i.segment.time.to)){let g=t.segmentReference.timescale;i.segment.time.to=p.getChunkEndTime(d,g)}u&&i.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=p.getServerLatencyTimestamps(d);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Ra(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Re(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,r="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:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await(0,T.abortable)(n,async function*(){let u=(0,T.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,T.fromEvent)(window,"online").pipe((0,T.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=(0,T.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ra(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Re(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,ui.default)(e,0).byte.from,to:(0,ui.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,T.now)(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Re(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,T.now)();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,ln.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){i();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=La(n.mime).parseFeedableSegmentChunk(l,this.isLive);c!=null&&c.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){await n();continue}let c=l.byte.from-r,d=l.byte.to-r,p=d-c+1,h=c<i,f=d<=i;if(!h)continue;let g=La(o.mime);if(l.status==="downloading"&&f){l.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+c,p);await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,i-c),u.loadedBytes>u.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),I=u.loadedBytes===p?S:g.parseFeedableSegmentChunk(S);I!=null&&I.byteLength&&(l.status="partially_fed",u.feedingBytes+=I.byteLength,await this.sourceBufferTaskQueue.append(I,s)&&!s.aborted?(u.fedBytes+=I.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var r;if(!((0,T.isNullable)(this.sourceBuffer)||!$e(this.mediaSource,this.sourceBuffer))){!this.isLive&&T.clientChecker.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Zt(this.sourceBuffer.buffered,e.segment.time.from,100)&&Zt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",ol(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let s of(r=this.segments.get(i.id))!=null?r:[])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[i,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=Wu(()=>(0,Jv.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",r=!1){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?(0,T.abortable)(this.destroyAbortController.signal,async function*(){let o=(0,T.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,La(e.mime),i)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&Re(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:T.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,r=!1){if(!this.sourceBuffer||!$e(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,T.isNullable)(e))return!1;let i=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:p}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,p):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push({...u.time}),i=n(i);let l=ol(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)(0,ln.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return i.length?(await Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!$e(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||!$e(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(){let e=this.getCurrentPosition();return!this.sourceBuffer||!$e(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,T.isNullable)(e)?0:St(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!$e(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!$e(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=Wu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:T.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,T.isNullable)(this.sourceBuffer)||!$e(this.mediaSource,this.sourceBuffer)||(0,T.isNullable)(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=100;for(let r of this.segments.values())for(let i of r){let{status:s}=i;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(i.time.from),o=Math.ceil(i.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?i.status="partially_ejected":this.gaps.some(c=>c.from===i.time.from||c.to===i.time.to)?i.status="partially_ejected":i.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:T.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Da=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Zv=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,i=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:i}};var K=require("@vkontakte/videoplayer-shared/es2018");var eS=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var dn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new K.ValueSubject(void 0);this.lastConnectionReused$=new K.ValueSubject(void 0);this.lastRequestFirstBytes$=new K.ValueSubject(void 0);this.abortAllController=new Pe;this.subscription=new K.Subscription;this.fetchManifest=(0,K.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Da(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=eS(r));let i=yield lt(r,{signal:this.abortAllController.signal}).catch(Ca);return i?(t.log("success",(0,K.flattenObject)({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",(0,K.flattenObject)({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,K.abortable)(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var Z,C;let l=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{c.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let _=new URL(l,location.href);_.searchParams.append("bytes",`${r.from}-${r.to}`),l=_.toString();break}default:(0,K.assertNever)(t)}this.requestQuic&&(l=Da(l));let p=this.abortAllController.signal,h;if(n){let _=new Pe;if(h=(0,K.merge)((0,K.fromEvent)(this.abortAllController.signal,"abort"),(0,K.fromEvent)(n,"abort")).subscribe(()=>{try{_.abort()}catch(ie){Ca(ie)}}),this.abortAllController.signal.aborted||n.aborted)try{_.abort()}catch(ie){Ca(ie)}p=_.signal}let f=(0,K.now)();d.log("startRequest",(0,K.flattenObject)({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:f}));let g=yield lt(l,{priority:s,headers:c,signal:p}).catch(Ca),S=(0,K.now)();if(!g)return d.error("error",{message:"No response in request"}),d.end(),h==null||h.unsubscribe(),null;if((Z=this.throughputEstimator)==null||Z.addRawRtt(S-f),!g.ok||!g.body){h==null||h.unsubscribe();let _=`Fetch error ${g.status}: ${g.statusText}`;return d.error("error",{message:_}),d.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!i&&!o){h==null||h.unsubscribe();let _=(0,K.now)(),ie={requestStartedAt:f,requestEndedAt:_,duration:_-f};return d.log("endRequest",(0,K.flattenObject)(ie)),d.end(),g.arrayBuffer()}let[I,x]=g.body.tee(),E=I.getReader();o&&((C=this.throughputEstimator)==null||C.trackStream(x,u));let A=0,w=new Uint8Array(0),Q=!1,F=_=>{h==null||h.unsubscribe(),Q=!0,Ca(_)},re=(0,K.abortable)(p,async function*({done:_,value:ie}){if(A===0&&this.lastRequestFirstBytes$.next((0,K.now)()-f),p.aborted){h==null||h.unsubscribe();return}if(!_&&ie){let me=new Uint8Array(w.length+ie.length);me.set(w),me.set(ie,w.length),w=me,A+=ie.byteLength,i==null||i(new DataView(w.buffer),A),yield E==null?void 0:E.read().then(re,F)}}.bind(this));yield E==null?void 0:E.read().then(re,F),h==null||h.unsubscribe();let W=(0,K.now)(),J={failed:Q,requestStartedAt:f,requestEndedAt:W,duration:W-f};return Q?(d.error("endRequest",(0,K.flattenObject)(J)),d.end(),null):(d.log("endRequest",(0,K.flattenObject)(J)),d.end(),w.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,K.abortable)(this.abortAllController.signal,async function*(e,t,r){var I;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=(I=e.indexRange)!=null?I:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let g;if(u)g=new DataView(d,f.from-n,f.to-f.from+1);else{let x=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!x)return null;g=new DataView(x)}let S=t.parseSegments(g,h,f);return{init:h,dataView:new DataView(d),segments:S}}.bind(this));this.fetchTemplateRepresentation=(0,K.abortable)(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(i)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:r}=Zv(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,r))!=null?n:null;default:(0,K.assertNever)(i)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Ca=a=>{if(!Ra(a))throw a};var Ir=(a,e,t)=>t*e+(1-t)*a,pl=(a,e)=>a.reduce((t,r)=>t+r,0)/e,tS=(a,e,t,r)=>{let i=0,s=t,n=pl(a,e),o=e<r?e:r;for(let u=0;u<o;u++)a[s]>n?i++:i--,s=(a.length+s-1)%a.length;return Math.abs(i)===o};var Va=require("@vkontakte/videoplayer-shared/es2018"),tr=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Va.ValueSubject(e.initial),this.debounced$=new Va.ValueSubject(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Le(`raw_${t}`),this.smoothedSeries$=new Le(`smoothed_${t}`),this.reportedSeries$=new Le(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,r++);this.takenMeasures=r,t/=r;let i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;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,Va.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 pn=class extends tr{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Ir(this.slow,e,this.params.emaAlphaSlow),this.fast=Ir(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var hn=class extends tr{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=pl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ir(this.emaSmoothed,e,this.params.emaAlpha);let r=tS(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var mn=class extends tr{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?Ir(this.smoothed,t,this.params.emaAlpha):t}};var Er=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new pn({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new hn({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new mn({initial:e,label:"liveEdgeDelay",...t})}};var hl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var fn=require("@vkontakte/videoplayer-shared/es2018");var Ba=class a{constructor(e,t){this.currentRepresentation$=new fn.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,fn.isNullable)(e))for(let r of this.representations)for(let i of r){let s=i.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 l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let r=a.filterRepresentations(t.representations);if(r){this.representations[this.representationsCursor]=r,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&&Re(t.segmentReference))}};var sR=["timeupdate","progress","play","seeked","stalled","waiting"],nR=["timeupdate","progress","loadeddata","playing","seeked"];var bn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new v.Subscription;this.representationSubscription=new v.Subscription;this.state$=new H("none");this.currentVideoRepresentation$=new v.ValueSubject(void 0);this.currentVideoRepresentationInit$=new v.ValueSubject(void 0);this.currentAudioRepresentation$=new v.ValueSubject(void 0);this.currentVideoSegmentLength$=new v.ValueSubject(0);this.currentAudioSegmentLength$=new v.ValueSubject(0);this.error$=new v.Subject;this.lastConnectionType$=new v.ValueSubject(void 0);this.lastConnectionReused$=new v.ValueSubject(void 0);this.lastRequestFirstBytes$=new v.ValueSubject(void 0);this.currentLiveTextRepresentation$=new v.ValueSubject(null);this.isLive$=new v.ValueSubject(!1);this.isActiveLive$=new v.ValueSubject(!1);this.isLowLatency$=new v.ValueSubject(!1);this.liveDuration$=new v.ValueSubject(0);this.liveSeekableDuration$=new v.ValueSubject(0);this.liveAvailabilityStartTime$=new v.ValueSubject(0);this.liveStreamStatus$=new v.ValueSubject(void 0);this.bufferLength$=new v.ValueSubject(0);this.liveLatency$=new v.ValueSubject(void 0);this.liveLoadBufferLength$=new v.ValueSubject(0);this.livePositionFromPlayer$=new v.ValueSubject(0);this.currentStallDuration$=new v.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new v.ValueSubject(0);this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new v.Subject;this.gapWatchdogActive=!1;this.destroyController=new Pe;this.initManifest=(0,v.abortable)(this.destroyController.signal,async function*(e,t,r){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=xe(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:v.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,v.abortable)(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:v.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Kv(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=jg(e))!=null?n:{id:"ManifestParsing",category:v.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let r=(u,l,c)=>{var d,p,h,f;return!!((p=(d=this.element)==null?void 0:d.canPlayType)!=null&&p.call(d,l)&&((f=(h=Lt())==null?void 0:h.isTypeSupported)!=null&&f.call(h,`${l}; codecs="${c}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:c,streamIsAlive:d}=t.live,p=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*p),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";d||(h=c?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h)}let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:h,codecs:f})=>r(u,h,f)),d=new Set(c.map(({codecs:h})=>h)),p=Ig(d);if(p&&(i[u]=c.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,f=i.video.some(S=>S.hdr),g=i.video.some(S=>!S.hdr);v.clientChecker.isHDR&&h&&f?i.video=i.video.filter(S=>S.hdr):g&&(i.video=i.video.filter(S=>!S.hdr))}}let s={...t,streams:i};return this.tracer.log("updateManifestEnd",(0,v.flattenObject)(s)),s}.bind(this));this.initRepresentations=(0,v.abortable)(this.destroyController.signal,async function*(e,t,r){var d;this.tracer.log("initRepresentationsStart",(0,v.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:r})),(0,v.assertNonNullable)(this.manifest),(0,v.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add((0,v.fromEvent)(p,"error").pipe((0,v.filter)(h=>{var f;return!!((f=this.element)!=null&&f.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:v.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?sg():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Zs())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.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 Ma("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,v.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new Ma("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Ba.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ba(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,v.merge)(...nR.map(p=>(0,v.fromEvent)(this.element,p))).pipe((0,v.map)(p=>this.element?St(this.element.buffered,this.element.currentTime*1e3):0),(0,v.filterChanged)(),(0,v.tap)(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,v.merge)((0,v.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,v.filterChanged)()).subscribe(h=>this.liveStreamEndTimestamp=(0,v.now)())),this.subscription.add((0,v.fromEvent)(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=(0,v.interval)(1e3).subscribe(h=>{let f=Hs(this.manifestUrlString,2);this.manifestUrlString=xe(this.manifestUrlString,f+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()})})).add((0,v.fromEvent)(this.element,"play").subscribe(h=>{var f;return(f=this.livePauseWatchdogSubscription)==null?void 0:f.unsubscribe()})),this.representationSubscription.add((0,v.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,v.map)(({isActiveLive:h,isLowLatency:f})=>h&&f),(0,v.filterChanged)()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||hl(this.element,1)})),this.representationSubscription.add((0,v.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,v.filter)(({bufferLength:h,isActiveLive:f,isLowLatency:g})=>f&&g&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let f=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(f,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add((0,v.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,v.filter)(({isLive:h})=>h),(0,v.filterChanged)((h,f)=>f.bufferLength<h.bufferLength),(0,v.map)(({rtt:h,bufferLength:f,segmentServerLatency:g})=>{let S=Hs(this.manifestUrlString,2);return(h/2+f+g+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,v.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:f,isLowLatency:g})=>{if(!g||!f)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,I=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,x=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,E=h-S;if(this.isManualDecreasePlaybackInLive())return;let A=1;Math.abs(E)>I&&(A=1+Math.sign(E)*x),hl(this.element,A)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var g,S;let f=0;if(h){let I=((S=(g=this.element)==null?void 0:g.currentTime)!=null?S:0)*1e3;f=Math.min(...this.bufferManagers.map(E=>{var A,w;return(w=(A=E.getLiveSegmentsToLoadState(this.manifest))==null?void 0:A.to)!=null?w:I}))-I}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add((0,v.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,v.throttle)(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,S=Hs(this.manifestUrlString,2),I=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,x=Math.min(I,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),E=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,A=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,w=isFinite(h)?h:f,Q=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),F=I<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(F);let re="none";if(Q?re="active_low_latency":this.isLowLatency$.getValue()&&F?(this.bufferManagers.forEach(W=>W.proceedLowLatencyLive()),re="active_low_latency"):S!==0&&w<x?re="live_forward_buffering":w<x+A&&(re="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),re==="live_forward_buffering"||re==="live_with_target_offset"){let W=p-(x+E),J=this.normolizeLiveOffset(Math.trunc(S+W/g)),Z=Math.abs(J-S),C=0;!h||Z<=this.tuning.dashCmafLive.offsetCalculationError?C=S:J>0&&Z>this.tuning.dashCmafLive.offsetCalculationError&&(C=J),this.manifestUrlString=xe(this.manifestUrlString,C,2)}(re==="live_with_target_offset"||re==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:v.ErrorCategory.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=(0,v.merge)(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe((0,v.map)(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=(0,v.merge)(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe((0,v.map)(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));if(this.representationSubscription.add((0,v.merge)(this.forceEnded$,(0,v.combine)({allBuffersFull:l,someBufferEnded:c}).pipe((0,v.filter)(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).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(),this.bufferManagers.forEach(h=>h.warmUpMediaSource())}catch(h){this.error$.next({id:"EndOfStream",category:v.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add((0,v.merge)(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)})),!this.isLive$.getValue()){let p=[(d=this.manifest.duration)!=null?d:0,...(0,fl.default)((0,fl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),Re(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&(0,v.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,r,i;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(i=this.audioBufferManager)!=null&&i.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,v.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:v.ErrorCategory.WTF,message:"Error handling gaps",thrown:s})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new dn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=Er.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var i,s,n;(0,v.assertNonNullable)(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?(0,v.now)()-this.liveStreamEndTimestamp:0,r=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(r===0),this.manifestUrlString=xe(this.manifestUrlString,r,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((i=this.videoBufferManager)==null?void 0:i.seekLive(this.manifest.streams.video)),await((s=this.audioBufferManager)==null?void 0:s.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){(0,v.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,v.merge)(...sR.map(e=>(0,v.fromEvent)(this.element,e)),(0,v.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:v.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,v.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,v.fromEvent)(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Zt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var h,f,g,S,I,x,E,A,w,Q;if(!this.element)return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let i={timeInWaiting:r},s=(0,v.now)(),n=100,o=(f=(h=this.videoBufferManager)==null?void 0:h.lastDataObtainedTimestamp)!=null?f:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(S=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?S:0,l=(x=(I=this.videoBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?x:0,c=(A=(E=this.audioBufferManager)==null?void 0:E.getForwardBufferDuration())!=null?A:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%2e3===0){let F=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(F).catch(re=>{this.error$.next({id:"stallIntervalCallback",category:v.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:re})}),i.liveLastOffset=F}else{let F=this.element.currentTime*1e3;(w=this.videoBufferManager)==null||w.maintain(F),(Q=this.audioBufferManager)==null||Q.maintain(F),i.position=F}this.tracer.log("stallIntervalCallback",(0,v.flattenObject)(i))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=(0,v.interval)(50).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:v.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?i==null?void 0:i.switchToWithPreviousAbort(t,r):i==null?void 0:i.switchTo(t,r):i==null?void 0:i.switchToOld(t,r)}async seek(e,t){var i,s,n,o,u;(0,v.assertNonNullable)(this.element),(0,v.assertNonNullable)(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!=null?i:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),Zt(this.element.buffered,r)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",(0,v.flattenObject)({requestedPosition:e,forcePrecise:t,position:r}))}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>{URL.revokeObjectURL(i.src),i.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.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}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),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,v.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(r=>r.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.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(),r={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let i=this.element.currentTime*1e3,s=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-n<=i&&u.to+n>i&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?s.push(1/0):s.push(u.to));if(s.length){let o=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,r={...r,gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",(0,v.flattenObject)(r)))}}};var gn=class{constructor(e,t){this.fov=e,this.orientation=t}};var vn=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var iS=`attribute vec2 a_vertex;
|
|
71
71
|
attribute vec2 a_texel;
|
|
72
72
|
|
|
73
73
|
varying vec2 v_texel;
|
|
@@ -78,7 +78,7 @@ void main(void) {
|
|
|
78
78
|
// save texel vector to pass to fragment shader
|
|
79
79
|
v_texel = a_texel;
|
|
80
80
|
}
|
|
81
|
-
`;var
|
|
81
|
+
`;var aS=`#ifdef GL_ES
|
|
82
82
|
precision highp float;
|
|
83
83
|
precision highp int;
|
|
84
84
|
#else
|
|
@@ -121,6 +121,6 @@ void main(void) {
|
|
|
121
121
|
// sample using new coordinates
|
|
122
122
|
gl_FragColor = texture2D(u_texture, tc);
|
|
123
123
|
}
|
|
124
|
-
`;var yn=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let i=this.canvas.getContext("webgl");if(!i)throw new Error("Could not initialize WebGL context");this.gl=i,this.container.appendChild(this.canvas),this.camera=new vn(this.params.fov,this.params.orientation),this.cameraRotationManager=new Sn(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),i=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(i,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Zv,this.gl.VERTEX_SHADER),r=this.createShader(eS,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:r=i/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,i=this.camera.fov.y/180/2,s=e-r,n=t-i,o=e+r,u=t-i,l=e+r,c=t+i,d=e-r,p=t+i;return[s,n,o,u,l,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var be=require("@vkontakte/videoplayer-shared/es2018"),bl=class{constructor(){this.isSeeked$=new be.ValueSubject(!1);this.isBuffering$=new be.ValueSubject(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new be.Subscription;this.severeStallOccurred$=new be.ValueSubject(!1)}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add((0,be.combine)({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe((0,be.filter)(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add((0,be.combine)({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{if((0,be.isNullable)(this.lastUniqueVideoTrackSelected))return;let{stallDurationNoDataBeforeQualityDecrease:r,stallCountBeforeQualityDecrease:i,resetQualityRestrictionTimeout:s}=this.qualityLimitsOnStall,n=this.rtt$.getValue(),o=this.throughput$.getValue(),u=this.videoLastDataObtainedTimestamp$.getValue(),l=(0,be.now)(),c=i&&this.currentStallsCount>=i,d=r&&l-this.lastUniqueVideoTrackSelectedTimestamp>=r+n&&l-u>=r+n&&t>=r;(c||d)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,(0,be.isNonNullable)(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=(0,be.now)(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},tS=bl;var Ne=require("@vkontakte/videoplayer-shared/es2018"),Tn=class{constructor(){this.subscription=new Ne.Subscription;this.pipSize$=new Ne.ValueSubject(void 0);this.videoSize$=new Ne.ValueSubject(void 0);this.elementSize$=new Ne.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=Ne.noop}connect({observableVideo:e,video:t}){let r=i=>{let s=i.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add((0,Ne.observeElementSize)(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:i})=>{this.pipSize$.next({width:i.width,height:i.height}),i.addEventListener("resize",r),this.pictureInPictureWindowRemoveEventListener=()=>{i.removeEventListener("resize",r)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add((0,Ne.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,Ne.map)(({videoSize:i,inPip:s,pipSize:n})=>s?n:i)).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 xr=class{constructor(e){this.subscription=new O.Subscription;this.videoState=new H("stopped");this.droppedFramesManager=new Ks;this.stallsManager=new tS;this.elementSizeManager=new Tn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Wi;this.audioTrackSwitchHistory=new Wi;this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.state==="requested"&&(r==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let l=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(i.position-l,i.forcePrecise)}if(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.hostname$.next(void 0),this.videoState.setState("stopped"),A(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&A(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return(0,O.assertNever)(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new yn(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((i=e.projectionData)==null?void 0:i.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 ze(e.source.url),this.params=e,this.video=Me(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(ve(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 gn({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=Ve(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:O.ErrorCategory.WTF,message:`${i} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,O.filter)(l=>!!l.length),(0,O.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$:r.playing$,pause$:r.pause$,tracks:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,O.map)(l=>l.to.state!=="none"),(0,O.filterChanged)());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe((0,O.filterChanged)()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:r.isBuffering$}),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe((0,O.filter)(O.isNonNullable),(0,O.once)()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe((0,O.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(bt(this.video,t.isLooped,i)),this.subscription.add(Ce(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ye(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(Ke(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),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 c=this.player.getStreams();if((0,O.assertNonNullable)(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(nl(h));let f=[];for(let g of h.representations){let S=Nv(g);f.push(S),this.audioTracksMap.set(S,{stream:h,representation:g})}this.audioStreamsMap.set(h,f)}this.params.output.availableAudioStreams$.next(p)}let d=[];for(let p of c.video){d.push(ol(p));let h=[];for(let f of p.representations){let g=_v({...f,streamId:p.id});g&&(h.push(g),this.videoTracksMap.set(g,{stream:p,representation:f}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(d);for(let p of c.text)for(let h of p.representations){let f=Fv(p,h);this.textTracksMap.set(f,{stream:p,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i)),this.subscription.add((0,O.merge)(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,O.fromEvent)(this.video,"progress")).subscribe(async()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,rS.default)(["manifest_ready","running"],l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[p,h]=d,f=[...this.videoTracksMap.keys()].find(S=>{var I;return((I=this.videoTracksMap.get(S))==null?void 0:I.representation.id)===p.id});(0,O.isNonNullable)(f)&&(this.stallsManager.lastVideoTrackSelected=f);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),l==="manifest_ready")await this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),h){let S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",h.id,S)}},i)),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,O.filterChanged)()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(ol(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,O.filterChanged)()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(nl(p))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe((0,O.map)(({to:l})=>l==="ready"),(0,O.filterChanged)());this.subscription.add((0,O.merge)(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,O.observableFrom)(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add((0,O.merge)(o,this.player.state$.stateChangeEnded$,(0,O.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=(0,O.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,O.observableFrom)(["init"])).pipe((0,O.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var F,re,W,J,Z,C,_,ie,he,L,P,q,ee;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(F=e.videoTrack.getState())==null?void 0:F.id,n=[...this.videoTracksMap.keys()].find(({id:Y})=>Y===i),o=t.currentVideoTrack$.getValue(),u=((J=(W=e.videoStream.getState())!=null?W:n&&((re=this.videoTracksMap.get(n))==null?void 0:re.stream))!=null?J:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:Y})=>Y===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=vt(this.video.buffered,this.video.currentTime*1e3),p;this.player.isActiveLive$.getValue()?p=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?p=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let h=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,f=Math.min(d/Math.min(p,h||1/0),1),g=(Z=e.audioStream.getState())!=null?Z:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,S=(C=[...this.audioStreamsMap.keys()].find(({id:Y})=>Y===(g==null?void 0:g.id)))!=null?C:this.audioStreamsMap.keys().next().value,I=0;if(S){if(n&&!r){let Y=Ys(n,c,(_=this.audioStreamsMap.get(S))!=null?_:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,(ie=Y==null?void 0:Y.bitrate)!=null?ie:-1/0)}if(o){let Y=Ys(o,c,(he=this.audioStreamsMap.get(S))!=null?he:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,(L=Y==null?void 0:Y.bitrate)!=null?L:-1/0)}}let E=Jt(c,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:I,forwardBufferHealth:f,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),x=r?E!=null?E:n:n!=null?n:E,k=S&&Eb(x,c,(P=this.audioStreamsMap.get(S))!=null?P:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:f,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),w=(q=this.videoTracksMap.get(x))==null?void 0:q.representation,Q=k&&((ee=this.audioTracksMap.get(k))==null?void 0:ee.representation);if(w&&Q)return[w,Q];if(w&&!Q&&this.audioTracksMap.size===0)return[w,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:O.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),De(this.video),this.tracer.end()}};var _a=class extends xr{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var rr=require("@vkontakte/videoplayer-shared/es2018");var Na=class extends xr{constructor(e){super(e),this.liveOffset=new wt,this.textTracksManager.destroy()}subscribe(){super.subscribe();let{output:e,observableVideo:t,desiredState:r,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),i(this.player.liveLatency$,e.liveLatency$),this.subscription.add(r.isLowLatency.stateChangeEnded$.pipe((0,rr.map)(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add((0,rr.combine)({interval:(0,rr.interval)(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{var n;if(this.videoState.getState()==="playing"){let o=e.position$.getValue()+(s-1);o<=0&&e.position$.next(o),(n=this.liveOffset)==null||n.resetTo(-o*1e3)}})).add((0,rr.combine)({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,rr.map)(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=qv(s);this.params.output.availableTextTracks$.next([n])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,i)})}};var iS=U(Hs(),1);var G=require("@vkontakte/videoplayer-shared/es2018"),ct={};var li=(a,e)=>new G.Observable(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Fa=class{constructor(e){this.subscription=new G.Subscription;this.videoState=new H("initializing");this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((r==null?void 0:r.to)!=="paused"&&i.state==="requested"&&this.seek(i.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:(0,G.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,G.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,G.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,G.assertNever)(e)}break;default:(0,G.assertNever)(t)}};this.textTracksManager=new ze(e.source.url),this.video=Me(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ve(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),De(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:G.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,iS.default)(import("hls.js").then(i=>{e||(ct.Hls=i.default,ct.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){(0,G.assertNonNullable)(ct.Hls,"hls.js not loaded"),this.hls=new ct.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,G.assertNonNullable)(ct.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:G.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=Ve(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(bt(this.video,e.isLooped,r)),this.subscription.add(Ce(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ye(this.video,e.playbackRate,i.playbackRateState$,r)),s(Ke(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe((0,G.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(li(this.hls,ct.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:G.ErrorCategory.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(e.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(li(this.hls,ct.Events.MANIFEST_PARSED).pipe((0,G.map)(({levels:l})=>l.reduce((c,d)=>{var E,x;let p=d.name||d.height.toString(10),{width:h,height:f}=d,g=(x=zt((E=d.attrs.QUALITY)!=null?E:""))!=null?x:(0,G.videoSizeToQuality)({width:h,height:f});if(!g)return c;let S=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,I={id:p.toString(),quality:g,bitrate:d.bitrate/1e3,size:{width:h,height:f},fps:S};return this.trackLevels.set(p,{track:I,level:d}),c.push(I),c},[]))),t.availableVideoTracks$),s(li(this.hls,ct.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",f=d.lang;c.push({id:p,url:h,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(li(this.hls,ct.Events.LEVEL_LOADING).pipe((0,G.map)(({url:l})=>ve(l))),t.hostname$),s(li(this.hls,ct.Events.FRAG_CHANGED),l=>{var p,h,f,g;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=c==null?void 0:c.endPTS)!=null?p:0)-((h=c==null?void 0:c.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((f=d==null?void 0:d.endPTS)!=null?f:0)-((g=d==null?void 0:d.startPTS)!=null?g:0))*1e3)}),this.subscription.add(Yt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=li(this.hls,ct.Events.LEVEL_SWITCHED).pipe((0,G.map)(({level:l})=>n(this.hls.levels[l])));o.pipe((0,G.filter)(G.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Yt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if((0,G.isNullable)(l))return;let c=(f=this.trackLevels.get(l.id))==null?void 0:f.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=(0,G.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,G.observableFrom)(["init"])).pipe((0,G.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await Be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:G.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),A(this.params.desiredState.playbackState,"stopped",!0)}};var aS="X-Playback-Duration",gl=async a=>{var i;let e=await ut(a),t=await e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(aS)?parseInt(e.headers.get(aS),10):void 0};var j=require("@vkontakte/videoplayer-shared/es2018");var Sl=U(Oo(),1);var In=require("@vkontakte/videoplayer-shared/es2018");var nR=a=>{let e=null;if(a.QUALITY&&(e=zt(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=(0,In.videoSizeToQuality)({width:t,height:r})}return e!=null?e:null},oR=(a,e)=>{var s,n;let t=a.split(`
|
|
125
|
-
`),r=[],i=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,Sl.default)(l[1].split(",").map(
|
|
126
|
-
`),s=0;for(let n=0;n<i.length;++n){let o=i[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=i[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(r.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!r.segmentStartTime){let d=new Date(r.vkStartTime).valueOf(),p=new Date(r.programDateTime).valueOf();r.segmentStartTime=p-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):r.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):r.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):r.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);r.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):r.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return r}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,Ge.isNonNullable)(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:r}=t[0].time,{to:i}=t[t.length-1].time;if(e<r||e>i)return;i-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 xe;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:Ge.ErrorCategory.WTF,thrown:t,message:e})}};var qa=class{constructor(e){this.subscription=new j.Subscription;this.videoState=new H("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new j.ValueSubject([]);this.liveOffset=new wt;this.manifestStartTime$=new j.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((i==null?void 0:i.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?A(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),A(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(i==null?void 0:i.to)==="paused"&&(A(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,j.assertNever)(t)}};var r;this.params=e,this.video=Me(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:j.VideoQuality.INVARIANT,url:this.params.source.url};let t=(i,s)=>En(i,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 xn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new ze(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:s})=>{var n;i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:j.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,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:j.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ve(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new j.ValueSubject((r=e.source.maxSeekBackTime)!=null?r:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:j.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=Ve(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.ended$,e.endedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(Ce(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ye(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ke(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(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe((0,j.filterChanged)(),(0,j.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(i.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,j.isNonNullable)(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(ve(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(i.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add((0,j.combine)({startTime:this.manifestStartTime$.pipe((0,j.filter)(j.isNonNullable)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe((0,j.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=(0,j.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,j.observableFrom)(["init"])).pipe((0,j.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}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),De(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if((0,j.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[p,h]of[[c,"mq"],[d,"lq"]]){let f=String(parseFloat(p||""));h&&p&&i.searchParams.set(h,f)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=Ee(i.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),gl(n).then(c=>{var d;if(!(0,j.isNullable)(c))this.maxSeekBackTime$.next(c);else{let p=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();((0,j.isNullable)(p)||!isFinite(p))&&ut(n).then(h=>h.text()).then(h=>{var g;let f=(g=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:g[1];if(f){let S=new URL(f,n).toString();gl(S).then(I=>{(0,j.isNullable)(I)||this.maxSeekBackTime$.next(I)})}}).catch(()=>{})}})}playIfAllowed(){Be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:j.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=Ee(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 X=require("@vkontakte/videoplayer-shared/es2018");var Ua=class{constructor(e){this.subscription=new X.Subscription;this.videoState=new H("stopped");this.manifests$=new X.ValueSubject([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?A(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,X.assertNever)(t)}};this.textTracksManager=new ze(e.source.url),this.params=e,this.video=Me(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:X.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(ve(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),En(Ee(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:X.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&(!i||!i.from)&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:X.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},i=Ve(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(i.timeUpdate$,e.position$),s(i.durationChange$,e.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.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,X.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(bt(this.video,t.isLooped,r)),this.subscription.add(Ce(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ye(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(i.loadedMetadata$.subscribe(()=>{var h;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,X.isNonNullable)(l.to)){let f=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let g=this.manifests$.getValue().find(S=>S.id===f);g&&(this.params.output.currentVideoTrack$.next(g),this.params.output.hostname$.next(ve(g.url)))}let d=this.params.desiredState.playbackRate.getState(),p=(h=this.params.output.element$.getValue())==null?void 0:h.playbackRate;if(d!==p){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(d),f.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe((0,X.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!X.clientChecker.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,X.merge)((0,X.fromEvent)(o,"addtrack"),(0,X.fromEvent)(o,"removetrack"),(0,X.fromEvent)(o,"change"),(0,X.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=(0,X.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,X.observableFrom)(["init"])).pipe((0,X.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),De(this.video)}prepare(){var s,n;let e=this.selectManifest();if((0,X.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){Be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:X.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var nS=U(jr(),1),yl=U(ei(),1),oS=U(Kt(),1);var oe=require("@vkontakte/videoplayer-shared/es2018");var Ha=class{constructor(e){this.subscription=new oe.Subscription;this.videoState=new H("stopped");this.trackUrls={};this.textTracksManager=new ze;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to);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((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?A(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return(0,oe.assertNever)(e)}};this.params=e,this.video=Me(e.container,e.tuning),this.params.output.element$.next(this.video),(0,nS.default)(this.params.source).reverse().forEach(([t,r],i)=>{let s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,yl.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,r=o=>{e.error$.next({id:"MpegProvider",category:oe.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},i=Ve(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.timeUpdate$,e.position$),s(i.durationChange$,e.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.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,oe.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(bt(this.video,t.isLooped,r)),this.subscription.add(Ce(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ye(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ke(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&(0,oe.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(c),p.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=(0,oe.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,oe.observableFrom)(["init"])).pipe((0,oe.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),De(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;(0,oe.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,oe.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Da(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ve(t))}playIfAllowed(){Be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:oe.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,c;this.params.output.autoVideoTrackLimits$.next(e);let t=d=>{this.params.output.currentVideoTrack$.next(d),this.params.desiredState.videoTrack.startTransitionTo(d)},r=d=>{let p=Jt(n,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:d,abrLogger:this.params.dependencies.abrLogger});t(p)},i=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,s=!!(e.max||e.min),n=(0,yl.default)(this.trackUrls).map(d=>d.track);if(!i||!s||Gi({limits:e,lowestAvailableQuality:(c=(0,oS.default)(n,-1))==null?void 0:c.quality,highestAvailableQuality:n[0].quality})){r();return}let o=e.max?(0,oe.isLowerOrEqual)(i,e.max):!0,u=e.min?(0,oe.isHigherOrEqual)(i,e.min):!0;o&&u||r(e)}};var ue=require("@vkontakte/videoplayer-shared/es2018");var lS=require("@vkontakte/videoplayer-shared/es2018"),uS=["stun:videostun.mycdn.me:80"],lR=1e3,cR=3,Tl=()=>null,Pn=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=Tl;this.externalStopCallback=Tl;this.externalErrorCallback=Tl;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:uS}]};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:lS.ErrorCategory.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(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),lR)}normalizeOptions(e={}){let t={stunServerList:uS,maxRetryNumber:cR,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var ja=class{constructor(e){this.videoState=new H("stopped");this.maxSeekBackTime$=new ue.ValueSubject(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return(0,ue.assertNever)(e)}};this.subscription=new ue.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Me(e.container,e.tuning),this.liveStreamClient=new Pn(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),De(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:ue.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};(0,ue.merge)(this.videoState.stateChangeStarted$.pipe((0,ue.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,ue.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=Ve(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(i.timeUpdate$,e.liveTime$),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(Ke(this.video),this.params.output.elementVisible$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(i.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ce(this.video,t.volume,i.volumeState$,r)).add(i.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return(0,ue.assertNever)(n.to)}},r)).add((0,ue.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,ue.observableFrom)(["init"])).pipe((0,ue.debounce)(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ve(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:ue.VideoQuality.INVARIANT}),this.video.srcObject=e,A(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:ue.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ue.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Qa=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};var y=require("@vkontakte/videoplayer-shared/es2018");var Dt=require("@vkontakte/videoplayer-shared/es2018"),cS=a=>new Dt.Observable(e=>{let t=new Dt.Subscription,r=a.desiredPlaybackState$.stateChangeStarted$.pipe((0,Dt.map)(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe((0,Dt.map)(({type:l})=>l!==void 0)),n=new Dt.Subject,o=0,u="unknown";return t.add(r.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(i.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var Ze=require("@vkontakte/videoplayer-shared/es2018");function dS(){return new(window.AudioContext||window.webkitAudioContext)}var pS=require("@vkontakte/videoplayer-shared/es2018");var Ga=class Ga{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new xe;this.subscriptions=new Ze.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,Ze.filter)(s=>!!s.type),(0,Ze.once)()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){pS.clientChecker.isSafari&&e!=="MPEG"||this.subscriptions.add((0,Ze.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,Ze.filter)(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),(0,Ze.once)()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(r=>{r||this.destroy()}).catch(r=>{this.handleError(r),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,r=dS();this.audioContext=r;let i=r.createGain();if(this.gainNode=i,i.gain.value=t,i.connect(r.destination),r.state==="suspended"&&(await r.resume(),this.destroyController.signal.aborted))return!1;let s=r.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(i),!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:Ga.errorId,category:Ze.ErrorCategory.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Ga.errorId} exception`,thrown:e})}};Ga.errorId="VolumeMultiplierManager";var ci=Ga;var dR={chunkDuration:5e3,maxParallelRequests:5},Wa=class{constructor(e){this.current$=new y.ValueSubject({type:void 0});this.providerError$=new y.Subject;this.noAvailableProvidersError$=new y.Subject;this.volumeMultiplierError$=new y.Subject;this.providerOutput={position$:new y.ValueSubject(0),duration$:new y.ValueSubject(1/0),volume$:new y.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new y.ValueSubject([]),currentVideoStream$:new y.ValueSubject(void 0),availableVideoTracks$:new y.ValueSubject([]),currentVideoTrack$:new y.ValueSubject(void 0),availableAudioStreams$:new y.ValueSubject([]),currentAudioStream$:new y.ValueSubject(void 0),availableAudioTracks$:new y.ValueSubject([]),currentVideoSegmentLength$:new y.ValueSubject(0),currentAudioSegmentLength$:new y.ValueSubject(0),isAudioAvailable$:new y.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new y.ValueSubject(!1),autoVideoTrackLimits$:new y.ValueSubject(void 0),currentBuffer$:new y.ValueSubject(void 0),isBuffering$:new y.ValueSubject(!0),error$:new y.Subject,warning$:new y.Subject,willSeekEvent$:new y.Subject,soundProhibitedEvent$:new y.Subject,seekedEvent$:new y.Subject,loopedEvent$:new y.Subject,endedEvent$:new y.Subject,firstBytesEvent$:new y.Subject,loadedMetadataEvent$:new y.Subject,firstFrameEvent$:new y.Subject,canplay$:new y.Subject,isLive$:new y.ValueSubject(void 0),isLowLatency$:new y.ValueSubject(!1),canChangePlaybackSpeed$:new y.ValueSubject(!0),liveTime$:new y.ValueSubject(void 0),liveBufferTime$:new y.ValueSubject(void 0),liveLatency$:new y.ValueSubject(void 0),availableTextTracks$:new y.ValueSubject([]),currentTextTrack$:new y.ValueSubject(void 0),hostname$:new y.ValueSubject(void 0),httpConnectionType$:new y.ValueSubject(void 0),httpConnectionReused$:new y.ValueSubject(void 0),inPiP$:new y.ValueSubject(!1),inFullscreen$:new y.ValueSubject(!1),element$:new y.ValueSubject(void 0),elementVisible$:new y.ValueSubject(!0),availableSources$:new y.ValueSubject(void 0),is3DVideo$:new y.ValueSubject(!1),playbackState$:new y.ValueSubject(""),getCurrentTime$:new y.ValueSubject(null)};this.subscription=new y.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=fg([...gg(this.params.tuning),...bg(this.params.tuning)],this.params.tuning).filter(l=>(0,y.isNonNullable)(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,Il.default)(i,l)),...t.filter(l=>(0,Il.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,y.flattenObject)(s)),this.screenFormatsIterator=new Qa(s);let n=[...Hu(!0),...Hu(!1)];this.chromecastFormatsIterator=new Qa(n.filter(l=>(0,y.isNonNullable)(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&ci.isSupported()&&(this.volumeMultiplierManager=new ci(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){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,y.isNullable)(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:y.ErrorCategory.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return(0,y.assertNever)(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,y.assertNonNullable)(o),new _a({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Na({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),ai||!this.params.tuning.useHlsJs?new Ua({...n,source:o}):new Fa({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new qa({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Ha({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Db({...n,source:o,config:{...dR,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new ja({container:r,source:o,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,y.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,y.assertNonNullable)(o),new ji({connection:o,meta:s,container:r,source:t,format:e,desiredState:i,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return(0,y.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,y.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,y.assertNever)(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:r(e.url)}}return(0,mS.default)((0,hS.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new y.Subscription,t=!1,r=0;return e.add((0,y.merge)(this.providerOutput.error$.pipe((0,y.filter)(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),cS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,y.map)(i=>({id:`ProviderHangup:${i}`,category:y.ErrorCategory.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let i=this.params.desiredState.playbackState.transitionEnded$.pipe((0,y.filter)(({to:s})=>s==="playing"),(0,y.once)()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination,n={error:i,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=i.category===y.ErrorCategory.NETWORK,u=i.category===y.ErrorCategory.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=r<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c},c?(r++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",(0,y.flattenObject)(n))})),e}};var V=require("@vkontakte/videoplayer-shared/es2018");var pR=5e3,fS="one_video_throughput",bS="one_video_rtt",Ct=window.navigator.connection,gS=()=>{let a=Ct==null?void 0:Ct.downlink;if((0,V.isNonNullable)(a)&&a!==10)return a*1e3},vS=()=>{let a=Ct==null?void 0:Ct.rtt;if((0,V.isNonNullable)(a)&&a!==3e3)return a},SS=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},El=class a{constructor(e){this.subscription=new V.Subscription;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(fS)||(e.useBrowserEstimation?gS():void 0)||pR,r=(s=(i=a.load(bS))!=null?i:e.useBrowserEstimation?vS():void 0)!=null?s:0;if(this.throughput$=new V.ValueSubject(t),this.rtt$=new V.ValueSubject(r),this.rttAdjustedThroughput$=new V.ValueSubject(SS(t,r,e.rttPenaltyRequestSize)),this.throughput=Er.getSmoothedValue(t,-1,e),this.rtt=Er.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=gS();u&&this.throughput.next(u);let l=vS();(0,V.isNonNullable)(l)&&this.rtt.next(l)};Ct&&"onchange"in Ct&&this.subscription.add((0,V.fromEvent)(Ct,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{V.safeStorage.set(fS,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{V.safeStorage.set(bS,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,V.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,V.map)(({throughput:n,rtt:o})=>SS(n,o,e.rttPenaltyRequestSize)),(0,V.filter)(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=(0,V.now)(),i=new V.Subscription;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add((0,V.fromEvent)(e,"progress").pipe((0,V.once)()).subscribe(s=>{t=s.loaded,r=(0,V.now)()}));break;case 1:case 0:i.add((0,V.fromEvent)(e,"loadstart").subscribe(()=>{t=0,r=(0,V.now)()}));break}i.add((0,V.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,V.now)(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=(0,V.now)(),n=0,o=(0,V.now)(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(i,(0,V.now)()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=(0,V.now)();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=d.byteLength,s=(0,V.now)()}else n+=d.byteLength;o=(0,V.now)()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,V.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,V.now)()-o,this.concurrentDownloads.size),n=0,o=(0,V.now)());await(r==null?void 0:r.read().then(l,u))}};this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=V.safeStorage.get(e);if((0,V.isNonNullable)(t))return(r=parseInt(t,10))!=null?r:void 0}},yS=El;var Pr=require("@vkontakte/videoplayer-shared/es2018"),TS={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Pr.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Pr.VideoQuality.Q_720P,trafficSavingLimit:Pr.VideoQuality.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Pr.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationNoDataBeforeQualityDecrease:500,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:72e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1},IS=a=>{var e;return{...(0,Pr.fillWithDefault)(a,TS),configName:[...(e=a.configName)!=null?e:[],...TS.configName]}};var m=require("@vkontakte/videoplayer-shared/es2018");var Vt=require("@vkontakte/videoplayer-shared/es2018"),xl=({seekState:a,position$:e})=>(0,Vt.merge)(a.stateChangeEnded$.pipe((0,Vt.map)(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),(0,Vt.filter)(Vt.isNonNullable)),e.pipe((0,Vt.filter)(()=>a.getState().state==="none")));var ES=require("@vkontakte/videoplayer-shared/es2018"),xS=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return(0,ES.assertNonNullable)(e,`Wrong container or containerId {${a.container}}`),e};var wn=require("@vkontakte/videoplayer-shared/es2018"),PS=(a,e,t,r)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe((0,wn.filter)(i=>i.length>0),(0,wn.once)()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Ya=class{constructor(e={configName:[]},t=m.Tracer.createRootTracer(!1)){this.subscription=new m.Subscription;this.logger=new m.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new m.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new H("stopped"),seekState:new H({state:"none"}),volume:new H({volume:1,muted:!1}),videoTrack:new H(void 0),videoStream:new H(void 0),audioStream:new H(void 0),autoVideoTrackSwitching:new H(!0),autoVideoTrackLimits:new H({}),isLooped:new H(!1),isLowLatency:new H(!1),playbackRate:new H(1),externalTextTracks:new H([]),internalTextTracks:new H([]),currentTextTrack:new H(void 0),textTrackCuesSettings:new H({}),cameraOrientation:new H({x:0,y:0})};this.info={playbackState$:new m.ValueSubject("stopped"),position$:new m.ValueSubject(0),duration$:new m.ValueSubject(1/0),muted$:new m.ValueSubject(!1),volume$:new m.ValueSubject(1),availableVideoStreams$:new m.ValueSubject([]),currentVideoStream$:new m.ValueSubject(void 0),availableQualities$:new m.ValueSubject([]),availableQualitiesFps$:new m.ValueSubject({}),currentQuality$:new m.ValueSubject(void 0),isAutoQualityEnabled$:new m.ValueSubject(!0),autoQualityLimitingAvailable$:new m.ValueSubject(!1),autoQualityLimits$:new m.ValueSubject({}),predefinedQualityLimitType$:new m.ValueSubject("unknown"),availableAudioStreams$:new m.ValueSubject([]),currentAudioStream$:new m.ValueSubject(void 0),availableAudioTracks$:new m.ValueSubject([]),isAudioAvailable$:new m.ValueSubject(!0),currentPlaybackRate$:new m.ValueSubject(1),currentBuffer$:new m.ValueSubject({start:0,end:0}),isBuffering$:new m.ValueSubject(!0),isStalled$:new m.ValueSubject(!1),isEnded$:new m.ValueSubject(!1),isLooped$:new m.ValueSubject(!1),isLive$:new m.ValueSubject(void 0),canChangePlaybackSpeed$:new m.ValueSubject(void 0),atLiveEdge$:new m.ValueSubject(void 0),atLiveDurationEdge$:new m.ValueSubject(void 0),liveTime$:new m.ValueSubject(void 0),liveBufferTime$:new m.ValueSubject(void 0),liveLatency$:new m.ValueSubject(void 0),currentFormat$:new m.ValueSubject(void 0),availableTextTracks$:new m.ValueSubject([]),currentTextTrack$:new m.ValueSubject(void 0),throughputEstimation$:new m.ValueSubject(void 0),rttEstimation$:new m.ValueSubject(void 0),videoBitrate$:new m.ValueSubject(void 0),hostname$:new m.ValueSubject(void 0),httpConnectionType$:new m.ValueSubject(void 0),httpConnectionReused$:new m.ValueSubject(void 0),surface$:new m.ValueSubject("none"),chromecastState$:new m.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new m.ValueSubject(void 0),intrinsicVideoSize$:new m.ValueSubject(void 0),availableSources$:new m.ValueSubject(void 0),is3DVideo$:new m.ValueSubject(!1),currentVideoSegmentLength$:new m.ValueSubject(0),currentAudioSegmentLength$:new m.ValueSubject(0)};this.events={inited$:new m.Subject,ready$:new m.Subject,started$:new m.Subject,playing$:new m.Subject,paused$:new m.Subject,stopped$:new m.Subject,willStart$:new m.Subject,willResume$:new m.Subject,willPause$:new m.Subject,willStop$:new m.Subject,willDestruct$:new m.Subject,watchCoverageRecord$:new m.Subject,watchCoverageLive$:new m.Subject,managedError$:new m.Subject,fatalError$:new m.Subject,ended$:new m.Subject,looped$:new m.Subject,seeked$:new m.Subject,willSeek$:new m.Subject,autoplaySoundProhibited$:new m.Subject,firstBytes$:new m.Subject,loadedMetadata$:new m.Subject,firstFrame$:new m.Subject,canplay$:new m.Subject,log$:new m.Subject};this.experimental={element$:new m.ValueSubject(void 0),tuningConfigName$:new m.ValueSubject([]),enableDebugTelemetry$:new m.ValueSubject(!1),dumpTelemetry:bb,getCurrentTime$:new m.ValueSubject(null)};if(this.initLogs(),this.tuning=IS(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new fs({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new yS(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new m.InternalsExposure("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,i,s)=>{let n=Reflect.get(r,i,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(h,f)=>{let g=typeof f;return(0,wS.default)(["number","string","boolean"],g)?f:f===null?null:`<${g}>`})),c=`Player.${String(i)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:m.ErrorCategory.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var i,s,n,o;this.config=e;let{container:t,...r}=e;return this.tracer.log("initVideo",(0,m.flattenObject)(r)),this.domContainer=xS(e),this.chromecastInitializer.contentId=(i=e.meta)==null?void 0:i.videoId,this.providerContainer=new Wa({sources:e.sources,meta:(s=e.meta)!=null?s:{},failoverHosts:(n=e.failoverHosts)!=null?n:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),(o=this.internalsExposure)==null||o.expose({config:e,logger:this.logger,tuning:this.tuning}),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Xi()?(this.tracer.log("request play from hidden tab"),(0,m.fromEvent)(document,"visibilitychange").pipe((0,m.once)()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue(),s=e;return e>=r&&!i&&(s=r-.2),this.tracer.log("seekTime",{duration:r,isLive:i,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){(0,m.assertNonNullable)(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe((0,m.filter)(r=>r.length>0),(0,m.once)()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",(0,m.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPredefinedQualityLimits(e){let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection,i;switch(e){case"high_quality":i={min:t,max:void 0};break;case"traffic_saving":i={max:r,min:void 0};break;default:i={max:void 0,min:void 0}}return this.setAutoQualityLimits(i),this}setPlaybackRate(e){var r;(0,m.assertNonNullable)(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",(0,m.flattenObject)(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return PS(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),r=this.desiredState.isLowLatency.getState();return!t||r===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let i=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:i.x+s.x,y:i.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if((0,m.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return(0,m.isNonNullable)(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,r;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((r=e==null?void 0:e.provider)!=null&&r.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:i})=>r||i||0,0),height:e.reduce((r,{height:i})=>r||i||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add((0,m.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,m.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Mu({limits:e,highQualityLimit:t,trafficSavingLimit:r}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,m.filter)(({from:e})=>e==="stopped"),(0,m.once)()).subscribe(()=>{this.initedAt=(0,m.now)(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",(0,m.flattenObject)(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:m.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe((0,m.once)()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",(0,m.flattenObject)(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,m.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,m.map)(n=>n.destination),(0,m.filterChanged)()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add((0,m.combine)({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe((0,m.map)(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>(0,m.isInvariantQuality)(u)?1:(0,m.isInvariantQuality)(l)?-1:(0,m.isHigher)(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe((0,m.filterChanged)()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe((0,m.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe((0,m.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,m.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,m.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,m.filterChanged)()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe((0,m.map)(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add((0,m.combine)({hasLiveOffsetByPaused:(0,m.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,m.map)(n=>n.to),(0,m.filterChanged)(),(0,m.map)(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add((0,m.combine)({atLiveEdge:(0,m.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:xl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,m.map)(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),(0,m.filterChanged)(),(0,m.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,m.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,m.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,m.map)(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,m.filterChanged)(),(0,m.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,m.map)(n=>n.muted),(0,m.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,m.map)(n=>n.volume),(0,m.filterChanged)()).subscribe(this.info.volume$)).add(xl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,m.merge)(e.providerOutput.endedEvent$.pipe((0,m.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,m.mapTo)(!1))).pipe((0,m.filterChanged)()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe((0,m.map)(n=>({id:n?`No${n}`:"NoProviders",category:m.ErrorCategory.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe((0,m.once)(),(0,m.map)(n=>n!=null?n:(0,m.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,m.once)(),(0,m.map)(()=>(0,m.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,m.once)(),(0,m.map)(()=>(0,m.now)()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new m.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new m.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,m.filter)(({to:n})=>n==="playing"),(0,m.once)()).subscribe(()=>r.next(!1)));let i=0,s=(0,m.merge)(e.providerOutput.isBuffering$,t,r).pipe((0,m.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),(0,m.filterChanged)());this.subscription.add(s.subscribe(n=>{n?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))})),this.subscription.add((0,m.merge)(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add((0,m.merge)(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,m.map)(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new m.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,m.filterChanged)((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,m.filter)(r=>r.length>0),(0,m.once)()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i,s;let t;this.wasSetStartedQuality=!0;let r=(s=this.explicitInitialQuality)!=null?s:(i=this.desiredState.videoTrack.getState())==null?void 0:i.quality;r&&(t=e.find(({quality:n})=>n===r),t||this.setAutoQuality(!0)),t||(t=Jt(e,{container:this.domContainer.getBoundingClientRect(),estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add((0,m.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,m.map)(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;(0,m.assertNonNullable)(this.providerContainer),(0,m.assertNonNullable)(e),fb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>mb(r)),this.providerContainer.current$.subscribe(({type:r})=>Qi("provider",r)),e.duration$.subscribe(r=>Qi("duration",r)),e.availableVideoTracks$.pipe((0,m.filter)(r=>!!r.length),(0,m.once)()).subscribe(r=>Qi("tracks",r)),this.events.fatalError$.subscribe(new Le("fatalError")),this.events.managedError$.subscribe(new Le("managedError")),e.position$.subscribe(new Le("position")),e.currentVideoTrack$.pipe((0,m.map)(r=>r==null?void 0:r.quality)).subscribe(new Le("quality")),this.info.currentBuffer$.subscribe(new Le("buffer")),e.isBuffering$.subscribe(new Le("isBuffering"))].forEach(r=>this.subscription.add(r)),Qi("codecs",mg())}initTracerSubscription(){let e=(0,m.getTraceSubscriptionMethod)(this.tracer.log.bind(this.tracer)),t=(0,m.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe((0,m.filterChanged)()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add((0,m.combine)({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe((0,m.filter)(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),(0,m.filterChanged)((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,m.filter)(r=>r>0),(0,m.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,m.filter)(r=>r>0),(0,m.filterChanged)()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add((0,m.combine)({currentBuffer:this.info.currentBuffer$.pipe((0,m.filter)(r=>r.end>0),(0,m.filterChanged)((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe((0,m.filterChanged)())}).pipe((0,m.throttle)(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe((0,m.filterChanged)()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe((0,m.filterChanged)()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe((0,m.filterChanged)()).subscribe(e("canChangePlaybackSpeed"))).add((0,m.combine)({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe((0,m.filter)(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),(0,m.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,m.filterChanged)(),(0,m.filter)(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,m.filterChanged)(),(0,m.filter)(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe((0,m.filterChanged)()).subscribe(e("muted"))).add(this.info.volume$.pipe((0,m.filterChanged)()).subscribe(e("volume"))).add(this.info.isEnded$.pipe((0,m.filterChanged)(),(0,m.filter)(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add((0,m.combine)({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe((0,m.filter)(({throughputEstimation:r,rtt:i})=>!!r&&!!i),(0,m.throttle)(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe((0,m.filterChanged)(),(0,m.filter)(r=>r===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:m.ErrorCategory.DOM,message:String(i)})})};this.subscription.add((0,m.merge)((0,m.fromEvent)(document,"visibilitychange"),(0,m.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);i&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(i=>i.quality===t);this.tracer.log("setVideoTrackIdByQuality",(0,m.flattenObject)({quality:t,availableTracks:(0,m.flattenObject)(e),track:(0,m.flattenObject)(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};var yt=require("@vkontakte/videoplayer-shared/es2018"),hR=`@vkontakte/videoplayer-core@${Mn}`;
|
|
124
|
+
`;var Sn=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let i=this.canvas.getContext("webgl");if(!i)throw new Error("Could not initialize WebGL context");this.gl=i,this.container.appendChild(this.canvas),this.camera=new gn(this.params.fov,this.params.orientation),this.cameraRotationManager=new vn(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),i=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(i,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(iS,this.gl.VERTEX_SHADER),r=this.createShader(aS,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:r=i/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,i=this.camera.fov.y/180/2,s=e-r,n=t-i,o=e+r,u=t-i,l=e+r,c=t+i,d=e-r,p=t+i;return[s,n,o,u,l,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var ge=require("@vkontakte/videoplayer-shared/es2018"),bl=class{constructor(){this.isSeeked$=new ge.ValueSubject(!1);this.isBuffering$=new ge.ValueSubject(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new ge.Subscription;this.severeStallOccurred$=new ge.ValueSubject(!1)}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add((0,ge.combine)({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe((0,ge.filter)(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add((0,ge.combine)({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{if((0,ge.isNullable)(this.lastUniqueVideoTrackSelected))return;let{stallDurationNoDataBeforeQualityDecrease:r,stallCountBeforeQualityDecrease:i,resetQualityRestrictionTimeout:s}=this.qualityLimitsOnStall,n=this.rtt$.getValue(),o=this.throughput$.getValue(),u=this.videoLastDataObtainedTimestamp$.getValue(),l=(0,ge.now)(),c=i&&this.currentStallsCount>=i,d=r&&l-this.lastUniqueVideoTrackSelectedTimestamp>=r+n&&l-u>=r+n&&t>=r;(c||d)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,(0,ge.isNonNullable)(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=(0,ge.now)(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},sS=bl;var Fe=require("@vkontakte/videoplayer-shared/es2018"),yn=class{constructor(){this.subscription=new Fe.Subscription;this.pipSize$=new Fe.ValueSubject(void 0);this.videoSize$=new Fe.ValueSubject(void 0);this.elementSize$=new Fe.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=Fe.noop}connect({observableVideo:e,video:t}){let r=i=>{let s=i.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add((0,Fe.observeElementSize)(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:i})=>{this.pipSize$.next({width:i.width,height:i.height}),i.addEventListener("resize",r),this.pictureInPictureWindowRemoveEventListener=()=>{i.removeEventListener("resize",r)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add((0,Fe.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,Fe.map)(({videoSize:i,inPip:s,pipSize:n})=>s?n:i)).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 xr=class{constructor(e){this.subscription=new O.Subscription;this.videoState=new H("stopped");this.droppedFramesManager=new zs;this.stallsManager=new sS;this.elementSizeManager=new yn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Wi;this.audioTrackSwitchHistory=new Wi;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.state==="requested"&&(r==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(i.position,i.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.hostname$.next(void 0),this.videoState.setState("stopped"),k(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"),k(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&k(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.seek(0,!1)):(r==null?void 0:r.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return(0,O.assertNever)(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new Sn(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((i=e.projectionData)==null?void 0:i.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 Ke(e.source.url),this.params=e,this.video=De(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(Se(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 bn({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=Be(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:O.ErrorCategory.WTF,message:`${i} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,O.filter)(l=>!!l.length),(0,O.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$:r.playing$,pause$:r.pause$,tracks:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,O.map)(l=>l.to.state!=="none"),(0,O.filterChanged)());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe((0,O.filterChanged)()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:r.isBuffering$}),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe((0,O.filter)(O.isNonNullable),(0,O.once)()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe((0,O.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(gt(this.video,t.isLooped,i)),this.subscription.add(Ve(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ze(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(Xe(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),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 c=this.player.getStreams();if((0,O.assertNonNullable)(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(sl(h));let f=[];for(let g of h.representations){let S=Hv(g);f.push(S),this.audioTracksMap.set(S,{stream:h,representation:g})}this.audioStreamsMap.set(h,f)}this.params.output.availableAudioStreams$.next(p)}let d=[];for(let p of c.video){d.push(nl(p));let h=[];for(let f of p.representations){let g=Uv({...f,streamId:p.id});g&&(h.push(g),this.videoTracksMap.set(g,{stream:p,representation:f}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(d);for(let p of c.text)for(let h of p.representations){let f=jv(p,h);this.textTracksMap.set(f,{stream:p,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i)),this.subscription.add((0,O.merge)(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,O.fromEvent)(this.video,"progress")).subscribe(async()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,nS.default)(["manifest_ready","running"],l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[p,h]=d,f=[...this.videoTracksMap.keys()].find(S=>{var I;return((I=this.videoTracksMap.get(S))==null?void 0:I.representation.id)===p.id});(0,O.isNonNullable)(f)&&(this.stallsManager.lastVideoTrackSelected=f);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),l==="manifest_ready")await this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),h){let S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",h.id,S)}},i)),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,O.filterChanged)()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(nl(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,O.filterChanged)()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(sl(p))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe((0,O.map)(({to:l})=>l==="ready"),(0,O.filterChanged)());this.subscription.add((0,O.merge)(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,O.observableFrom)(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add((0,O.merge)(o,this.player.state$.stateChangeEnded$,(0,O.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=(0,O.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,O.observableFrom)(["init"])).pipe((0,O.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var F,re,W,J,Z,C,_,ie,me,L,P,q,ee;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(F=e.videoTrack.getState())==null?void 0:F.id,n=[...this.videoTracksMap.keys()].find(({id:Y})=>Y===i),o=t.currentVideoTrack$.getValue(),u=((J=(W=e.videoStream.getState())!=null?W:n&&((re=this.videoTracksMap.get(n))==null?void 0:re.stream))!=null?J:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:Y})=>Y===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=St(this.video.buffered,this.video.currentTime*1e3),p;this.player.isActiveLive$.getValue()?p=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?p=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let h=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,f=Math.min(d/Math.min(p,h||1/0),1),g=(Z=e.audioStream.getState())!=null?Z:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,S=(C=[...this.audioStreamsMap.keys()].find(({id:Y})=>Y===(g==null?void 0:g.id)))!=null?C:this.audioStreamsMap.keys().next().value,I=0;if(S){if(n&&!r){let Y=Ws(n,c,(_=this.audioStreamsMap.get(S))!=null?_:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,(ie=Y==null?void 0:Y.bitrate)!=null?ie:-1/0)}if(o){let Y=Ws(o,c,(me=this.audioStreamsMap.get(S))!=null?me:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,(L=Y==null?void 0:Y.bitrate)!=null?L:-1/0)}}let x=Jt(c,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:I,forwardBufferHealth:f,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),E=r?x!=null?x:n:n!=null?n:x,A=S&&Ab(E,c,(P=this.audioStreamsMap.get(S))!=null?P:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:f,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),w=(q=this.videoTracksMap.get(E))==null?void 0:q.representation,Q=A&&((ee=this.audioTracksMap.get(A))==null?void 0:ee.representation);if(w&&Q)return[w,Q];if(w&&!Q&&this.audioTracksMap.size===0)return[w,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Oe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:O.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),Ce(this.video),this.tracer.end()}};var Oa=class extends xr{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var ue=require("@vkontakte/videoplayer-shared/es2018");var _a=class extends xr{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:r,desiredState:i,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),s(r.timeUpdate$,t.liveBufferTime$),s(this.player.liveSeekableDuration$,t.duration$),s(this.player.liveLatency$,t.liveLatency$);let n=new ue.ValueSubject(1);s(r.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(i.isLowLatency.stateChangeEnded$.pipe((0,ue.map)(o=>o.to)).subscribe(this.player.isLowLatency$)).add((0,ue.combine)({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,ue.map)(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add((0,ue.combine)({position:t.position$,liveStreamStatus:this.player.liveStreamStatus$}).subscribe(({position:o,liveStreamStatus:u})=>t.isLiveEnded$.next(u!=="active"&&o===0))).add((0,ue.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,ue.merge)(r.playbackRateState$,new ue.ValueSubject(1))}).pipe((0,ue.filter)(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||u<1-d||this.video.paused||(0,ue.isNullable)(l)||(e=o-l)})).add((0,ue.combine)({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,ue.merge)(r.playbackRateState$,new ue.ValueSubject(1))}).pipe((0,ue.filterChanged)((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&l>=1-d||(0,ue.isNullable)(o)||(0,ue.isNullable)(u))return;let p=-1*(u-o-e);t.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=Qv(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(r).then(()=>{this.params.output.position$.next(e/1e3)})}};var oS=U(Us(),1);var G=require("@vkontakte/videoplayer-shared/es2018"),dt={};var li=(a,e)=>new G.Observable(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Na=class{constructor(e){this.subscription=new G.Subscription;this.videoState=new H("initializing");this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((r==null?void 0:r.to)!=="paused"&&i.state==="requested"&&this.seek(i.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:(0,G.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,G.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,G.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,G.assertNever)(e)}break;default:(0,G.assertNever)(t)}};this.textTracksManager=new Ke(e.source.url),this.video=De(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Se(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),Ce(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:G.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,oS.default)(import("hls.js").then(i=>{e||(dt.Hls=i.default,dt.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){(0,G.assertNonNullable)(dt.Hls,"hls.js not loaded"),this.hls=new dt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,G.assertNonNullable)(dt.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:G.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=Be(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(gt(this.video,e.isLooped,r)),this.subscription.add(Ve(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ze(this.video,e.playbackRate,i.playbackRateState$,r)),s(Xe(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe((0,G.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(li(this.hls,dt.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:G.ErrorCategory.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(e.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(li(this.hls,dt.Events.MANIFEST_PARSED).pipe((0,G.map)(({levels:l})=>l.reduce((c,d)=>{var x,E;let p=d.name||d.height.toString(10),{width:h,height:f}=d,g=(E=zt((x=d.attrs.QUALITY)!=null?x:""))!=null?E:(0,G.videoSizeToQuality)({width:h,height:f});if(!g)return c;let S=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,I={id:p.toString(),quality:g,bitrate:d.bitrate/1e3,size:{width:h,height:f},fps:S};return this.trackLevels.set(p,{track:I,level:d}),c.push(I),c},[]))),t.availableVideoTracks$),s(li(this.hls,dt.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",f=d.lang;c.push({id:p,url:h,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(li(this.hls,dt.Events.LEVEL_LOADING).pipe((0,G.map)(({url:l})=>Se(l))),t.hostname$),s(li(this.hls,dt.Events.FRAG_CHANGED),l=>{var p,h,f,g;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=c==null?void 0:c.endPTS)!=null?p:0)-((h=c==null?void 0:c.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((f=d==null?void 0:d.endPTS)!=null?f:0)-((g=d==null?void 0:d.startPTS)!=null?g:0))*1e3)}),this.subscription.add(Yt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=li(this.hls,dt.Events.LEVEL_SWITCHED).pipe((0,G.map)(({level:l})=>n(this.hls.levels[l])));o.pipe((0,G.filter)(G.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Yt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if((0,G.isNullable)(l))return;let c=(f=this.trackLevels.get(l.id))==null?void 0:f.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=(0,G.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,G.observableFrom)(["init"])).pipe((0,G.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await Oe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:G.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0)}};var uS="X-Playback-Duration",gl=async a=>{var i;let e=await lt(a),t=await e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(uS)?parseInt(e.headers.get(uS),10):void 0};var j=require("@vkontakte/videoplayer-shared/es2018");var Sl=U(Bo(),1);var Tn=require("@vkontakte/videoplayer-shared/es2018");var cR=a=>{let e=null;if(a.QUALITY&&(e=zt(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=(0,Tn.videoSizeToQuality)({width:t,height:r})}return e!=null?e:null},dR=(a,e)=>{var s,n;let t=a.split(`
|
|
125
|
+
`),r=[],i=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,Sl.default)(l[1].split(",").map(x=>x.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=cR(d),f;d.BANDWIDTH&&(f=parseInt(d.BANDWIDTH,10)/1e3||void 0),!f&&d["AVERAGE-BANDWIDTH"]&&(f=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let g=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,S;if(d.RESOLUTION){let[x,E]=d.RESOLUTION.split("x").map(A=>parseInt(A,10));x&&E&&(S={width:x,height:E})}let I=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:I,bandwidth:f,size:S,fps:g})}if(c){let d=(0,Sl.default)(c[1].split(",").map(g=>{let S=g.indexOf("=");return[g.substring(0,S),g.substring(S+1)]}).map(([g,S])=>[g,S.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=d.LANGUAGE,f=d.NAME;p&&h&&i.push({type:"internal",id:h,label:f,language:h,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},pR=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),vl=0,lS=async(a,e=a,t,r)=>{let s=await(await lt(a,r)).text();vl+=1;try{let{qualityManifests:n,textTracks:o}=dR(s,e);return{qualityManifests:n,textTracks:o}}catch(n){if(vl<=t.manifestRetryMaxCount)return await pR((0,Tn.getExponentialDelay)(vl-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),lS(a,e,t)}return{qualityManifests:[],textTracks:[]}},In=lS;var We=require("@vkontakte/videoplayer-shared/es2018");var En=class{constructor(e,t,r,i,s){this.subscription=new We.Subscription;this.abortControllers={destroy:new Pe,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new We.ValueSubject(null);this.getCurrentTime$=new We.ValueSubject(null);this.error$=new We.Subject;this.params={fetchManifestData:r,sourceUrl:i,downloadThreshold:s},this.subscription.add(e.pipe((0,We.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:r}=await this.fetchManifestData();await this.processTextTracks(r,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let r=await this.parseTextTracks(e,t);r&&(this.currentTextTrackData=r)}catch(r){this.error("processTextTracks",r)}}async parseTextTracks(e,t){for(let r of e){let i=new URL(r.url,t).toString(),n=await(await lt(i,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,i);return{textTrack:r,playlist:o}}}parsePlaylist(e,t){let r={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},i=e.split(`
|
|
126
|
+
`),s=0;for(let n=0;n<i.length;++n){let o=i[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=i[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(r.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!r.segmentStartTime){let d=new Date(r.vkStartTime).valueOf(),p=new Date(r.programDateTime).valueOf();r.segmentStartTime=p-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):r.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):r.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):r.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);r.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):r.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return r}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,We.isNonNullable)(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:r}=t[0].time,{to:i}=t[t.length-1].time;if(e<r||e>i)return;i-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 Pe;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:We.ErrorCategory.WTF,thrown:t,message:e})}};var Fa=class{constructor(e){this.subscription=new j.Subscription;this.videoState=new H("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new j.ValueSubject([]);this.liveOffset=new vr;this.manifestStartTime$=new j.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((i==null?void 0:i.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?k(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(i==null?void 0:i.to)==="paused"&&(k(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,j.assertNever)(t)}};var r;this.params=e,this.video=De(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:j.VideoQuality.INVARIANT,url:this.params.source.url};let t=(i,s)=>In(i,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 En(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Ke(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:s})=>{var n;i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:j.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,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:j.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Se(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new j.ValueSubject((r=e.source.maxSeekBackTime)!=null?r:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:j.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=Be(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.ended$,e.endedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(Ve(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ze(this.video,t.playbackRate,i.playbackRateState$,r)),s(Xe(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(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe((0,j.filterChanged)(),(0,j.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(i.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,j.isNonNullable)(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Se(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(i.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add((0,j.combine)({startTime:this.manifestStartTime$.pipe((0,j.filter)(j.isNonNullable)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe((0,j.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=(0,j.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,j.observableFrom)(["init"])).pipe((0,j.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}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),Ce(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if((0,j.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[p,h]of[[c,"mq"],[d,"lq"]]){let f=String(parseFloat(p||""));h&&p&&i.searchParams.set(h,f)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=xe(i.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),gl(n).then(c=>{var d;if(!(0,j.isNullable)(c))this.maxSeekBackTime$.next(c);else{let p=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();((0,j.isNullable)(p)||!isFinite(p))&<(n).then(h=>h.text()).then(h=>{var g;let f=(g=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:g[1];if(f){let S=new URL(f,n).toString();gl(S).then(I=>{(0,j.isNullable)(I)||this.maxSeekBackTime$.next(I)})}}).catch(()=>{})}})}playIfAllowed(){Oe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:j.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=xe(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 X=require("@vkontakte/videoplayer-shared/es2018");var qa=class{constructor(e){this.subscription=new X.Subscription;this.videoState=new H("stopped");this.manifests$=new X.ValueSubject([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?k(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,X.assertNever)(t)}};this.textTracksManager=new Ke(e.source.url),this.params=e,this.video=De(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:X.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(Se(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),In(xe(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:X.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&(!i||!i.from)&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:X.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},i=Be(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(i.timeUpdate$,e.position$),s(i.durationChange$,e.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.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,X.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(gt(this.video,t.isLooped,r)),this.subscription.add(Ve(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ze(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(i.loadedMetadata$.subscribe(()=>{var h;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,X.isNonNullable)(l.to)){let f=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let g=this.manifests$.getValue().find(S=>S.id===f);g&&(this.params.output.currentVideoTrack$.next(g),this.params.output.hostname$.next(Se(g.url)))}let d=this.params.desiredState.playbackRate.getState(),p=(h=this.params.output.element$.getValue())==null?void 0:h.playbackRate;if(d!==p){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(d),f.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe((0,X.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!X.clientChecker.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,X.merge)((0,X.fromEvent)(o,"addtrack"),(0,X.fromEvent)(o,"removetrack"),(0,X.fromEvent)(o,"change"),(0,X.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=(0,X.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,X.observableFrom)(["init"])).pipe((0,X.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ce(this.video)}prepare(){var s,n;let e=this.selectManifest();if((0,X.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){Oe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:X.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var cS=U(jr(),1),yl=U(ei(),1),dS=U(Kt(),1);var oe=require("@vkontakte/videoplayer-shared/es2018");var Ua=class{constructor(e){this.subscription=new oe.Subscription;this.videoState=new H("stopped");this.trackUrls={};this.textTracksManager=new Ke;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(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((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?k(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),k(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()):(r==null?void 0:r.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return(0,oe.assertNever)(e)}};this.params=e,this.video=De(e.container,e.tuning),this.params.output.element$.next(this.video),(0,cS.default)(this.params.source).reverse().forEach(([t,r],i)=>{let s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,yl.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,r=o=>{e.error$.next({id:"MpegProvider",category:oe.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},i=Be(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.timeUpdate$,e.position$),s(i.durationChange$,e.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.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,oe.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(gt(this.video,t.isLooped,r)),this.subscription.add(Ve(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ze(this.video,t.playbackRate,i.playbackRateState$,r)),s(Xe(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&(0,oe.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(c),p.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=(0,oe.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,oe.observableFrom)(["init"])).pipe((0,oe.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Ce(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;(0,oe.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,oe.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Da(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Se(t))}playIfAllowed(){Oe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:oe.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,c;this.params.output.autoVideoTrackLimits$.next(e);let t=d=>{this.params.output.currentVideoTrack$.next(d),this.params.desiredState.videoTrack.startTransitionTo(d)},r=d=>{let p=Jt(n,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:d,abrLogger:this.params.dependencies.abrLogger});t(p)},i=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,s=!!(e.max||e.min),n=(0,yl.default)(this.trackUrls).map(d=>d.track);if(!i||!s||Gi({limits:e,lowestAvailableQuality:(c=(0,dS.default)(n,-1))==null?void 0:c.quality,highestAvailableQuality:n[0].quality})){r();return}let o=e.max?(0,oe.isLowerOrEqual)(i,e.max):!0,u=e.min?(0,oe.isHigherOrEqual)(i,e.min):!0;o&&u||r(e)}};var le=require("@vkontakte/videoplayer-shared/es2018");var hS=require("@vkontakte/videoplayer-shared/es2018"),pS=["stun:videostun.mycdn.me:80"],hR=1e3,mR=3,Tl=()=>null,xn=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=Tl;this.externalStopCallback=Tl;this.externalErrorCallback=Tl;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:pS}]};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:hS.ErrorCategory.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(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),hR)}normalizeOptions(e={}){let t={stunServerList:pS,maxRetryNumber:mR,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ha=class{constructor(e){this.videoState=new H("stopped");this.maxSeekBackTime$=new le.ValueSubject(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(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"),k(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()):(r==null?void 0:r.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return(0,le.assertNever)(e)}};this.subscription=new le.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=De(e.container,e.tuning),this.liveStreamClient=new xn(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),Ce(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:le.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};(0,le.merge)(this.videoState.stateChangeStarted$.pipe((0,le.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,le.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=Be(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(i.timeUpdate$,e.liveTime$),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(Xe(this.video),this.params.output.elementVisible$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(i.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ve(this.video,t.volume,i.volumeState$,r)).add(i.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return(0,le.assertNever)(n.to)}},r)).add((0,le.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,le.observableFrom)(["init"])).pipe((0,le.debounce)(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Se(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:le.VideoQuality.INVARIANT}),this.video.srcObject=e,k(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:le.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Oe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(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}))}prepare(){this.liveStreamClient.connect()}};var ja=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};var y=require("@vkontakte/videoplayer-shared/es2018");var Dt=require("@vkontakte/videoplayer-shared/es2018"),mS=a=>new Dt.Observable(e=>{let t=new Dt.Subscription,r=a.desiredPlaybackState$.stateChangeStarted$.pipe((0,Dt.map)(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe((0,Dt.map)(({type:l})=>l!==void 0)),n=new Dt.Subject,o=0,u="unknown";return t.add(r.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(i.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var et=require("@vkontakte/videoplayer-shared/es2018");function fS(){return new(window.AudioContext||window.webkitAudioContext)}var bS=require("@vkontakte/videoplayer-shared/es2018");var Qa=class Qa{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new Pe;this.subscriptions=new et.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,et.filter)(s=>!!s.type),(0,et.once)()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){bS.clientChecker.isSafari&&e!=="MPEG"||this.subscriptions.add((0,et.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,et.filter)(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),(0,et.once)()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(r=>{r||this.destroy()}).catch(r=>{this.handleError(r),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,r=fS();this.audioContext=r;let i=r.createGain();if(this.gainNode=i,i.gain.value=t,i.connect(r.destination),r.state==="suspended"&&(await r.resume(),this.destroyController.signal.aborted))return!1;let s=r.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(i),!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:Qa.errorId,category:et.ErrorCategory.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Qa.errorId} exception`,thrown:e})}};Qa.errorId="VolumeMultiplierManager";var ci=Qa;var fR={chunkDuration:5e3,maxParallelRequests:5},Ga=class{constructor(e){this.current$=new y.ValueSubject({type:void 0});this.providerError$=new y.Subject;this.noAvailableProvidersError$=new y.Subject;this.volumeMultiplierError$=new y.Subject;this.providerOutput={position$:new y.ValueSubject(0),duration$:new y.ValueSubject(1/0),volume$:new y.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new y.ValueSubject([]),currentVideoStream$:new y.ValueSubject(void 0),availableVideoTracks$:new y.ValueSubject([]),currentVideoTrack$:new y.ValueSubject(void 0),availableAudioStreams$:new y.ValueSubject([]),currentAudioStream$:new y.ValueSubject(void 0),availableAudioTracks$:new y.ValueSubject([]),currentVideoSegmentLength$:new y.ValueSubject(0),currentAudioSegmentLength$:new y.ValueSubject(0),isAudioAvailable$:new y.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new y.ValueSubject(!1),autoVideoTrackLimits$:new y.ValueSubject(void 0),currentBuffer$:new y.ValueSubject(void 0),isBuffering$:new y.ValueSubject(!0),error$:new y.Subject,warning$:new y.Subject,willSeekEvent$:new y.Subject,soundProhibitedEvent$:new y.Subject,seekedEvent$:new y.Subject,loopedEvent$:new y.Subject,endedEvent$:new y.Subject,firstBytesEvent$:new y.Subject,loadedMetadataEvent$:new y.Subject,firstFrameEvent$:new y.Subject,canplay$:new y.Subject,isLive$:new y.ValueSubject(void 0),isLiveEnded$:new y.ValueSubject(null),isLowLatency$:new y.ValueSubject(!1),canChangePlaybackSpeed$:new y.ValueSubject(!0),liveTime$:new y.ValueSubject(void 0),liveBufferTime$:new y.ValueSubject(void 0),liveLatency$:new y.ValueSubject(void 0),availableTextTracks$:new y.ValueSubject([]),currentTextTrack$:new y.ValueSubject(void 0),hostname$:new y.ValueSubject(void 0),httpConnectionType$:new y.ValueSubject(void 0),httpConnectionReused$:new y.ValueSubject(void 0),inPiP$:new y.ValueSubject(!1),inFullscreen$:new y.ValueSubject(!1),element$:new y.ValueSubject(void 0),elementVisible$:new y.ValueSubject(!0),availableSources$:new y.ValueSubject(void 0),is3DVideo$:new y.ValueSubject(!1),playbackState$:new y.ValueSubject(""),getCurrentTime$:new y.ValueSubject(null)};this.subscription=new y.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=Sg([...Tg(this.params.tuning),...yg(this.params.tuning)],this.params.tuning).filter(l=>(0,y.isNonNullable)(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,Il.default)(i,l)),...t.filter(l=>(0,Il.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,y.flattenObject)(s)),this.screenFormatsIterator=new ja(s);let n=[...Uu(!0),...Uu(!1)];this.chromecastFormatsIterator=new ja(n.filter(l=>(0,y.isNonNullable)(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&ci.isSupported()&&(this.volumeMultiplierManager=new ci(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){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,y.isNullable)(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:y.ErrorCategory.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return(0,y.assertNever)(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,y.assertNonNullable)(o),new Oa({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new _a({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),ai||!this.params.tuning.useHlsJs?new qa({...n,source:o}):new Na({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Fa({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Ua({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Ob({...n,source:o,config:{...fR,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Ha({container:r,source:o,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,y.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,y.assertNonNullable)(o),new ji({connection:o,meta:s,container:r,source:t,format:e,desiredState:i,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return(0,y.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,y.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,y.assertNever)(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:r(e.url)}}return(0,vS.default)((0,gS.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new y.Subscription,t=!1,r=0;return e.add((0,y.merge)(this.providerOutput.error$.pipe((0,y.filter)(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),mS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,y.map)(i=>({id:`ProviderHangup:${i}`,category:y.ErrorCategory.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let i=this.params.desiredState.playbackState.transitionEnded$.pipe((0,y.filter)(({to:s})=>s==="playing"),(0,y.once)()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination,n={error:i,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=i.category===y.ErrorCategory.NETWORK,u=i.category===y.ErrorCategory.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=r<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c},c?(r++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",(0,y.flattenObject)(n))})),e}};var V=require("@vkontakte/videoplayer-shared/es2018");var bR=5e3,SS="one_video_throughput",yS="one_video_rtt",Ct=window.navigator.connection,TS=()=>{let a=Ct==null?void 0:Ct.downlink;if((0,V.isNonNullable)(a)&&a!==10)return a*1e3},IS=()=>{let a=Ct==null?void 0:Ct.rtt;if((0,V.isNonNullable)(a)&&a!==3e3)return a},ES=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},El=class a{constructor(e){this.subscription=new V.Subscription;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(SS)||(e.useBrowserEstimation?TS():void 0)||bR,r=(s=(i=a.load(yS))!=null?i:e.useBrowserEstimation?IS():void 0)!=null?s:0;if(this.throughput$=new V.ValueSubject(t),this.rtt$=new V.ValueSubject(r),this.rttAdjustedThroughput$=new V.ValueSubject(ES(t,r,e.rttPenaltyRequestSize)),this.throughput=Er.getSmoothedValue(t,-1,e),this.rtt=Er.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=TS();u&&this.throughput.next(u);let l=IS();(0,V.isNonNullable)(l)&&this.rtt.next(l)};Ct&&"onchange"in Ct&&this.subscription.add((0,V.fromEvent)(Ct,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{V.safeStorage.set(SS,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{V.safeStorage.set(yS,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,V.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,V.map)(({throughput:n,rtt:o})=>ES(n,o,e.rttPenaltyRequestSize)),(0,V.filter)(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=(0,V.now)(),i=new V.Subscription;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add((0,V.fromEvent)(e,"progress").pipe((0,V.once)()).subscribe(s=>{t=s.loaded,r=(0,V.now)()}));break;case 1:case 0:i.add((0,V.fromEvent)(e,"loadstart").subscribe(()=>{t=0,r=(0,V.now)()}));break}i.add((0,V.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,V.now)(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=(0,V.now)(),n=0,o=(0,V.now)(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(i,(0,V.now)()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=(0,V.now)();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=d.byteLength,s=(0,V.now)()}else n+=d.byteLength;o=(0,V.now)()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,V.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,V.now)()-o,this.concurrentDownloads.size),n=0,o=(0,V.now)());await(r==null?void 0:r.read().then(l,u))}};this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=V.safeStorage.get(e);if((0,V.isNonNullable)(t))return(r=parseInt(t,10))!=null?r:void 0}},xS=El;var Pr=require("@vkontakte/videoplayer-shared/es2018"),PS={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Pr.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Pr.VideoQuality.Q_720P,trafficSavingLimit:Pr.VideoQuality.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Pr.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationNoDataBeforeQualityDecrease:500,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1},wS=a=>{var e;return{...(0,Pr.fillWithDefault)(a,PS),configName:[...(e=a.configName)!=null?e:[],...PS.configName]}};var m=require("@vkontakte/videoplayer-shared/es2018");var Vt=require("@vkontakte/videoplayer-shared/es2018"),xl=({seekState:a,position$:e})=>(0,Vt.merge)(a.stateChangeEnded$.pipe((0,Vt.map)(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),(0,Vt.filter)(Vt.isNonNullable)),e.pipe((0,Vt.filter)(()=>a.getState().state==="none")));var AS=require("@vkontakte/videoplayer-shared/es2018"),kS=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return(0,AS.assertNonNullable)(e,`Wrong container or containerId {${a.container}}`),e};var Pn=require("@vkontakte/videoplayer-shared/es2018"),LS=(a,e,t,r)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe((0,Pn.filter)(i=>i.length>0),(0,Pn.once)()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Wa=class{constructor(e={configName:[]},t=m.Tracer.createRootTracer(!1)){this.subscription=new m.Subscription;this.logger=new m.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new m.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new H("stopped"),seekState:new H({state:"none"}),volume:new H({volume:1,muted:!1}),videoTrack:new H(void 0),videoStream:new H(void 0),audioStream:new H(void 0),autoVideoTrackSwitching:new H(!0),autoVideoTrackLimits:new H({}),isLooped:new H(!1),isLowLatency:new H(!1),playbackRate:new H(1),externalTextTracks:new H([]),internalTextTracks:new H([]),currentTextTrack:new H(void 0),textTrackCuesSettings:new H({}),cameraOrientation:new H({x:0,y:0})};this.info={playbackState$:new m.ValueSubject("stopped"),position$:new m.ValueSubject(0),duration$:new m.ValueSubject(1/0),muted$:new m.ValueSubject(!1),volume$:new m.ValueSubject(1),availableVideoStreams$:new m.ValueSubject([]),currentVideoStream$:new m.ValueSubject(void 0),availableQualities$:new m.ValueSubject([]),availableQualitiesFps$:new m.ValueSubject({}),currentQuality$:new m.ValueSubject(void 0),isAutoQualityEnabled$:new m.ValueSubject(!0),autoQualityLimitingAvailable$:new m.ValueSubject(!1),autoQualityLimits$:new m.ValueSubject({}),predefinedQualityLimitType$:new m.ValueSubject("unknown"),availableAudioStreams$:new m.ValueSubject([]),currentAudioStream$:new m.ValueSubject(void 0),availableAudioTracks$:new m.ValueSubject([]),isAudioAvailable$:new m.ValueSubject(!0),currentPlaybackRate$:new m.ValueSubject(1),currentBuffer$:new m.ValueSubject({start:0,end:0}),isBuffering$:new m.ValueSubject(!0),isStalled$:new m.ValueSubject(!1),isEnded$:new m.ValueSubject(!1),isLooped$:new m.ValueSubject(!1),isLive$:new m.ValueSubject(void 0),isLiveEnded$:new m.ValueSubject(null),canChangePlaybackSpeed$:new m.ValueSubject(void 0),atLiveEdge$:new m.ValueSubject(void 0),atLiveDurationEdge$:new m.ValueSubject(void 0),liveTime$:new m.ValueSubject(void 0),liveBufferTime$:new m.ValueSubject(void 0),liveLatency$:new m.ValueSubject(void 0),currentFormat$:new m.ValueSubject(void 0),availableTextTracks$:new m.ValueSubject([]),currentTextTrack$:new m.ValueSubject(void 0),throughputEstimation$:new m.ValueSubject(void 0),rttEstimation$:new m.ValueSubject(void 0),videoBitrate$:new m.ValueSubject(void 0),hostname$:new m.ValueSubject(void 0),httpConnectionType$:new m.ValueSubject(void 0),httpConnectionReused$:new m.ValueSubject(void 0),surface$:new m.ValueSubject("none"),chromecastState$:new m.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new m.ValueSubject(void 0),intrinsicVideoSize$:new m.ValueSubject(void 0),availableSources$:new m.ValueSubject(void 0),is3DVideo$:new m.ValueSubject(!1),currentVideoSegmentLength$:new m.ValueSubject(0),currentAudioSegmentLength$:new m.ValueSubject(0)};this.events={inited$:new m.Subject,ready$:new m.Subject,started$:new m.Subject,playing$:new m.Subject,paused$:new m.Subject,stopped$:new m.Subject,willStart$:new m.Subject,willResume$:new m.Subject,willPause$:new m.Subject,willStop$:new m.Subject,willDestruct$:new m.Subject,watchCoverageRecord$:new m.Subject,watchCoverageLive$:new m.Subject,managedError$:new m.Subject,fatalError$:new m.Subject,ended$:new m.Subject,looped$:new m.Subject,seeked$:new m.Subject,willSeek$:new m.Subject,autoplaySoundProhibited$:new m.Subject,firstBytes$:new m.Subject,loadedMetadata$:new m.Subject,firstFrame$:new m.Subject,canplay$:new m.Subject,log$:new m.Subject};this.experimental={element$:new m.ValueSubject(void 0),tuningConfigName$:new m.ValueSubject([]),enableDebugTelemetry$:new m.ValueSubject(!1),dumpTelemetry:yb,getCurrentTime$:new m.ValueSubject(null)};if(this.initLogs(),this.tuning=wS(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ms({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new xS(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new m.InternalsExposure("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,i,s)=>{let n=Reflect.get(r,i,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(h,f)=>{let g=typeof f;return(0,RS.default)(["number","string","boolean"],g)?f:f===null?null:`<${g}>`})),c=`Player.${String(i)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:m.ErrorCategory.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var i,s,n,o;this.config=e;let{container:t,...r}=e;return this.tracer.log("initVideo",(0,m.flattenObject)(r)),this.domContainer=kS(e),this.chromecastInitializer.contentId=(i=e.meta)==null?void 0:i.videoId,this.providerContainer=new Ga({sources:e.sources,meta:(s=e.meta)!=null?s:{},failoverHosts:(n=e.failoverHosts)!=null?n:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),(o=this.internalsExposure)==null||o.expose({config:e,logger:this.logger,tuning:this.tuning}),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Xi()?(this.tracer.log("request play from hidden tab"),(0,m.fromEvent)(document,"visibilitychange").pipe((0,m.once)()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue(),s=e;return e>=r&&!i&&(s=r-.2),this.tracer.log("seekTime",{duration:r,isLive:i,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){(0,m.assertNonNullable)(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe((0,m.filter)(r=>r.length>0),(0,m.once)()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",(0,m.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPredefinedQualityLimits(e){let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection,i;switch(e){case"high_quality":i={min:t,max:void 0};break;case"traffic_saving":i={max:r,min:void 0};break;default:i={max:void 0,min:void 0}}return this.setAutoQualityLimits(i),this}setPlaybackRate(e){var r;(0,m.assertNonNullable)(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",(0,m.flattenObject)(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return LS(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),r=this.desiredState.isLowLatency.getState();return!t||r===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let i=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:i.x+s.x,y:i.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if((0,m.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return(0,m.isNonNullable)(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,r;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((r=e==null?void 0:e.provider)!=null&&r.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:i})=>r||i||0,0),height:e.reduce((r,{height:i})=>r||i||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add((0,m.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,m.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next($u({limits:e,highQualityLimit:t,trafficSavingLimit:r}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,m.filter)(({from:e})=>e==="stopped"),(0,m.once)()).subscribe(()=>{this.initedAt=(0,m.now)(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",(0,m.flattenObject)(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:m.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe((0,m.once)()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",(0,m.flattenObject)(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,m.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,m.map)(n=>n.destination),(0,m.filterChanged)()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add((0,m.combine)({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe((0,m.map)(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>(0,m.isInvariantQuality)(u)?1:(0,m.isInvariantQuality)(l)?-1:(0,m.isHigher)(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe((0,m.filterChanged)()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe((0,m.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe((0,m.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,m.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,m.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,m.filterChanged)()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe((0,m.map)(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe((0,m.tap)(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add((0,m.combine)({hasLiveOffsetByPaused:(0,m.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,m.map)(n=>n.to),(0,m.filterChanged)(),(0,m.map)(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add((0,m.combine)({atLiveEdge:(0,m.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:xl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,m.map)(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),(0,m.filterChanged)(),(0,m.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,m.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,m.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,m.map)(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,m.filterChanged)(),(0,m.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,m.map)(n=>n.muted),(0,m.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,m.map)(n=>n.volume),(0,m.filterChanged)()).subscribe(this.info.volume$)).add(xl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,m.merge)(e.providerOutput.endedEvent$.pipe((0,m.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,m.mapTo)(!1))).pipe((0,m.filterChanged)()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe((0,m.map)(n=>({id:n?`No${n}`:"NoProviders",category:m.ErrorCategory.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe((0,m.once)(),(0,m.map)(n=>n!=null?n:(0,m.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,m.once)(),(0,m.map)(()=>(0,m.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,m.once)(),(0,m.map)(()=>(0,m.now)()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new m.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new m.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,m.filter)(({to:n})=>n==="playing"),(0,m.once)()).subscribe(()=>r.next(!1)));let i=0,s=(0,m.merge)(e.providerOutput.isBuffering$,t,r).pipe((0,m.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),(0,m.filterChanged)());this.subscription.add(s.subscribe(n=>{n?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))})),this.subscription.add((0,m.merge)(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add((0,m.merge)(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,m.map)(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new m.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,m.filterChanged)((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,m.filter)(r=>r.length>0),(0,m.once)()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i,s;let t;this.wasSetStartedQuality=!0;let r=(s=this.explicitInitialQuality)!=null?s:(i=this.desiredState.videoTrack.getState())==null?void 0:i.quality;r&&(t=e.find(({quality:n})=>n===r),t||this.setAutoQuality(!0)),t||(t=Jt(e,{container:this.domContainer.getBoundingClientRect(),estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add((0,m.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,m.map)(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;(0,m.assertNonNullable)(this.providerContainer),(0,m.assertNonNullable)(e),Sb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>vb(r)),this.providerContainer.current$.subscribe(({type:r})=>Qi("provider",r)),e.duration$.subscribe(r=>Qi("duration",r)),e.availableVideoTracks$.pipe((0,m.filter)(r=>!!r.length),(0,m.once)()).subscribe(r=>Qi("tracks",r)),this.events.fatalError$.subscribe(new Le("fatalError")),this.events.managedError$.subscribe(new Le("managedError")),e.position$.subscribe(new Le("position")),e.currentVideoTrack$.pipe((0,m.map)(r=>r==null?void 0:r.quality)).subscribe(new Le("quality")),this.info.currentBuffer$.subscribe(new Le("buffer")),e.isBuffering$.subscribe(new Le("isBuffering"))].forEach(r=>this.subscription.add(r)),Qi("codecs",vg())}initTracerSubscription(){let e=(0,m.getTraceSubscriptionMethod)(this.tracer.log.bind(this.tracer)),t=(0,m.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe((0,m.filterChanged)()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add((0,m.combine)({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe((0,m.filter)(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),(0,m.filterChanged)((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,m.filter)(r=>r>0),(0,m.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,m.filter)(r=>r>0),(0,m.filterChanged)()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add((0,m.combine)({currentBuffer:this.info.currentBuffer$.pipe((0,m.filter)(r=>r.end>0),(0,m.filterChanged)((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe((0,m.filterChanged)())}).pipe((0,m.throttle)(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe((0,m.filterChanged)()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe((0,m.filterChanged)()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe((0,m.filterChanged)()).subscribe(e("canChangePlaybackSpeed"))).add((0,m.combine)({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe((0,m.filter)(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),(0,m.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,m.filterChanged)(),(0,m.filter)(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,m.filterChanged)(),(0,m.filter)(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe((0,m.filterChanged)()).subscribe(e("muted"))).add(this.info.volume$.pipe((0,m.filterChanged)()).subscribe(e("volume"))).add(this.info.isEnded$.pipe((0,m.filterChanged)(),(0,m.filter)(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add((0,m.combine)({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe((0,m.filter)(({throughputEstimation:r,rtt:i})=>!!r&&!!i),(0,m.throttle)(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe((0,m.filterChanged)(),(0,m.filter)(r=>r===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:m.ErrorCategory.DOM,message:String(i)})})};this.subscription.add((0,m.merge)((0,m.fromEvent)(document,"visibilitychange"),(0,m.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);i&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(i=>i.quality===t);this.tracer.log("setVideoTrackIdByQuality",(0,m.flattenObject)({quality:t,availableTracks:(0,m.flattenObject)(e),track:(0,m.flattenObject)(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};var Tt=require("@vkontakte/videoplayer-shared/es2018"),gR=`@vkontakte/videoplayer-core@${$n}`;
|